<?php
/**
 * Agentic Square - Client Premium Interactive Workspace Dashboard Infrastructure
 * Path: client/client-dashboard.php
 */

require_once __DIR__ . '/../config/config.php';

// SECURITY ACCESS GUARD RULE: If not logged in, boot out.
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

// AUTOMATIC CLIENT ESCALATION: If the role is explicitly seller or admin, bounce them out of this specific sub-view.
// If they are anything else (e.g., 'client', empty or basic user status flags), they safely fall back into client clearance.
if ($_SESSION['user_role'] === 'seller' || $_SESSION['user_role'] === 'admin') {
    header('Location: ../login.php');
    exit;
}

require_once __DIR__ . '/../sections/header.php';
?>

<body class="bg-nftDark text-white antialiased overflow-x-hidden">

    <?php include_once __DIR__ . '/client-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-16 px-4 sm:px-6 lg:px-8">
        <div class="max-w-7xl mx-auto space-y-10">
            
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 border-b border-slate-900/60 pb-6">
                <div>
                    <span class="text-xs font-bold tracking-widest text-nftAccentCyan uppercase block mb-1">// End-User Client Environment Workspace</span>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">Client Hub Overview</h1>
                    <p class="text-sm text-nftTextGray mt-1">Welcome back, <span class="text-white font-semibold"><?php echo htmlspecialchars($_SESSION['user_name'], ENT_QUOTES, 'UTF-8'); ?></span>! Review code acquisitions and package downloads.</p>
                </div>
            </div>

            <?php include_once __DIR__ . '/client-card.php'; ?>

            <?php include_once __DIR__ . '/item-table.php'; ?>

        </div>
    </main>

    <div id="reviewReviewModalFrame" class="fixed inset-0 z-50 hidden bg-slate-950/80 backdrop-blur-md flex items-center justify-center p-4 transition-all duration-300">
        <div class="glass-card w-full max-w-lg rounded-2xl border border-slate-800 bg-slate-900 p-6 space-y-6 relative shadow-2xl">
            <div class="flex items-center justify-between border-b border-slate-800/80 pb-4">
                <div>
                    <h4 class="text-md font-bold text-white tracking-wide">Write a Product Review</h4>
                    <p id="targetReviewItemTitleDisplay" class="text-xs text-nftAccentCyan font-mono mt-0.5">// Loading Index Target Context...</p>
                </div>
                <button type="button" onclick="closeReviewModalWindow()" class="text-slate-400 hover:text-white transition-colors text-sm">
                    <i class="fa-solid fa-xmark text-lg"></i>
                </button>
            </div>

            <form id="asyncFormReviewSubmissionHandler" class="space-y-4">
                <input type="hidden" name="order_id" id="hidden_order_id_field">
                <input type="hidden" name="item_id" id="hidden_item_id_field">
                <input type="hidden" name="seller_id" id="hidden_seller_id_field">

                <div class="space-y-2">
                    <label class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">Assign Quality Rating Grade</label>
                    <div class="flex items-center gap-2" id="starSelectionInteractiveContainer">
                        <?php for($i = 1; $i <= 5; $i++): ?>
                            <button type="button" data-star-value="<?php echo $i; ?>" class="text-xl text-slate-700 hover:text-amber-400 transition-all transform hover:scale-110 star-selector-btn">
                                <i class="fa-solid fa-star"></i>
                            </button>
                        <?php endfor; ?>
                    </div>
                    <input type="hidden" name="rating" id="calculated_rating_numerical_value" value="0">
                </div>

                <div class="space-y-2">
                    <label for="input_review_text_area" class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">Detailed Operational Feedback</label>
                    <textarea name="review_text" id="input_review_text_area" rows="4" required placeholder="Please provide technical or performance insights concerning this script package..." class="w-full bg-slate-950 text-xs text-slate-200 p-3.5 rounded-xl border border-slate-800 focus:outline-none focus:border-nftAccentPurple font-medium placeholder-slate-600 transition-colors resize-none"></textarea>
                </div>

                <div class="flex items-center justify-end gap-3 pt-2">
                    <button type="button" onclick="closeReviewModalWindow()" class="px-5 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider text-slate-400 bg-slate-950 border border-slate-800 hover:text-white transition-all">Cancel</button>
                    <button type="submit" class="px-5 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider text-slate-950 bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple shadow-md font-black hover:opacity-90 transition-all">Submit Evaluation</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const modalFrame = document.getElementById('reviewReviewModalFrame');
        const starButtons = document.querySelectorAll('.star-selector-btn');
        const hiddenRatingInput = document.getElementById('calculated_rating_numerical_value');

        function applyStarStateHighlight(rating) {
            starButtons.forEach(btn => {
                const val = parseInt(btn.getAttribute('data-star-value'));
                if (val <= rating) {
                    btn.classList.remove('text-slate-700');
                    btn.classList.add('text-amber-400');
                } else {
                    btn.classList.remove('text-amber-400');
                    btn.classList.add('text-slate-700');
                }
            });
        }

        starButtons.forEach(button => {
            button.addEventListener('click', () => {
                const selectedVal = parseInt(button.getAttribute('data-star-value'));
                hiddenRatingInput.value = selectedVal;
                applyStarStateHighlight(selectedVal);
            });
        });

        function initializeReviewModal(contextPayload) {
            document.getElementById('hidden_order_id_field').value = contextPayload.order_id;
            document.getElementById('hidden_item_id_field').value = contextPayload.item_id;
            document.getElementById('hidden_seller_id_field').value = contextPayload.seller_id;
            document.getElementById('targetReviewItemTitleDisplay').textContent = `Evaluation: ${contextPayload.item_name}`;
            
            hiddenRatingInput.value = "0";
            document.getElementById('input_review_text_area').value = "";
            applyStarStateHighlight(0);

            modalFrame.classList.remove('hidden');
        }

        function closeReviewModalWindow() {
            modalFrame.classList.add('hidden');
        }

        document.getElementById('asyncFormReviewSubmissionHandler').addEventListener('submit', function(e) {
            e.preventDefault();
            
            if(hiddenRatingInput.value === "0") {
                alert("Please select a star rating value before submitting.");
                return;
            }

            const formData = new FormData(this);

            fetch('review-endpoint.php', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if(data.success) {
                    alert(data.message);
                    closeReviewModalWindow();
                    window.location.reload();
                } else {
                    alert(`Error: ${data.message}`);
                }
            })
            .catch(err => {
                console.error(err);
                alert("System error encountered. Review submission failed.");
            });
        });
    </script>
</body>
</html>