<?php
/**
 * Agentic Square - Client Orders & Operational Asset Matrix Component
 * Path: client/item-table.php
 */

if (!isset($pdo) || !isset($_SESSION['user_id'])) {
    die('Architecture Context Violation: Direct sub-module access block.');
}

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

try {
    $tableQuery = "
        SELECT 
            o.id AS order_id,
            o.item_id,
            o.item_name,
            o.price,
            o.payment_status,
            o.created_at AS order_date,
            o.seller_id,
            s.seller_name,
            i.item_slug,
            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 = ?
        ORDER BY o.id DESC
    ";

    $tableStmt = $pdo->prepare($tableQuery);
    $tableStmt->execute([$client_user_id]);
    $ordersRecords = $tableStmt->fetchAll();
} catch (\PDOException $e) {
    echo '<div class="bg-rose-500/10 border border-rose-500/20 text-rose-400 p-4 rounded-xl text-xs font-mono">Table Layer Pipeline Execution Fault: ' . htmlspecialchars($e->getMessage()) . '</div>';
    $ordersRecords = [];
}
?>

<div class="glass-card rounded-2xl border border-slate-800/80 overflow-hidden bg-slate-950/20">
    <div class="px-6 py-5 border-b border-slate-900/60 flex items-center justify-between">
        <div>
            <h3 class="text-base font-bold text-white tracking-wide">Acquisition Index Assets Ledger</h3>
            <p class="text-xs text-nftTextGray mt-0.5">Track your digital asset settlements, file packaging, and code validation reviews.</p>
        </div>
    </div>

    <div class="overflow-x-auto">
        <table class="w-full text-left border-collapse">
            <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">Ordered Date</th>
                    <th class="px-6 py-4">Item Name</th>
                    <th class="px-6 py-4">Seller Name</th>
                    <th class="px-6 py-4">Price</th>
                    <th class="px-6 py-4">Payment Status</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">
                <?php if (empty($ordersRecords)): ?>
                    <tr>
                        <td colspan="6" class="px-6 py-10 text-center text-nftTextGray font-mono">
                            No functional historical acquisition records mapped to this account frame.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($ordersRecords as $record): ?>
                        <?php
                            $downloadUrl = !empty($record['item_zip_file']) ? media_url($record['item_zip_file']) : '';
                            $itemDetailsUrl = !empty($record['item_slug'])
                                ? item_url([
                                    'id' => (int)$record['item_id'],
                                    'item_slug' => (string)$record['item_slug'],
                                ])
                                : '';
                        ?>
	                        <tr class="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 font-bold text-white">
                                <?php if ($itemDetailsUrl !== ''): ?>
                                    <a href="<?php echo htmlspecialchars($itemDetailsUrl, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener" class="hover:text-nftAccentCyan transition-colors">
                                        <?php echo htmlspecialchars($record['item_name']); ?>
                                    </a>
                                <?php else: ?>
                                    <?php echo htmlspecialchars($record['item_name']); ?>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 text-nftAccentCyan">
                                <?php echo htmlspecialchars($record['seller_name'] ?? 'System Core Platform'); ?>
                            </td>
                            <td class="px-6 py-4 font-mono font-bold text-white">
                                <?php echo htmlspecialchars(format_currency($record['price']), ENT_QUOTES, 'UTF-8'); ?>
                            </td>
                            <td class="px-6 py-4">
                                <?php if ($record['payment_status'] === 'Paid'): ?>
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
                                        <span class="w-1 h-1 rounded-full bg-emerald-400"></span> Paid
                                    </span>
                                <?php else: ?>
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider bg-amber-500/10 text-amber-400 border border-amber-500/20">
                                        <span class="w-1 h-1 rounded-full bg-amber-400"></span> <?php echo htmlspecialchars($record['payment_status']); ?>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 text-right space-x-2">
                                <?php if ($record['payment_status'] === 'Paid'): ?>
                                        <?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">
	                                            <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 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; ?>
                                <?php else: ?>
	                                    <a href="<?php echo htmlspecialchars(app_url('buy-now.php?item_id=' . (int)$record['item_id']), ENT_QUOTES, 'UTF-8'); ?>" class="inline-flex items-center justify-center px-3 py-1.5 rounded-lg bg-gradient-to-r from-amber-500 to-orange-600 text-white text-[11px] font-bold tracking-wide transition-all hover:opacity-90 shadow-md">
                                        <i class="fa-solid fa-credit-card mr-1.5"></i> Pay Now
                                    </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<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() {
    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');
    
    // Toast UI targeting states
    const toastElement = document.getElementById('portalToastNotification');
    const toastIcon = document.getElementById('toastIconContainer');
    const toastMsg = document.getElementById('toastContentMessage');

    // 1. Toast Generator Core System
    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;';
        }

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

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

    // 2. Core Event Handler Map for Opening trigger items
    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';
        });
    });

    // 3. Dynamic star layout color system tracker
    function applyStarStateHighlight(rating) {
        starButtons.forEach(btn => {
            const val = parseInt(btn.getAttribute('data-star-value'));
            if (val <= rating) {
                btn.style.color = '#fbbf24'; 
            } else {
                btn.style.color = '#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);

    // 4. Submit with Loading Interceptor Framework
    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;
        }

        // Switch button to Loading state UI pipeline
        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();
                // Graceful delay for user to read toast before page reload occurs
                setTimeout(() => {
                    window.location.reload();
                }, 1500);
            } else {
                triggerSystemToast(`Submission Error: ${data.message}`, "error");
                // Restore button state
                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>
/* Pure CSS spinner animation if not compiled globally */
@keyframes spin {
    to { transform: rotate(360deg); }
}
.animate-spin {
    animation: spin 1s linear infinite;
}
</style>
