<?php
/**
 * Agentic Square - Client Asset Downloads Vault & Verification Core
 * Path: client/downloads.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.
$current_user_role = $_SESSION['user_role'] ?? 'client';
if ($current_user_role === 'seller' || $current_user_role === 'admin') {
    header('Location: ../login.php');
    exit;
}

$client_user_id = (int)$_SESSION['user_id'];

try {
    // Pipeline Query: Extracts ONLY paid status order mappings assigned to this client context
    $downloadQuery = "
        SELECT 
            o.id AS order_id,
            o.item_id,
            o.item_name,
            o.price,
            o.created_at AS order_date,
            o.seller_id,
            s.seller_name,
            i.item_zip_file,
            r.id AS review_id
        FROM orders o
        LEFT JOIN sellers s ON o.seller_id = s.user_id
        LEFT JOIN items i ON o.item_id = i.id
        LEFT JOIN reviews r ON o.id = r.order_id
        WHERE o.user_id = ? AND o.payment_status = 'Paid'
        ORDER BY o.id DESC
    ";

    $downloadStmt = $pdo->prepare($downloadQuery);
    $downloadStmt->execute([$client_user_id]);
    $downloadRecords = $downloadStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
    $downloadRecords = [];
    $errorPipelineMessage = $e->getMessage();
}

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-8">
            
            <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">// Digital Storage Safe Box</span>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">Your Downloads Vault</h1>
                    <p class="text-sm text-nftTextGray mt-1">Access, download, and review your purchased production source packages instantly.</p>
                </div>
                
                <div class="relative max-w-xs w-full">
                    <span class="absolute inset-y-0 left-0 flex items-center pl-3.5 pointer-events-none text-slate-500 text-xs">
                        <i class="fa-solid fa-magnifying-glass"></i>
                    </span>
                    <input type="text" id="vaultRealTimeSearchBox" placeholder="Search item or seller name..." class="w-full bg-slate-950/60 text-xs text-slate-200 pl-10 pr-4 py-3 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan font-medium placeholder-slate-600 transition-all shadow-inner">
                </div>
            </div>

            <?php if (isset($errorPipelineMessage)): ?>
                <div class="bg-rose-500/10 border border-rose-500/20 text-rose-400 p-4 rounded-xl text-xs font-mono">
                    System Pipeline Exception: <?php echo htmlspecialchars($errorPipelineMessage); ?>
                </div>
            <?php endif; ?>

            <div class="glass-card rounded-2xl border border-slate-800/80 overflow-hidden bg-slate-950/20">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse" id="vaultDownloadsRegistryTable">
                        <thead>
                            <tr class="border-b border-slate-900 text-[10px] font-bold uppercase tracking-widest text-nftTextGray bg-slate-950/40">
                                <th class="px-6 py-4">Acquisition Date</th>
                                <th class="px-6 py-4">Item Name / Asset ID</th>
                                <th class="px-6 py-4">Author Channel</th>
                                <th class="px-6 py-4">Settled Value</th>
                                <th class="px-6 py-4 text-right">Operational Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-900/40 text-xs text-slate-300 font-medium" id="vaultTableRecordsBody">
                            <?php if (empty($downloadRecords)): ?>
                                <tr class="no-records-fallback-row">
                                    <td colspan="5" class="px-6 py-14 text-center text-nftTextGray font-mono">
                                        No settled asset distributions maps linked into this workspace index.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($downloadRecords as $record): ?>
                                    <?php $downloadUrl = !empty($record['item_zip_file']) ? media_url($record['item_zip_file']) : ''; ?>
	                                    <tr class="vault-data-row hover:bg-slate-900/20 transition-all">
                                        <td class="px-6 py-4 font-mono text-[11px] text-slate-400">
                                            <?php echo date('Y-m-d H:i', strtotime($record['order_date'])); ?>
                                        </td>
                                        <td class="px-6 py-4">
                                            <div class="font-bold text-white tracking-wide search-target-item"><?php echo htmlspecialchars($record['item_name']); ?></div>
                                            <span class="text-[10px] font-mono text-slate-500 block mt-0.5">ID: #AS-<?php echo str_pad($record['item_id'], 5, '0', STR_PAD_LEFT); ?></span>
                                        </td>
                                        <td class="px-6 py-4 text-nftAccentCyan font-semibold search-target-seller">
                                            <?php echo htmlspecialchars($record['seller_name'] ?? 'System Core Platform'); ?>
                                        </td>
                                        <td class="px-6 py-4 font-mono font-bold text-emerald-400">
                                            <?php echo htmlspecialchars(format_currency($record['price']), ENT_QUOTES, 'UTF-8'); ?>
                                        </td>
                                        <td class="px-6 py-4 text-right space-x-2">
                                                <?php if ($downloadUrl !== ''): ?>
	                                                <a href="<?php echo htmlspecialchars($downloadUrl, ENT_QUOTES, 'UTF-8'); ?>" download class="inline-flex items-center justify-center px-3 py-1.5 rounded-lg bg-nftAccentCyan text-slate-950 text-[11px] font-bold tracking-wide transition-all hover:opacity-90 shadow-md">
	                                                    <i class="fa-solid fa-download mr-1.5"></i> Download Item
	                                                </a>
                                                <?php else: ?>
                                                    <span class="inline-flex items-center justify-center px-3 py-1.5 rounded-lg bg-slate-900/70 border border-slate-800 text-slate-500 text-[11px] font-bold tracking-wide">
                                                        <i class="fa-solid fa-ban mr-1.5"></i> File Missing
                                                    </span>
                                                <?php endif; ?>

                                            <?php if ($record['review_id']): ?>
                                                <span class="inline-flex items-center text-[11px] font-bold uppercase text-nftTextGray font-mono bg-slate-900/60 border border-slate-800 px-3 py-1.5 rounded-lg">
                                                    <i class="fa-solid fa-square-poll-horizontal text-nftAccentPurple mr-1.5"></i> Reviewed
                                                </span>
                                            <?php else: ?>
                                                <button type="button"
                                                    data-order-id="<?php echo (int)$record['order_id']; ?>"
                                                    data-item-id="<?php echo (int)$record['item_id']; ?>"
                                                    data-item-name="<?php echo htmlspecialchars($record['item_name'], ENT_QUOTES, 'UTF-8'); ?>"
                                                    data-seller-id="<?php echo (int)$record['seller_id']; ?>"
                                                    class="open-review-modal-btn inline-flex items-center justify-center px-3 py-1.5 rounded-lg border border-nftAccentPurple/40 bg-nftAccentPurple/10 text-nftAccentPurple text-[11px] font-bold tracking-wide transition-all hover:bg-nftAccentPurple hover:text-white">
                                                    <i class="fa-solid fa-star mr-1.5 text-[10px]"></i> Review Asset
                                                </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div id="vaultPaginationControlPanel" class="px-6 py-4 bg-slate-950/40 border-t border-slate-900/60 flex flex-col sm:flex-row items-center justify-between gap-4">
                    <span id="paginationSummaryMetricsInfo" class="text-xs text-nftTextGray font-medium"></span>
                    <div class="flex items-center gap-1.5" id="paginationControlsButtonsGroup"></div>
                </div>
            </div>

        </div>
    </main>

    <div id="reviewReviewModalFrame" class="fixed inset-0 z-[9999] hidden bg-black/80 backdrop-blur-md flex items-center justify-center p-4" style="display: none;">
        <div class="bg-slate-900 border border-slate-800 w-full max-w-lg rounded-2xl 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 context...</p>
                </div>
                <button type="button" id="closeModalCrossButton" class="text-slate-400 hover:text-white transition-colors text-sm p-1">
                    &#x2715;
                </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-2xl text-slate-700 hover:text-amber-400 transition-all transform hover:scale-110 star-selector-btn">
                                &#9733;
                            </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 your feedback insights here..." 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" id="closeModalCancelButton" 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" id="submitReviewFormButton" class="inline-flex items-center gap-2 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">
                        <span id="submitBtnText">Submit Evaluation</span>
                        <span id="submitBtnSpinner" class="hidden w-4 h-4 border-2 border-slate-950 border-t-transparent rounded-full animate-spin"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div id="portalToastNotification" class="fixed top-5 right-5 z-[10000] hidden transform translate-y-[-20px] opacity-0 transition-all duration-300 flex items-center p-4 w-full max-w-xs text-slate-300 bg-slate-900 border rounded-xl shadow-2xl" role="alert">
        <div id="toastIconContainer" class="inline-flex items-center justify-center flex-shrink-0 w-8 h-8 rounded-lg"></div>
        <div id="toastContentMessage" class="ms-3 text-xs font-bold tracking-wide"></div>
    </div>

    <script>
    document.addEventListener("DOMContentLoaded", function() {
        // Data Arrays Matrix Sources
        const searchInput = document.getElementById('vaultRealTimeSearchBox');
        const allDataRows = Array.from(document.querySelectorAll('.vault-data-row'));
        const tableBody = document.getElementById('vaultTableRecordsBody');
        const paginationSummary = document.getElementById('paginationSummaryMetricsInfo');
        const paginationControls = document.getElementById('paginationControlsButtonsGroup');
        
        let filteredDataRows = [...allDataRows];
        const rowsPerPageGrid = 10; // Change this variable to expand records limits per table page frame
        let currentActivePage = 1;

        // 1. Pagination State Computation Engine
        function layoutActivePageSegment() {
            const totalItemsCount = filteredDataRows.length;
            
            // Remove existing visibility settings
            allDataRows.forEach(row => row.style.display = 'none');
            
            // Handle complete dynamic zero search results matching cases cleanly
            const dynamicFallback = tableBody.querySelector('.no-records-fallback-row');
            if (dynamicFallback) dynamicFallback.remove();

            if (totalItemsCount === 0) {
                const fallbackHtml = `
                    <tr class="no-records-fallback-row">
                        <td colspan="5" class="px-6 py-14 text-center text-nftTextGray font-mono">
                            No assets discovered matching requested structural query attributes.
                        </td>
                    </tr>`;
                tableBody.insertAdjacentHTML('beforeend', fallbackHtml);
                paginationSummary.textContent = "Showing 0 of 0 entries";
                paginationControls.innerHTML = '';
                return;
            }

            const totalPagesCalculated = Math.ceil(totalItemsCount / rowsPerPageGrid);
            if (currentActivePage > totalPagesCalculated) currentActivePage = totalPagesCalculated;
            if (currentActivePage < 1) currentActivePage = 1;

            const operationalStartIndex = (currentActivePage - 1) * rowsPerPageGrid;
            const operationalEndIndex = Math.min(operationalStartIndex + rowsPerPageGrid, totalItemsCount);

            // Reactivate current visibility block matrices
            for (let i = operationalStartIndex; i < operationalEndIndex; i++) {
                filteredDataRows[i].style.display = '';
            }

            paginationSummary.textContent = `Showing ${operationalStartIndex + 1} to ${operationalEndIndex} of ${totalItemsCount} verified entries`;
            generateControlsButtonsMatrix(totalPagesCalculated);
        }

        // 2. Build Interactive Navigation Pagination Tabs Layout Block
        function generateControlsButtonsMatrix(totalPages) {
            paginationControls.innerHTML = '';
            if (totalPages <= 1) return;

            // Generate Navigational Trigger Block Helpers
            for (let pageIdx = 1; pageIdx <= totalPages; pageIdx++) {
                const btn = document.createElement('button');
                btn.type = 'button';
                btn.textContent = pageIdx;
                btn.className = "px-3 py-1.5 rounded-lg text-xs font-mono font-bold transition-all ";
                
                if (pageIdx === currentActivePage) {
                    btn.className += "bg-gradient-to-r from-nftAccentCyan/20 to-nftAccentPurple/20 border border-nftAccentCyan text-white shadow-md shadow-nftAccentCyan/10";
                } else {
                    btn.className += "bg-slate-950 border border-slate-900 text-slate-400 hover:text-white hover:bg-slate-900";
                }

                btn.addEventListener('click', function() {
                    currentActivePage = pageIdx;
                    layoutActivePageSegment();
                });
                paginationControls.appendChild(btn);
            }
        }

        // 3. Connect Real-time Search Matrix Operations Filter Interceptor
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                const normalizedFilterQuery = this.value.toLowerCase().trim();
                
                filteredDataRows = allDataRows.filter(row => {
                    const itemNameContent = row.querySelector('.search-target-item').textContent.toLowerCase();
                    const sellerNameContent = row.querySelector('.search-target-seller').textContent.toLowerCase();
                    return itemNameContent.includes(normalizedFilterQuery) || sellerNameContent.includes(normalizedFilterQuery);
                });

                currentActivePage = 1; // Always reset map layer to initial page view stack framing on adjustments
                layoutActivePageSegment();
            });
        }

        // Initialize display configuration state on initial layout loading completion
        layoutActivePageSegment();

        // ==========================================
        // DYNAMIC REVIEW ACTION CONTROLS INTEGRATION
        // ==========================================
        const modalFrame = document.getElementById('reviewReviewModalFrame');
        const starButtons = document.querySelectorAll('.star-selector-btn');
        const hiddenRatingInput = document.getElementById('calculated_rating_numerical_value');
        
        const submitBtn = document.getElementById('submitReviewFormButton');
        const submitText = document.getElementById('submitBtnText');
        const submitSpinner = document.getElementById('submitBtnSpinner');
        
        const toastElement = document.getElementById('portalToastNotification');
        const toastIcon = document.getElementById('toastIconContainer');
        const toastMsg = document.getElementById('toastContentMessage');

        function triggerSystemToast(message, type = 'success') {
            toastMsg.textContent = message;
            if (type === 'success') {
                toastElement.style.borderColor = 'rgba(16, 185, 129, 0.3)';
                toastIcon.style.backgroundColor = 'rgba(16, 185, 129, 0.1)';
                toastIcon.style.color = '#10b981';
                toastIcon.innerHTML = '&#x2713;'; 
            } else {
                toastElement.style.borderColor = 'rgba(239, 68, 68, 0.3)';
                toastIcon.style.backgroundColor = 'rgba(239, 68, 68, 0.1)';
                toastIcon.style.color = '#ef4444';
                toastIcon.innerHTML = '&#x26A0;';
            }

            toastElement.classList.remove('hidden');
            setTimeout(() => {
                toastElement.style.opacity = '1';
                toastElement.style.transform = 'translateY(0)';
            }, 10);

            setTimeout(() => {
                toastElement.style.opacity = '0';
                toastElement.style.transform = 'translateY(-20px)';
                setTimeout(() => { toastElement.classList.add('hidden'); }, 300);
            }, 4000);
        }

        document.querySelectorAll('.open-review-modal-btn').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                
                const orderId = this.getAttribute('data-order-id');
                const itemId = this.getAttribute('data-item-id');
                const itemName = this.getAttribute('data-item-name');
                const sellerId = this.getAttribute('data-seller-id');

                document.getElementById('hidden_order_id_field').value = orderId;
                document.getElementById('hidden_item_id_field').value = itemId;
                document.getElementById('hidden_seller_id_field').value = sellerId;
                document.getElementById('targetReviewItemTitleDisplay').textContent = "Evaluation Scope: " + itemName;
                
                hiddenRatingInput.value = "0";
                document.getElementById('input_review_text_area').value = "";
                applyStarStateHighlight(0);

                modalFrame.classList.remove('hidden');
                modalFrame.style.display = 'flex';
            });
        });

        function applyStarStateHighlight(rating) {
            starButtons.forEach(btn => {
                const val = parseInt(btn.getAttribute('data-star-value'));
                btn.style.color = (val <= rating) ? '#fbbf24' : '#334155';
            });
        }

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

        function closeWindow() {
            modalFrame.classList.add('hidden');
            modalFrame.style.display = 'none';
        }

        document.getElementById('closeModalCrossButton').addEventListener('click', closeWindow);
        document.getElementById('closeModalCancelButton').addEventListener('click', closeWindow);

        document.getElementById('asyncFormReviewSubmissionHandler').addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (hiddenRatingInput.value === "0") {
                triggerSystemToast("Please select a star rating level before logging your record.", "error");
                return;
            }

            submitBtn.disabled = true;
            submitText.textContent = "Processing...";
            submitSpinner.classList.remove('hidden');

            const formData = new FormData(this);

            fetch('review-endpoint.php', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    triggerSystemToast(data.message, "success");
                    closeWindow();
                    setTimeout(() => { window.location.reload(); }, 1500);
                } else {
                    triggerSystemToast(`Submission Error: ${data.message}`, "error");
                    submitBtn.disabled = false;
                    submitText.textContent = "Submit Evaluation";
                    submitSpinner.classList.add('hidden');
                }
            })
            .catch(err => {
                console.error(err);
                triggerSystemToast("Interconnect Error: Review processing execution failed.", "error");
                submitBtn.disabled = false;
                submitText.textContent = "Submit Evaluation";
                submitSpinner.classList.add('hidden');
            });
        });
    });
    </script>

    <style>
    @keyframes spin { to { transform: rotate(360deg); } }
    .animate-spin { animation: spin 1s linear infinite; }
    </style>
</body>
</html>
