<?php 
// 1. الاتصال بقاعدة البيانات والإعدادات البدئية
include 'config.php'; 

// جلب رقم الفرع والمستخدم الحالي من الجلسة بشكل آمن
$current_branch_id = $_SESSION['branch_id'] ?? 1;
$current_user_id   = $_SESSION['user_id'] ?? 1; 

// 2. معالجة فتح الوردية برمجياً مع حفظ الأرصدة الافتتاحية وأسعار الصرف
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'open_shift') {
    $cash_start     = floatval($_POST['cash_start'] ?? 0);
    $cash_start_usd = floatval($_POST['cash_start_usd'] ?? 0); 
    $cash_start_jpy = floatval($_POST['cash_start_jpy'] ?? 0); 
    $egp_rate       = floatval($_POST['egp_rate'] ?? 1); 
    $jpy_rate       = floatval($_POST['jpy_rate'] ?? 1); 
    
    $insert = $pdo->prepare("INSERT INTO shifts (user_id, branch_id, start_time, cash_start, cash_start_usd, cash_start_jpy, egp_rate, jpy_rate, status) VALUES (:user_id, :branch_id, NOW(), :cash_start, :cash_start_usd, :cash_start_jpy, :egp_rate, :jpy_rate, 'open')");
    $insert->execute([
        ':user_id'        => $current_user_id,
        ':branch_id'      => $current_branch_id,
        ':cash_start'     => $cash_start,
        ':cash_start_usd' => $cash_start_usd,
        ':cash_start_jpy' => $cash_start_jpy,
        ':egp_rate'       => $egp_rate,
        ':jpy_rate'       => $jpy_rate
    ]);
    
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// 3. معالجة إنهاء الوردية برمجياً وحفظ الأرصدة النهائية
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'close_shift') {
    $cash_end     = floatval($_POST['cash_end'] ?? 0);
    $cash_end_usd = floatval($_POST['cash_end_usd'] ?? 0); 
    $cash_end_jpy = floatval($_POST['cash_end_jpy'] ?? 0); 
    $shift_to_close = intval($_POST['shift_id']);
    
    $update = $pdo->prepare("UPDATE shifts SET end_time = NOW(), cash_end = :cash_end, cash_end_usd = :cash_end_usd, cash_end_jpy = :cash_end_jpy, status = 'closed' WHERE id = :shift_id");
    $update->execute([
        ':cash_end'     => $cash_end,
        ':cash_end_usd' => $cash_end_usd,
        ':cash_end_jpy' => $cash_end_jpy,
        ':shift_id'     => $shift_to_close
    ]);
    
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// 4. التحقق هل توجد وردية مفتوحة حالياً؟
$stmt = $pdo->prepare("SELECT id, status, egp_rate, jpy_rate FROM shifts WHERE user_id = :user_id AND branch_id = :branch_id AND status = 'open' LIMIT 1");
$stmt->execute([
    ':user_id'   => $current_user_id,
    ':branch_id' => $current_branch_id
]);
$active_shift = $stmt->fetch();

$is_shift_open = (bool)$active_shift;
$current_shift_id = $is_shift_open ? $active_shift['id'] : 0;

$egp_exchange_rate = $is_shift_open ? floatval($active_shift['egp_rate']) : 1;
$jpy_exchange_rate = $is_shift_open ? floatval($active_shift['jpy_rate']) : 1;

// 5. جلب المنتجات 
$all_products = [];
if ($is_shift_open) {
    $sql = "SELECT p.*, 
            CASE 
                WHEN p.is_composite = 1 THEN 
                    IFNULL((SELECT i2.quantity FROM inventory i2 WHERE i2.product_id = p.raw_product_id AND i2.branch_id = :branch_id1), 0)
                ELSE 
                    IFNULL(i.quantity, 0)
            END as current_stock
            FROM products p 
            LEFT JOIN inventory i ON p.id = i.product_id AND i.branch_id = :branch_id2
            ORDER BY p.is_composite DESC, p.product_name ASC";
            
    $stmt_products = $pdo->prepare($sql);
    $stmt_products->execute([
        ':branch_id1' => $current_branch_id,
        ':branch_id2' => $current_branch_id
    ]);
    $all_products = $stmt_products->fetchAll();
}

include 'header.php'; 
?>

<style>
    :root { 
        --odoo-purple: #714B67; 
        --odoo-teal: #008784; 
        --egyptian-dark: #2b2621;
        --papyrus-bg: #f5e6c8;
        --papyrus-text: #4a2c11;
    }
    
    body { 
        margin: 0; 
        overflow: hidden; 
        background: var(--egyptian-dark); 
        height: 100vh; 
        font-family: 'Segoe UI', sans-serif; 
    }
    
    .pos-container { display: flex; height: calc(100vh - 120px); direction: rtl; }

    /* شاشة فتح الوردية */
    .shift-modal-bg {
        display: flex; justify-content: center; align-items: center; height: calc(100vh - 60px); direction: rtl;
        overflow-y: auto; padding: 20px 0;
    }
    .shift-card {
        background: #fdfaf4; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.4);
        width: 450px; padding: 25px; border-top: 5px solid #8b5a2b;
    }
    .shift-card h3 { color: #5c3a21; margin-top: 0; text-align: center; font-size: 1.4rem; margin-bottom: 20px; }
    .form-control-odoo {
        width: 100%; padding: 8px; margin: 6px 0 14px 0; border: 1px solid #c2a678; border-radius: 4px; box-sizing: border-box; font-size: 1.05rem; text-align: center; background: #fff;
    }
    .btn-odoo-submit {
        width: 100%; padding: 12px; background: var(--odoo-teal); color: white; border: none; border-radius: 4px; font-size: 1.1rem; font-weight: bold; cursor: pointer; margin-top: 5px;
    }
    .btn-odoo-submit:hover { background: #006b68; }

    /* منطقة عرض المنتجات */
    .products-area { flex: 1; display: flex; flex-direction: column; background: #36302b; }
    .search-container { padding: 15px; background: #221e1a; border-bottom: 1px solid #443c35; }
    .search-container input { width: 100%; padding: 12px; font-size: 1.1rem; border: 2px solid #8b5a2b; background: #443c35; color: #fff; border-radius: 6px; outline: none; }
    .search-container input::placeholder { color: #a09488; }

    .product-screen { 
        flex: 1; padding: 15px; overflow-y: auto; 
        display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); 
        gap: 12px; align-content: flex-start; 
    }
    .o-product {
        background: #ebdcc5; border: 1px solid #c2a678; border-radius: 6px;
        cursor: pointer; transition: 0.2s; position: relative; text-align: center;
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }
    .o-product:hover { border-color: #8b5a2b; transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.4); }
    .o-product .p-img { height: 85px; display: flex; align-items: center; justify-content: center; background: #fdf6ec; border-bottom: 1px solid #decbad; padding: 5px; border-top-left-radius: 5px; border-top-right-radius: 5px; }
    .o-product .p-img img { max-height: 100%; max-width: 100%; object-fit: contain; }
    .o-product .p-info { padding: 10px; background: #ebdcc5; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; }
    .o-product .p-name { font-weight: bold; font-size: 0.9rem; color: #3d2511; display: block; height: 32px; overflow: hidden; margin-bottom: 4px; }
    .o-product .p-price { color: #b85c00; font-weight: bold; font-size: 1rem; } 
    .text-ancient { color: #8b5a2b; }

    /* تفاصيل البردية القديمة للفاتورة */
    .order-screen { 
        width: 420px; 
        background-color: var(--papyrus-bg); 
        background-image: 
            linear-gradient(rgba(210, 180, 140, 0.25) 1px, transparent 1px),
            linear-gradient(90deg, rgba(210, 180, 140, 0.25) 1px, transparent 1px);
        background-size: 10px 10px;
        border-right: 6px ridge #8b5a2b; 
        display: flex; 
        flex-direction: column; 
        box-shadow: -5px 0 20px rgba(0,0,0,0.3);
    }
    .order-header { 
        padding: 12px 15px; 
        background: #e9d5b3; 
        border-bottom: 2px dashed #8b5a2b; 
        font-weight: bold; 
        color: var(--papyrus-text); 
    }
    .order-list { flex: 1; overflow-y: auto; }
    
    .order-item { 
        padding: 12px 15px; 
        border-bottom: 1px dashed rgba(139, 90, 43, 0.4); 
        display: flex; 
        justify-content: space-between; 
        align-items: center; 
        color: var(--papyrus-text);
    }
    .order-item:hover { background: rgba(233, 213, 179, 0.4); }
    
    .qty-controls { display: flex; align-items: center; gap: 8px; margin-top: 5px; }
    .qty-btn { background: #e9d5b3; border: 1px solid #8b5a2b; color: #3d2511; border-radius: 4px; width: 25px; height: 25px; display: flex; justify-content: center; align-items: center; cursor: pointer; font-weight: bold; font-size: 14px; }
    .qty-btn:hover { background: #dec49a; }

    .order-footer { 
        background: #704722; 
        color: #fdf5e6; 
        padding: 15px; 
        border-top: 3px double #4a2c11;
    }
    
    .discount-container { display: flex; gap: 10px; margin-bottom: 12px; }
    .btn-discount { flex: 1; padding: 10px; font-size: 0.95rem; font-weight: bold; border-radius: 4px; border: none; cursor: pointer; transition: 0.2s; }
    .btn-discount-custom { background: #d9822b; color: white; }
    .btn-discount-custom:hover { background: #b8691d; }

    .total-row { display: flex; justify-content: space-between; font-size: 1.6rem; font-weight: bold; margin-bottom: 5px; color: #ffc107; }
    .promo-badge-container { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }

    .converted-row { display: flex; justify-content: space-between; font-size: 1.4rem; font-weight: bold; margin-bottom: 10px; color: #fff; border-top: 1px dashed #fff; padding-top: 5px; }
    .btn-pay { width: 100%; padding: 12px; background: var(--odoo-teal); color: white; border: none; border-radius: 4px; font-size: 1.3rem; font-weight: bold; cursor: pointer; transition: 0.2s; }
    .btn-pay:hover { background: #006b68; }
    .btn-pay:disabled { background: #555; cursor: not-allowed; }

    .btn-close-shift {
        background: #c93b3b; color: white; border: none; padding: 4px 10px; border-radius: 4px; font-size: 0.8rem; cursor: pointer; margin-right: 10px; font-weight: bold;
    }
    .btn-close-shift:hover { background: #a62e2e; }
</style>

<?php if (!$is_shift_open): ?>
    <div class="shift-modal-bg">
        <div class="shift-card">
            <h3><i class="fa fa-door-open"></i> فتح وردية جديدة وتحديد الأرصدة</h3>
            <form method="POST" action="">
                <input type="hidden" name="action" value="open_shift">
                
                <div style="background: #f3e6ce; padding: 12px; border-radius: 6px; margin-bottom: 15px; border-right: 4px solid var(--odoo-teal);">
                    <h5 class="m-0 mb-2 fw-bold text-dark" style="font-size: 0.95rem;">💵 أرصدة الكاش الافتتاحية بالدرج:</h5>
                    
                    <label class="fw-bold small text-muted">رصيد الدولار الأمريكي (USD):</label>
                    <input type="number" step="0.01" min="0" name="cash_start_usd" class="form-control-odoo" placeholder="0.00 $" required autofocus>

                    <label class="fw-bold small text-muted">رصيد الجنيه المصري (EGP):</label>
                    <input type="number" step="0.01" min="0" name="cash_start" class="form-control-odoo" placeholder="0.00 ج.م" required>
                    
                    <label class="fw-bold small text-muted">رصيد الين الياباني (JPY):</label>
                    <input type="number" step="1" min="0" name="cash_start_jpy" class="form-control-odoo" placeholder="0 ¥" required>
                </div>
                
                <div style="background: #f3e6ce; padding: 12px; border-radius: 6px; margin-bottom: 15px; border-right: 4px solid #8b5a2b;">
                    <h5 class="m-0 mb-2 fw-bold text-dark" style="font-size: 0.95rem;">📈 أسعار الصرف للوردية (الأساس هو الدولار):</h5>

                    <label class="fw-bold small text-muted">سعر صرف الجنيه (1 USD = ? EGP):</label>
                    <input type="number" step="0.01" min="0.01" name="egp_rate" class="form-control-odoo" placeholder="مثال: 48.50" required>
                    
                    <label class="fw-bold small text-muted">سعر صرف الين (1 USD = ? JPY):</label>
                    <input type="number" step="0.0001" min="0.0001" name="jpy_rate" class="form-control-odoo" placeholder="مثال: 150.25" required>
                </div>
                
                <button type="submit" class="btn-odoo-submit">بدء الشيفت وتثبيت البيانات</button>
            </form>
        </div>
    </div>
<?php else: ?>
    <div class="pos-container">
        <div class="products-area">
            <div class="search-container">
                <input type="text" id="barcodeSearch" placeholder="🔍 امسح الباركود أو ابحث بالاسم ثم اضغط Enter..." autofocus>
            </div>

            <div class="product-screen">
                <?php foreach($all_products as $p): ?>
                <div class="o-product" 
                     onclick="handleProductClick(this)"
                     data-id="<?= $p['id'] ?>"
                     data-barcode="<?= htmlspecialchars($p['barcode'] ?? '') ?>"
                     data-name="<?= htmlspecialchars($p['product_name'], ENT_QUOTES) ?>"
                     data-price="<?= floatval($p['price']) ?>"
                     data-unit="<?= htmlspecialchars($p['unit'], ENT_QUOTES) ?>"
                     data-composite="<?= intval($p['is_composite']) ?>"
                     data-consumption="<?= floatval($p['consumption_qty']) ?>"
                     data-stock="<?= floatval($p['current_stock']) ?>"> 
                     
                    <div class="p-img">
                        <?php if (!empty($p['product_image'])): ?>
                            <img src="assets/pharaonic/<?= htmlspecialchars($p['product_image']) ?>" alt="<?= htmlspecialchars($p['product_name']) ?>">
                        <?php else: ?>
                            <?php 
                                $ancient_icons = ['fa-ankh', 'fa-eye', 'fa-monument', 'fa-scroll', 'fa-crown', 'fa-gem'];
                                $icon_route = $p['id'] % count($ancient_icons);
                                $chosen_icon = $ancient_icons[$icon_route];
                            ?>
                            <i class="fa <?= $chosen_icon ?> fa-3x text-ancient"></i>
                        <?php endif; ?>
                    </div>
                    
                    <div class="p-info">
                        <span class="p-name"><?= htmlspecialchars($p['product_name']) ?></span>
                        <span class="p-price"><?= number_format($p['price'], 2) ?> $</span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- واجهة الفاتورة الجانبية -->
        <div class="order-screen">
            <div class="order-header d-flex justify-content-between align-items-center">
                <div>
                    <span>📜 الطلب الفرعوني الحالي</span>
                    <span class="badge bg-amber text-dark" style="margin-right: 5px; background:#8b5a2b; color:#fff;">وردية #<?= $current_shift_id ?></span>
                </div>
                <button onclick="triggerCloseShift()" class="btn-close-shift">
                    <i class="fa fa-power-off"></i> إنهاء الوردية
                </button>
            </div>
            <div id="cartItems" class="order-list"></div>
            
            <div class="order-footer">
                <div class="mb-3">
                    <label class="text-white small fw-bold mb-1 d-block"><i class="fa fa-money-bill-wave"></i> عملة الدفع:</label>
                    <select id="payCurrency" class="form-select form-select-sm" onchange="calculateCurrencyConversion()" style="font-weight: bold; background: #ebdcc5; color: #3d2511;">
                        <option value="USD" selected>دولار أمريكي (USD) - الافتراضي</option>
                        <option value="EGP">جنيه مصري (EGP)</option>
                        <option value="JPY">ين ياباني (JPY)</option>
                    </select>
                </div>

                <div class="discount-container">
                    <button type="button" class="btn-discount btn-discount-custom" onclick="openDiscountModal()">
                        <i class="fa fa-gift"></i> إدارة خصومات وهدايا المنتجات
                    </button>
                </div>

                <div class="total-row">
                    <span>الإجمالي النهائي:</span>
                    <span><span id="grandTotal">0.00</span> $</span>
                </div>

                <div class="converted-row" id="convertedRow" style="display: none;">
                    <span>المطلوب دفعه:</span>
                    <span><span id="convertedTotal">0.00</span> <span id="convertedLabel"></span></span>
                </div>

                <button onclick="processPayment()" id="payBtn" class="btn-pay">دفع وتأكيد</button>
            </div>
        </div>
    </div>

    <!-- نافذة الـ Modal لخصومات وهدايا المنتجات -->
    <div id="discountModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); z-index: 9999; justify-content: center; align-items: center; direction: rtl;">
        <div style="background: #fdf6ec; padding: 25px; border-radius: 8px; width: 90%; max-width: 650px; max-height: 80vh; overflow-y: auto; border-top: 5px solid #8b5a2b; box-shadow: 0 5px 15px rgba(0,0,0,0.5);">
            <h4 style="color: #4a2c11; border-bottom: 2px solid #8b5a2b; padding-bottom: 10px; margin-bottom: 15px; font-weight: bold;">
                <i class="fa fa-gift"></i> خصومات وهدايا المنتجات الحالية
            </h4>
            
            <div id="modalProductsList"></div>

            <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px; border-top: 1px solid #decbad; padding-top: 15px;">
                <button onclick="closeDiscountModal()" style="background: var(--odoo-teal); color: white; border: none; padding: 8px 20px; border-radius: 4px; cursor: pointer; font-weight: bold;">إغلاق وحفظ</button>
            </div>
        </div>
    </div>

    <!-- فورم الإغلاق السرّي للوردية -->
    <form id="closeShiftForm" method="POST" action="" style="display:none;">
        <input type="hidden" name="action" value="close_shift">
        <input type="hidden" name="shift_id" value="<?= $current_shift_id ?>">
        <input type="hidden" name="cash_end_usd" id="cash_end_usd_input">
        <input type="hidden" name="cash_end" id="cash_end_input"> 
        <input type="hidden" name="cash_end_jpy" id="cash_end_jpy_input">
    </form>

    <script>
    let cartOrder = [];
    const branchId = <?= $current_branch_id ?>;
    const shiftId = <?= $current_shift_id ?>;
    
    const egpRate = <?= $egp_exchange_rate ?>; 
    const jpyRate = <?= $jpy_exchange_rate ?>;

    function calculateCurrencyConversion() {
        const selectedCurrency = document.getElementById('payCurrency').value;
        const totalUSD = parseFloat(document.getElementById('grandTotal').innerText) || 0;
        const convertedRow = document.getElementById('convertedRow');
        const convertedTotal = document.getElementById('convertedTotal');
        const convertedLabel = document.getElementById('convertedLabel');

        if (selectedCurrency === 'USD' || totalUSD === 0) {
            convertedRow.style.display = 'none';
        } else if (selectedCurrency === 'EGP') {
            convertedRow.style.display = 'flex';
            convertedTotal.innerText = (totalUSD * egpRate).toFixed(2); 
            convertedLabel.innerText = 'جنيه (EGP)';
        } else if (selectedCurrency === 'JPY') {
            convertedRow.style.display = 'flex';
            convertedTotal.innerText = (totalUSD * jpyRate).toFixed(0); 
            convertedLabel.innerText = 'ين (¥)';
        }
    }

    document.getElementById('barcodeSearch').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            let term = this.value.trim().toLowerCase();
            if (!term) return;

            let products = document.querySelectorAll('.o-product');
            let found = false;

            products.forEach(el => {
                if (found) return; 

                let name = el.dataset.name.toLowerCase();
                let barcode = el.dataset.barcode ? el.dataset.barcode.toLowerCase() : '';
                
                if (barcode === term || name.includes(term)) {
                    el.click(); 
                    found = true;
                }
            });

            if (!found) {
                alert('لم يتم العثور على منتج يطابق بحثك أو الباركود المدخل!');
            }
            this.value = ''; 
            this.focus();
        }
    });

    function triggerCloseShift() {
        let confirmClose = confirm("هل أنت متأكد من رغبتك في إنهاء الوردية الحالية وبث الإغلاق للسيستم؟");
        if (!confirmClose) return;

        let cashEndUsd = prompt("أدخل رصيد الكاش النهائي بالدولار الأمريكي (USD) المتواجد بالدرج حالياً:", "0");
        if (cashEndUsd === null || isNaN(cashEndUsd) || cashEndUsd === '' || Number(cashEndUsd) < 0) {
            alert("إغلاق ملغي! الرجاء إدخال رقم كاش صحيح للدولار.");
            return;
        }

        let cashEnd = prompt("أدخل رصيد الكاش النهائي بالجنيه المصري (EGP) المتواجد بالدرج حالياً:", "0");
        if (cashEnd === null || isNaN(cashEnd) || cashEnd === '' || Number(cashEnd) < 0) {
            alert("إغلاق ملغي! الرجاء إدخال رقم كاش صحيح للجنيه.");
            return;
        }

        let cashEndJpy = prompt("أدخل رصيد الكاش النهائي بالين الياباني (JPY) المتواجد بالدرج حالياً:", "0");
        if (cashEndJpy === null || isNaN(cashEndJpy) || cashEndJpy === '' || Number(cashEndJpy) < 0) {
            alert("إغلاق ملغي! الرجاء إدخال رقم كاش صحيح للين.");
            return;
        }

        document.getElementById('cash_end_usd_input').value = cashEndUsd;
        document.getElementById('cash_end_input').value = cashEnd;
        document.getElementById('cash_end_jpy_input').value = cashEndJpy;
        
        document.getElementById('closeShiftForm').submit();
    }

    function handleProductClick(el) {
        const p = {
            id: parseInt(el.dataset.id),
            name: el.dataset.name,
            price: parseFloat(el.dataset.price),
            unit: el.dataset.unit,
            isComposite: parseInt(el.dataset.composite),
            consumption: parseFloat(el.dataset.consumption),
            stock: parseFloat(el.dataset.stock)
        };

        if (p.unit === 'kg' || p.unit === 'كيلو' || p.unit === 'جرام') {
            let mode = confirm("OK للبيع بمبلغ معين، Cancel للبيع بالوزن");
            if (mode) {
                let amount = prompt("أدخل المبلغ المطلوب بالدولار ($):");
                if (amount && !isNaN(amount) && Number(amount) > 0) {
                    let qty = parseFloat(amount) / p.price;
                    addItem(p, qty, parseFloat(amount), 'بالمبلغ');
                }
            } else {
                let weight = prompt("أدخل الوزن بالجرام:");
                if (weight && !isNaN(weight) && Number(weight) > 0) {
                    let qty = parseFloat(weight) / 1000;
                    addItem(p, qty, qty * p.price, weight + ' جرام');
                }
            }
        } else {
            let existingItemIndex = cartOrder.findIndex(item => item.id === p.id && !item.name.includes('بالمبلغ') && !item.name.includes('جرام'));
            if(existingItemIndex !== -1) {
                updateItemQty(existingItemIndex, cartOrder[existingItemIndex].qty + 1);
            } else {
                addItem(p, 1, p.price, '');
            }
        }
    }

    function addItem(p, qty, total, note) {
        if (!validateStock(p, qty)) return;

        cartOrder.push({
            id: p.id,
            name: p.name + (note ? ` (${note})` : ''),
            qty: qty,
            price: p.price,
            total: total,
            discount_percent: 0, 
            free_qty: 0 // 🔥 تم التعديل إلى كمية فري بدلاً من boolean
        });
        updateUI();
    }

    function validateStock(p, qty) {
        if (p.isComposite === 1) {
            let neededRawKg = (qty * p.consumption) / 1000;
            if (p.stock < neededRawKg) { 
                alert("عفواً، رصيد البن الخام في المخزن لا يكفي لتحضير هذه الكمية!");
                return false;
            }
        } else {
            if (p.stock < qty) {
                alert("عفواً، الرصيد المتبقي في المخزن لا يكفي!");
                return false;
            }
        }
        return true;
    }

    function updateItemQty(index, newQty) {
        if(newQty <= 0) return removeItem(index);

        let item = cartOrder[index];
        let pElement = document.querySelector(`.o-product[data-id="${item.id}"]`);
        if(pElement) {
            let pData = {
                id: parseInt(pElement.dataset.id),
                isComposite: parseInt(pElement.dataset.composite),
                consumption: parseFloat(pElement.dataset.consumption),
                stock: parseFloat(pElement.dataset.stock)
            };
            if(!validateStock(pData, newQty)) return;
        }

        item.qty = newQty;
        
        // 🔥 التأكد من أن الكمية الهدايا لا تتجاوز الكمية المطلوبة
        if (item.free_qty > item.qty) {
            item.free_qty = item.qty;
        }
        
        updateUI();
    }

    function promptManualQty(index) {
        let currentQty = cartOrder[index].qty;
        let newQty = prompt("أدخل الكمية المطلوبة:", currentQty);
        if(newQty !== null && !isNaN(newQty) && Number(newQty) > 0) {
            updateItemQty(index, parseFloat(newQty));
        }
    }

    function updateUI() {
        const list = document.getElementById('cartItems');
        let grandTotal = 0; 
        
        list.innerHTML = cartOrder.map((item, index) => {
            let freeQty = parseFloat(item.free_qty) || 0;
            let payableQty = Math.max(0, item.qty - freeQty); // الكمية المدفوعة فقط
            
            let itemSubtotal = payableQty * item.price;
            
            let itemDiscount = 0;
            if (item.discount_percent > 0) {
                itemDiscount = itemSubtotal * (item.discount_percent / 100);
            }
            
            item.total = itemSubtotal - itemDiscount;
            grandTotal += item.total;

            let badgeHTML = '';
            if (freeQty > 0) {
                badgeHTML += `<span class="badge bg-success" style="font-size: 10px; margin-right: 3px;">🎁 ${freeQty.toFixed(3)} هدايا</span>`;
            }
            if (item.discount_percent > 0) {
                badgeHTML += `<span class="badge bg-warning text-dark" style="font-size: 10px; margin-right: 3px;">خصم ${item.discount_percent}%</span>`;
            }

            return `
                <div class="order-item">
                    <div>
                        <span class="fw-bold">${item.name}</span>
                        <div class="promo-badge-container">${badgeHTML}</div>
                        <small class="text-muted">
                            ${item.qty.toFixed(3)} x ${item.price.toFixed(2)} $
                            ${freeQty > 0 ? `(المدفوع: ${payableQty.toFixed(3)})` : ''}
                        </small>
                        <div class="qty-controls">
                            <span class="qty-btn" onclick="updateItemQty(${index}, ${item.qty + 1})"><i class="fa fa-plus text-success" style="font-size: 10px;"></i></span>
                            <span class="qty-btn" onclick="updateItemQty(${index}, ${item.qty - 1})"><i class="fa fa-minus text-warning" style="font-size: 10px;"></i></span>
                            <span class="qty-btn" title="إدخال يدوي للكمية" onclick="promptManualQty(${index})"><i class="fa fa-keyboard text-primary" style="font-size: 10px;"></i></span>
                        </div>
                    </div>
                    <div class="text-start d-flex flex-column align-items-end">
                        <span class="fw-bold d-block mb-2 text-success">${item.total.toFixed(2)} $</span>
                        <i class="fa fa-trash-alt text-danger" style="cursor:pointer; font-size: 1.1rem;" onclick="removeItem(${index})"></i>
                    </div>
                </div>`;
        }).join('');

        document.getElementById('grandTotal').innerText = grandTotal.toFixed(2);
        calculateCurrencyConversion();
    }

    function removeItem(index) {
        cartOrder.splice(index, 1);
        updateUI();
    }

    function openDiscountModal() {
        if (cartOrder.length === 0) {
            alert("السلة فارغة!");
            return;
        }
        
        const container = document.getElementById('modalProductsList');
        container.innerHTML = cartOrder.map((item, index) => {
            return `
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 15px 5px; border-bottom: 1px solid #eee; gap: 10px;">
                    <div style="flex: 2;">
                        <strong style="display:block; font-size:0.95rem; color:#333;">${item.name}</strong>
                        <small class="text-muted">الكمية الإجمالية: ${item.qty.toFixed(3)}</small>
                    </div>
                    
                    <!-- 🔥 خانة إدخال عدد أو وزن القطع الهدايا/المجانية -->
                    <div style="flex: 1.8; text-align: center;">
                        <span class="small text-muted d-block fw-bold mb-1">🎁 الكمية الهدايا:</span>
                        <input type="number" 
                               step="any" 
                               min="0" 
                               max="${item.qty}" 
                               value="${item.free_qty}" 
                               oninput="updateModalFreeQty(${index}, this.value)"
                               style="width: 80px; padding: 5px; text-align: center; border: 1px solid #28a745; border-radius: 4px; font-weight: bold; color: #28a745;"
                               placeholder="0">
                    </div>

                    <div style="flex: 1.5; display: flex; flex-direction: column; align-items: flex-end; gap: 2px;">
                        <span class="small text-muted fw-bold">نسبة الخصم:</span>
                        <div style="display: flex; align-items: center; gap: 3px;">
                            <input type="number" 
                                   min="0" 
                                   max="100" 
                                   value="${item.discount_percent}" 
                                   oninput="updateModalDiscountPercent(${index}, this.value)"
                                   style="width: 65px; padding: 5px; text-align: center; border: 1px solid #ccc; border-radius: 4px; font-weight: bold;"
                                   placeholder="%">
                            <span class="small fw-bold">%</span>
                        </div>
                    </div>
                </div>
            `;
        }).join('');
        
        document.getElementById('discountModal').style.display = 'flex';
    }

    function closeDiscountModal() {
        document.getElementById('discountModal').style.display = 'none';
    }

    // 🔥 دالة تحديث عدد/وزن الكمية الفري المجانية
    function updateModalFreeQty(index, value) {
        let fQty = parseFloat(value) || 0;
        if (fQty < 0) fQty = 0;
        if (fQty > cartOrder[index].qty) {
            alert("لا يمكن أن تتجاوز الكمية المجانية إجمالي الكمية الكلية بالطلب!");
            fQty = cartOrder[index].qty;
        }
        
        cartOrder[index].free_qty = fQty;
        updateUI(); 
    }

    function updateModalDiscountPercent(index, value) {
        let percent = parseFloat(value) || 0;
        if (percent < 0) percent = 0;
        if (percent > 100) percent = 100;
        
        cartOrder[index].discount_percent = percent;
        updateUI(); 
    }

    async function processPayment() {
        if (cartOrder.length === 0) return alert("السلة فارغة!");

        const btn = document.getElementById('payBtn');
        const selectedCurrency = document.getElementById('payCurrency').value;
        const totalUSD = parseFloat(document.getElementById('grandTotal').innerText); 
        
        let currentRate = 1;
        let finalPaidAmount = totalUSD;

        if (selectedCurrency === 'EGP') {
            currentRate = egpRate;
            finalPaidAmount = parseFloat(document.getElementById('convertedTotal').innerText);
        } else if (selectedCurrency === 'JPY') {
            currentRate = jpyRate;
            finalPaidAmount = parseFloat(document.getElementById('convertedTotal').innerText);
        }

        btn.disabled = true;
        btn.innerText = "جاري المعالجة...";

        const payload = {
            cart: cartOrder, // يحتوي على free_qty لكل صنف
            total_amount: totalUSD, 
            currency: selectedCurrency,
            exchange_rate: currentRate,
            paid_amount: finalPaidAmount,
            branch_id: branchId,
            shift_id: shiftId
        };

        try {
            const response = await fetch('save_order.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            const res = await response.json();
            if (res.status === 'success') {
                alert(`تم تسجيل البيع بنجاح بـ (${selectedCurrency})!`);
                window.open('print_receipt.php?id=' + res.order_id, '_blank', 'width=400,height=600');
                location.reload();
            } else {
                alert("فشل الحفظ: " + res.message);
                btn.disabled = false;
                btn.innerText = "دفع وتأكيد";
            }
        } catch (err) {
            alert("حدث خطأ في الاتصال بالخادم!");
            btn.disabled = false;
            btn.innerText = "دفع وتأكيد";
        }
    }
    </script>
<?php endif; ?>