<?php
require_once 'db/config.php';
$settings = [];
try {
    $rows = db()->query("SELECT * FROM settings")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $r) {
        $settings[$r['key']] = $r['value'];
    }
} catch (Exception $e) {
    // Fallback if DB fails
}

$title = $settings['customer_display_greeting_title'] ?? 'Welcome';
$subtitle = $settings['customer_display_greeting_text'] ?? 'We are ready to serve you.';
$slides = [];
if (!empty($settings['display_slide_1'])) $slides[] = $settings['display_slide_1'];
if (!empty($settings['display_slide_2'])) $slides[] = $settings['display_slide_2'];
if (!empty($settings['display_slide_3'])) $slides[] = $settings['display_slide_3'];

// Fallbacks
if (empty($slides)) {
    $slides = [
        'https://images.unsplash.com/photo-1441986300917-64674bd600d8?q=80&w=1920&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1472851294608-415170d4e897?q=80&w=1920&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1556742049-0cfed4f7a07d?q=80&w=1920&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1528698827591-e19ccd7bc23d?q=80&w=1920&auto=format&fit=crop'
    ];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Display</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="assets/css/custom.css?v=<?= time() ?>">
    <style>
        body {
            background-color: var(--bg);
            color: var(--text);
            height: 100vh;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            transition: background-color 0.3s, color 0.3s;
        }
        .header {
            background: var(--surface);
            padding: 1rem 2rem;
            border-bottom: 1px solid var(--border);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo {
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--accent);
        }
        .content {
            flex: 1;
            display: flex;
            overflow: hidden;
            
        }
        .items-section {
            flex: 2;
            padding: 2rem;
            overflow-y: auto;
            border-right: 1px solid var(--border);
            background: var(--surface);
        }
        .totals-section {
            flex: 1;
            padding: 2rem;
            background: var(--bg);
            display: flex;
            flex-direction: column;
            justify-content: center;
        }
        .cart-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem;
            border-bottom: 1px solid var(--border);
            margin-bottom: 0.5rem;
            background: var(--surface);
            border-radius: var(--radius);
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
        }
        .item-name {
            font-size: 2.5vmin;
            font-weight: 600;
            color: var(--text);
        }
        .item-details {
            color: var(--text-muted);
            font-size: 2vmin;
        }
        .item-price {
            font-size: 2.5vmin;
            font-weight: bold;
            color: var(--accent);
        }
        .total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 1rem;
            font-size: 2.5vmin;
            color: var(--text-muted);
        }
        .grand-total {
            background: var(--accent);
            color: white;
            padding: 2rem;
            border-radius: 12px;
            text-align: center;
            margin-top: auto;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .grand-total-label {
            font-size: 3vmin;
            text-transform: uppercase;
            opacity: 0.9;
        }
        .grand-total-amount {
            font-size: 10vmin;
            font-weight: 800;
            line-height: 1.2;
        }
        .welcome-screen {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            text-align: center;
            color: white;
            overflow: hidden;
            background: #212529;
        }
        .slideshow-bg {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
        }
        .slideshow-bg::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5); /* Overlay */
            z-index: 2;
        }
        .slide {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-size: cover;
            background-position: center;
            opacity: 0;
            transition: opacity 2s ease-in-out;
            transform: scale(1.1); /* Subtle zoom effect start */
            transition: opacity 2s ease-in-out, transform 10s ease;
        }
        .slide.active {
            opacity: 1;
            transform: scale(1);
            z-index: 1;
        }
        .welcome-content {
            position: relative;
            z-index: 10;
            padding: 3rem;
            max-width: 800px;
            animation: fadeIn 1s ease-out;
        }
        .welcome-logo {
            max-height: 15vh;
            margin-bottom: 2rem;
            filter: drop-shadow(0 4px 10px rgba(0,0,0,0.3));
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .welcome-icon {
            font-size: 15vmin;
            margin-bottom: 1rem;
            color: rgba(255,255,255,0.8);
            text-shadow: 0 4px 10px rgba(0,0,0,0.3);
        }
        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }
        ::-webkit-scrollbar-track {
            background: var(--bg); 
        }
        ::-webkit-scrollbar-thumb {
            background: var(--border); 
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: var(--text-muted); 
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="logo">
            <i class="bi bi-cart4 me-2"></i>Customer Display
        </div>
        <div class="d-flex align-items-center">
            <button onclick="toggleFullScreen()" class="btn btn-sm btn-link text-muted me-3" title="Toggle Fullscreen"><i class="bi bi-arrows-fullscreen"></i></button>
            <div id="debugInfo" class="me-3 badge bg-secondary" style="display: none;">Items: 0</div>
            <div id="customerName" class="badge bg-light text-dark fs-6 fw-normal border">
                Welcome
            </div>
        </div>
    </div>

    <div id="activeCart" class="content" style="display: none;">
        <div class="items-section" id="itemsList">
            <!-- Items will be injected here -->
        </div>
        
        <div class="totals-section">
            <div class="total-row">
                <span id="labelSubtotal">Subtotal</span>
                <span id="displaySubtotal">OMR 0.000</span>
            </div>
            <div id="displayTaxRow" class="total-row text-muted">
                <span id="labelVAT">VAT</span>
                <span id="displayTax">OMR 0.000</span>
            </div>
            <div id="displayDiscountRow" class="total-row text-danger" style="display: none;">
                <span id="labelDiscount">Discount</span>
                <span id="displayDiscount">- OMR 0.000</span>
            </div>
            <div id="displayLoyaltyRow" class="total-row text-success" style="display: none;">
                <span id="labelLoyalty">Loyalty Redeemed</span>
                <span id="displayLoyalty">- OMR 0.000</span>
            </div>
            
            <div class="grand-total">
                <div class="grand-total-label" id="labelTotal">Total to Pay</div>
                <div class="grand-total-amount" id="displayTotal">OMR 0.000</div>
            </div>
        </div>
    </div>

    <div id="welcomeScreen" class="welcome-screen">
        <div class="slideshow-bg" id="slideshow">
            <?php foreach ($slides as $i => $url): ?>
            <div class="slide <?= $i === 0 ? 'active' : '' ?>" style="background-image: url('<?= htmlspecialchars($url) ?>');"></div>
            <?php endforeach; ?>
        </div>
        
        <div class="welcome-content">
            <?php if (!empty($settings['company_logo']) && file_exists($settings['company_logo'])): ?>
                <img src="<?= htmlspecialchars($settings['company_logo']) ?>?v=<?= time() ?>" alt="Store Logo" class="welcome-logo">
            <?php elseif (file_exists('uploads/logo.png')): ?>
                 <img src="uploads/logo.png?v=<?= time() ?>" alt="Store Logo" class="welcome-logo">
            <?php else: ?>
                <div class="welcome-icon"><i class="bi bi-shop"></i></div>
            <?php endif; ?>
            <h1 class="display-3 fw-bold mb-3 text-white"><?= htmlspecialchars($title) ?></h1>
            <p class="lead fs-3 text-white-50"><?= htmlspecialchars($subtitle) ?></p>
        </div>
    </div>

    <script>
        let lastTimestamp = 0;
        let currentCurrency = 'OMR';

        function formatMoney(amount) {
            return currentCurrency + ' ' + parseFloat(amount).toFixed(3);
        }

        function updateDisplay(data) {
            if (!data) return;
            lastTimestamp = data.timestamp || 0;
            currentCurrency = data.currency || 'OMR';

            // Labels translation if Arabic detected in items
            const isAr = data.items && data.items.some(i => /[\u0600-\u06FF]/.test(i.name));
            if (isAr) {
                document.getElementById('labelSubtotal').innerText = 'المجموع (بدون الضريبة) / Subtotal';
                document.getElementById('labelVAT').innerText = 'الضريبة / VAT';
                document.getElementById('labelDiscount').innerText = 'الخصم / Discount';
                document.getElementById('labelLoyalty').innerText = 'الولاء / Loyalty';
                document.getElementById('labelTotal').innerText = 'الإجمالي / Total';
            } else {
                document.getElementById('labelSubtotal').innerText = 'Subtotal';
                document.getElementById('labelVAT').innerText = 'VAT';
                document.getElementById('labelDiscount').innerText = 'Discount';
                document.getElementById('labelLoyalty').innerText = 'Loyalty';
                document.getElementById('labelTotal').innerText = 'Total to Pay';
            }

            // Debug info
            const items = data.items || [];
            document.getElementById('debugInfo').innerText = 'Items: ' + items.length;
            
            // Show/Hide screens
            if (items.length > 0) {
                document.getElementById('welcomeScreen').style.display = 'none';
                document.getElementById('activeCart').style.display = 'flex';
                document.getElementById('debugInfo').style.display = 'block';
            } else {
                document.getElementById('welcomeScreen').style.display = 'flex';
                document.getElementById('activeCart').style.display = 'none';
                document.getElementById('debugInfo').style.display = 'none';
                return; // Stop if empty
            }

            // Update Customer Name if available
            if (data.customerName || data.customer_name) {
                 document.getElementById('customerName').innerText = data.customerName || data.customer_name;
            } else {
                 document.getElementById('customerName').innerText = 'Welcome';
            }

            // Render Items
            const list = document.getElementById('itemsList');
            list.innerHTML = '';
            
            items.forEach(item => {
                const div = document.createElement('div');
                div.className = 'cart-item';
                
                const qty = parseFloat(item.quantity || item.qty) || 0;
                const price = parseFloat(item.price) || 0;
                // If total is not provided, calculate it: qty * price
                let total = item.total ? parseFloat(item.total) : (qty * price);
                
                let details = `${qty} x ${formatMoney(price)}`;
                const itemDiscount = parseFloat(item.discount) || 0;
                if (itemDiscount > 0) {
                    details += ` (Disc: ${formatMoney(itemDiscount)})`;
                }
                
                div.innerHTML = `
                    <div>
                        <div class="item-name">${item.name}</div>
                        <div class="item-details">${details}</div>
                    </div>
                    <div class="item-price">
                        ${formatMoney(total)}
                    </div>
                `;
                list.appendChild(div);
            });
            
            // Scroll to bottom
            list.scrollTop = list.scrollHeight;

            // Update Totals
            const vat = parseFloat(data.vat) || 0;
            const subtotal = parseFloat(data.subtotal) || 0;
            document.getElementById('displaySubtotal').innerText = formatMoney(subtotal - vat);
            document.getElementById('displayTax').innerText = formatMoney(vat);
            
            const discount = parseFloat(data.discount) || 0;
            if (discount > 0) {
                document.getElementById('displayDiscountRow').style.display = 'flex';
                document.getElementById('displayDiscount').innerText = '- ' + formatMoney(discount);
            } else {
                document.getElementById('displayDiscountRow').style.display = 'none';
            }

            const loyalty = parseFloat(data.loyalty) || 0;
            if (loyalty > 0) {
                document.getElementById('displayLoyaltyRow').style.display = 'flex';
                document.getElementById('displayLoyalty').innerText = '- ' + formatMoney(loyalty);
            } else {
                document.getElementById('displayLoyaltyRow').style.display = 'none';
            }

            document.getElementById('displayTotal').innerText = formatMoney(data.total || 0);
        }

        // Listen for storage events
        window.addEventListener('storage', (e) => {
            if (e.key === 'pos_cart_update') {
                try {
                    const data = JSON.parse(e.newValue);
                    updateDisplay(data);
                } catch (err) {
                    console.error('Error parsing cart data', err);
                }
            }
        });

        // Polling fallback (every 1 second)
        setInterval(() => {
            const stored = localStorage.getItem('pos_cart_update');
            if (stored) {
                try {
                    const data = JSON.parse(stored);
                    if (data.timestamp && data.timestamp !== lastTimestamp) {
                        updateDisplay(data);
                    }
                } catch (e) {}
            }
        }, 1000);

        // Initial check
        const stored = localStorage.getItem('pos_cart_update');
        if (stored) {
            try {
                updateDisplay(JSON.parse(stored));
            } catch (e) {}
        }

        function toggleFullScreen() {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen();
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                }
            }
        }

        // Attempt to maximize on load
        window.addEventListener('load', () => {
             try {
                 window.moveTo(0, 0);
                 window.resizeTo(screen.availWidth, screen.availHeight);
             } catch(e) {}
             
             // Start slideshow
             const slides = document.querySelectorAll('.slide');
             let currentSlide = 0;
             if (slides.length > 0) {
                 setInterval(() => {
                     slides[currentSlide].classList.remove('active');
                     currentSlide = (currentSlide + 1) % slides.length;
                     slides[currentSlide].classList.add('active');
                 }, 6000);
             }
        });
    </script>
</body>
</html>
