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

// جلب رقم الفرع الحالي من الجلسة (الافتراضي 1 في حال عدم وجود نظام تسجيل دخول حالياً)
$current_branch_id = $_SESSION['branch_id'] ?? 1;

// 2. منطق الحفظ والتعديل (PHP) المطور والمتوافق مع القيود الفريدة
if(isset($_POST['save_product'])){
    $p_id = !empty($_POST['p_id']) ? intval($_POST['p_id']) : null;
    $p_name = $_POST['p_name'];
    $p_barcode = !empty($_POST['p_barcode']) ? trim($_POST['p_barcode']) : null;
    $p_price = floatval($_POST['p_price']);
    $p_unit = $_POST['p_unit'];
    $is_composite = isset($_POST['is_composite']) ? 1 : 0;

    if($is_composite){
        $raw_id = !empty($_POST['raw_product_id']) ? intval($_POST['raw_product_id']) : null;
        $cons_qty = floatval($_POST['consumption_qty']);
        $limit = floatval($_POST['comp_grams_limit']); 
        $qty = 0;
    } else {
        $raw_id = null;
        $cons_qty = 0;
        $qty = floatval($_POST['initial_qty']);
        $limit = floatval($_POST['p_limit']);
    }

    try {
        if(!empty($p_id)){
            $stmt = $pdo->prepare("UPDATE products SET product_name = :name, barcode = :barcode, price = :price, min_limit = :limit, unit = :unit, is_composite = :is_comp, raw_product_id = :raw_id, consumption_qty = :cons_qty WHERE id = :id");
            $stmt->execute([
                ':name'     => $p_name,
                ':barcode'  => $p_barcode,
                ':price'    => $p_price,
                ':limit'    => $limit,
                ':unit'     => $p_unit,
                ':is_comp'  => $is_composite,
                ':raw_id'   => $raw_id,
                ':cons_qty' => $cons_qty,
                ':id'       => $p_id
            ]);
            
            if(!$is_composite) {
                $stmt_inv = $pdo->prepare("INSERT INTO inventory (branch_id, product_id, quantity) VALUES (:branch_id, :product_id, :quantity) 
                                           ON DUPLICATE KEY UPDATE quantity = VALUES(quantity)");
                $stmt_inv->execute([
                    ':branch_id'  => $current_branch_id,
                    ':product_id' => $p_id,
                    ':quantity'   => $qty
                ]);
            }
        } else {
            $stmt = $pdo->prepare("INSERT INTO products (product_name, barcode, price, min_limit, unit, is_composite, raw_product_id, consumption_qty) VALUES (:name, :barcode, :price, :limit, :unit, :is_comp, :raw_id, :cons_qty)");
            $stmt->execute([
                ':name'     => $p_name,
                ':barcode'  => $p_barcode,
                ':price'    => $p_price,
                ':limit'    => $limit,
                ':unit'     => $p_unit,
                ':is_comp'  => $is_composite,
                ':raw_id'   => $raw_id,
                ':cons_qty' => $cons_qty
            ]);
            $last_id = $pdo->lastInsertId();
            
            $initial_stock = $is_composite ? 0 : $qty;
            $stmt_inv = $pdo->prepare("INSERT INTO inventory (branch_id, product_id, quantity) VALUES (:branch_id, :product_id, :quantity) 
                                       ON DUPLICATE KEY UPDATE quantity = VALUES(quantity)");
            $stmt_inv->execute([
                ':branch_id'  => $current_branch_id,
                ':product_id' => $last_id,
                ':quantity'   => $initial_stock
            ]);
        }
        echo "<script>window.location='main_inventory.php';</script>";
    } catch (Exception $e) {
        echo "<script>alert('خطأ في الحفظ: " . addslashes($e->getMessage()) . "');</script>";
    }
}

// 3. جلب البيانات للعرض
$query_sql = "SELECT p.*, 
              IFNULL((SELECT SUM(quantity) FROM order_items WHERE product_id = p.id), 0) as total_sold,
              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_balance,
              (SELECT raw_p.unit FROM products raw_p WHERE raw_p.id = p.raw_product_id) as raw_unit
              FROM products p 
              LEFT JOIN inventory i ON p.id = i.product_id AND i.branch_id = :branch_id2
              ORDER BY p.id DESC";

$stmt_fetch = $pdo->prepare($query_sql);
$stmt_fetch->execute(['branch_id1' => $current_branch_id, 'branch_id2' => $current_branch_id]);
$products = $stmt_fetch->fetchAll();

$stmt_raw = $pdo->prepare("SELECT id, product_name, unit FROM products WHERE is_composite = 0");
$stmt_raw->execute();
$raw_materials = $stmt_raw->fetchAll();

// 4. محرك تصدير المخزن إلى Excel
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    header("Content-Type: application/vnd.ms-excel; charset=utf-8");
    header("Content-Disposition: attachment; filename=inventory_branch_" . $current_branch_id . "_" . date('Y-m-d') . ".xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    
    echo "\xEF\xBB\xBF";
    echo "<table border='1' dir='rtl'>";
    echo "<thead style='background-color: #111111; color: #D4AF37;'>
            <tr>
                <th>كود المنتج (ID)</th>
                <th>اسم المنتج</th>
                <th>الباركود</th>
                <th>نوع المنتج</th>
                <th>الرصيد المتاح حالياً</th>
                <th>سعر البيع</th>
                <th>الكمية المباعة</th>
                <th>الوضعية / الحالة</th>
            </tr>
          </thead>
          <tbody>";
          
    foreach ($products as $p) {
        $type = $p['is_composite'] ? 'منتج مركب' : 'خام الرئيسي';
        if ($p['is_composite']) {
            if (($p['raw_unit'] == 'كيلو' || $p['raw_unit'] == 'kg') && $p['consumption_qty'] > 0) {
                $available_packages = ($p['current_balance'] * 1000) / $p['consumption_qty'];
                $balance_text = number_format($available_packages, 1) . " عبوة أو كوب متاح (يعادل " . number_format($p['current_balance'], 2) . " كيلو خام)";
            } else {
                $balance_text = number_format($p['current_balance'], 2) . " " . $p['unit'];
            }
        } else {
            $balance_text = number_format($p['current_balance'], 2) . " " . $p['unit'];
        }
        
        $is_low = false;
        if ($p['is_composite']) {
            if (($p['raw_unit'] == 'كيلو' || $p['raw_unit'] == 'kg') && $p['consumption_qty'] > 0) {
                $available_qty = ($p['current_balance'] * 1000) / $p['consumption_qty'];
                if ($available_qty <= $p['min_limit']) { $is_low = true; }
            }
        } else {
            if ($p['current_balance'] <= $p['min_limit']) { $is_low = true; }
        }
        $status_text = $is_low ? 'منخفض (تحت حد التنبيه)' : 'متوفر';

        echo "<tr>";
        echo "<td>" . $p['id'] . "</td>";
        echo "<td>" . htmlspecialchars($p['product_name']) . "</td>";
        echo "<td style='mso-number-format:\"\\@\";'>" . htmlspecialchars($p['barcode'] ?? '') . "</td>";
        echo "<td>" . $type . "</td>";
        echo "<td>" . $balance_text . "</td>";
        echo "<td>" . number_format($p['price'], 2) . " ج.م</td>";
        echo "<td>" . number_format($p['total_sold'], 2) . " " . $p['unit'] . "</td>";
        echo "<td>" . $status_text . "</td>";
        echo "</tr>";
    }
    echo "</tbody></table>";
    exit;
}

include 'header.php'; 
?>

<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&family=Reem+Kufi:wght@500;700&display=swap" rel="stylesheet">

<style>
    :root { 
        --pharaoh-gold: #D4AF37; 
        --pharaoh-dark-gold: #AA7C11; 
        --pharaoh-black: #11161d;
        --pharaoh-surface: #121820;
        --pharaoh-surface-light: #1a232e;
    }
    
    body { 
        background-color: #070a0e !important; 
        font-family: 'Cairo', sans-serif; 
        color: #e0e6ed !important;
        position: relative;
        min-height: 100vh;
        overflow-x: hidden;
    }
    
    /* ─── حاوي الشعلة المطور بالـ CSS والدخان ─── */
    .torch-wrapper {
        position: fixed;
        top: 50%;
        transform: translateY(-50%);
        width: 80px; 
        z-index: 10;
        pointer-events: none;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    .torch-wrapper.left { left: 15px; }
    .torch-wrapper.right { right: 15px; }
    
    .pharaoh-fire {
        position: relative;
        width: 30px;
        height: 50px;
        background: linear-gradient(to top, rgba(255, 60, 0, 0) 0%, rgba(255, 60, 0, 0.8) 20%, rgba(255, 150, 0, 0.9) 60%, rgba(255, 230, 100, 1) 100%);
        border-radius: 50% 50% 35% 35% / 60% 60% 40% 40%;
        filter: blur(1px);
        animation: flicker 1.5s ease-in-out infinite alternate;
        box-shadow: 0 -10px 20px rgba(255, 60, 0, 0.5), 0 -20px 40px rgba(255, 150, 0, 0.3);
    }
    .pharaoh-fire::before {
        content: '';
        position: absolute;
        bottom: 0; left: 15%; width: 70%; height: 75%;
        background: linear-gradient(to top, rgba(255, 100, 0, 0) 0%, rgba(255, 200, 0, 0.9) 50%, #ffffff 100%);
        border-radius: 50% 50% 35% 35% / 60% 60% 40% 40%;
        animation: flicker 1.1s ease-in-out infinite alternate-reverse;
    }
    .torch-cup {
        width: 38px;
        height: 16px;
        background: linear-gradient(180deg, var(--pharaoh-gold), #44320a);
        border-radius: 4px 4px 50% 50%;
        border-top: 2px solid #000;
        box-shadow: 0 4px 8px rgba(0,0,0,0.6);
        z-index: 3;
    }
    .torch-holder {
        width: 10px;
        height: 70px;
        background: linear-gradient(90deg, var(--pharaoh-dark-gold), var(--pharaoh-gold), var(--pharaoh-dark-gold));
        border-radius: 2px;
        position: relative;
    }
    .torch-mount {
        width: 22px;
        height: 22px;
        background: #222;
        border: 2px solid var(--pharaoh-gold);
        border-radius: 50%;
        position: absolute;
        bottom: 10px; left: 50%; transform: translateX(-50%);
        z-index: -1;
    }
    @keyframes flicker {
        0% { transform: scale(0.95) rotate(-1deg); opacity: 0.9; }
        100% { transform: scale(1.05) rotate(1deg); }
    }

    .smoke-container {
        position: absolute;
        top: -50px; left: 50%; transform: translateX(-50%);
        width: 40px; height: 100px;
    }
    .smoke-particle {
        position: absolute;
        bottom: 0; left: 50%; width: 10px; height: 10px;
        background: rgba(120, 130, 140, 0.15);
        border-radius: 50%; filter: blur(4px);
        animation: smokeRise 3.5s infinite linear;
    }
    .sm1 { animation-delay: 0s; left: 35%; }
    .sm2 { animation-delay: 1.2s; left: 45%; }
    .sm3 { animation-delay: 2.4s; left: 55%; }
    @keyframes smokeRise {
        0% { transform: translateY(0) scale(1); opacity: 0; }
        10% { opacity: 0.4; }
        100% { transform: translateY(-100px) scale(4); opacity: 0; }
    }
    @media (max-width: 1200px) { .torch-wrapper { display: none; } }

    /* ─── التعديل الصارم لقتل اللون الأبيض في الجدول والـ Wrapper ─── */
    .o_form_view, .table-responsive { 
        background: var(--pharaoh-surface) !important; 
        background-color: var(--pharaoh-surface) !important; 
        border-radius: 12px; 
        box-shadow: 0 10px 30px rgba(0,0,0,0.5); 
        border: 1px solid rgba(212, 175, 55, 0.15) !important; 
    }
    
    .table { 
        color: #e0e6ed !important; 
        background: var(--pharaoh-surface) !important;
        background-color: var(--pharaoh-surface) !important;
    }
    
    /* إجبار الصفوف والخلايا على الخلفية الداكنة الملكية */
    .table tbody tr, .table tbody td {
        background: var(--pharaoh-surface) !important;
        background-color: var(--pharaoh-surface) !important;
        color: #e0e6ed !important;
        border-bottom: 1px solid rgba(255, 255, 255, 0.05) !important;
    }
    
    .table-light { 
        background: var(--pharaoh-surface-light) !important; 
        background-color: var(--pharaoh-surface-light) !important; 
        color: var(--pharaoh-gold) !important; 
    }
    
    .table-light th { 
        background: var(--pharaoh-surface-light) !important; 
        background-color: var(--pharaoh-surface-light) !important; 
        color: var(--pharaoh-gold) !important;
        border-bottom: 2px solid rgba(212, 175, 55, 0.3) !important; 
        font-family: 'Reem Kufi', serif; 
        font-size: 1.05rem; 
    }
    
    .table-hover tbody tr:hover td { 
        background-color: rgba(212, 175, 55, 0.08) !important; 
    }
    
    .btn-pharaoh { 
        background: linear-gradient(135deg, var(--pharaoh-gold), var(--pharaoh-dark-gold)); 
        color: #111; 
        border-radius: 6px; 
        border: none; 
        padding: 8px 20px; 
        transition: 0.3s; 
        font-family: 'Cairo', sans-serif;
    }
    .btn-pharaoh:hover { 
        background: linear-gradient(135deg, #ffffff, var(--pharaoh-gold)); 
        box-shadow: 0 0 15px rgba(212, 175, 55, 0.4); 
        color: #000;
    }
    
    .status-pill { font-weight: 600; font-size: 0.85rem; padding: 4px 14px; border-radius: 50px; }
    .bg-success-light { background-color: rgba(25, 135, 84, 0.2); color: #2ecc71; border: 1px solid rgba(46, 204, 113, 0.4); }
    .bg-danger-light { background-color: rgba(220, 53, 69, 0.2); color: #e74c3c; border: 1px solid rgba(231, 76, 60, 0.4); }

    .composite-box {
        display: none;
        background: var(--pharaoh-surface);
        border: 2px solid #00bcd4;
        border-radius: 8px;
        animation: fadeInSlide 0.3s ease forwards;
    }
    @keyframes fadeInSlide { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
    
    .barcode-badge { font-family: monospace; font-size: 0.8rem; background: var(--pharaoh-surface-light); padding: 3px 8px; border-radius: 4px; color: var(--pharaoh-gold); border: 1px solid rgba(212, 175, 55, 0.15); }
    .text-muted-pharaoh { color: #a0aec0 !important; }

    .modal-content.o_form_view { background: var(--pharaoh-surface) !important; color: #e0e6ed !important; }
    .modal-header.bg-light { background: var(--pharaoh-surface-light) !important; border-bottom: 1px solid rgba(212, 175, 55, 0.1) !important; }
    .modal-header .modal-title { color: var(--pharaoh-gold); font-family: 'Reem Kufi', serif; }
    .modal-header .btn-close { filter: invert(1); }
    
    .form-control, .form-select {
        background-color: var(--pharaoh-surface-light) !important;
        color: #ffffff !important;
        border: 1px solid rgba(212, 175, 55, 0.2) !important;
    }
    .form-control:focus, .form-select:focus {
        border-color: var(--pharaoh-gold) !important;
        box-shadow: 0 0 8px rgba(212, 175, 55, 0.3) !important;
        color: #fff !important;
    }
    .form-control::placeholder { color: #718096; }
</style>

<!-- الشعلة اليسرى -->
<div class="torch-wrapper left">
    <div class="smoke-container">
        <span class="smoke-particle sm1"></span>
        <span class="smoke-particle sm2"></span>
        <span class="smoke-particle sm3"></span>
    </div>
    <div class="pharaoh-fire"></div>
    <div class="torch-cup"></div>
    <div class="torch-holder"><div class="torch-mount"></div></div>
</div>

<!-- الشعلة اليمنى -->
<div class="torch-wrapper right">
    <div class="smoke-container">
        <span class="smoke-particle sm1"></span>
        <span class="smoke-particle sm2"></span>
        <span class="smoke-particle sm3"></span>
    </div>
    <div class="pharaoh-fire"></div>
    <div class="torch-cup"></div>
    <div class="torch-holder"><div class="torch-mount"></div></div>
</div>

<div class="container py-4" dir="rtl">
    <div class="d-flex justify-content-between mb-4 align-items-center">
        <h4 class="fw-bold style-title" style="color: var(--pharaoh-gold); font-family: 'Reem Kufi', serif;"><i class="fa fa-boxes me-2"></i>المخزن الرئيسي (فرع #<?= $current_branch_id ?>)</h4>
        <div class="d-flex gap-2">
            <a href="?export=excel" class="btn btn-success shadow-sm fw-bold px-3">
                <i class="fa fa-file-excel me-1"></i> تصدير إلى Excel
            </a>
            <button class="btn btn-pharaoh shadow-sm fw-bold" onclick="openCreateModal()">
                <i class="fa fa-plus me-1"></i> إنشاء صنف جديد
            </button>
        </div>
    </div>

    <div class="o_form_view table-responsive">
        <table class="table table-hover mb-0 text-end align-middle">
            <thead class="table-light">
                <tr>
                    <th class="ps-4">المنتج</th>
                    <th>النوع</th>
                    <th>الرصيد المتاح حالياً</th>
                    <th>الكمية المباعة</th>
                    <th>الحالة</th>
                    <th class="text-center">طباعة الباركود</th>
                    <th class="text-center">تعديل</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($products as $p): ?>
                <tr onclick='editProduct(<?= json_encode($p, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>)' style="cursor: pointer;">
                    <td class="ps-4">
                        <span class="fw-bold d-block text-white"><?= htmlspecialchars($p['product_name']) ?></span>
                        <?php if(!empty($p['barcode'])): ?>
                            <span class="barcode-badge mt-1 d-inline-block"><i class="fa fa-barcode"></i> <?= htmlspecialchars($p['barcode']) ?></span>
                        <?php endif; ?>
                    </td>
                    <td><?= $p['is_composite'] ? '<span class="badge bg-info text-dark fw-bold">منتج مركب</span>' : '<span class="badge bg-warning text-dark fw-bold">خام الرئيسي</span>' ?></td>
                    <td>
                        <?php 
                        if($p['is_composite']) {
                            if(($p['raw_unit'] == 'كيلو' || $p['raw_unit'] == 'kg') && $p['consumption_qty'] > 0) {
                                $available_packages = ($p['current_balance'] * 1000) / $p['consumption_qty'];
                                echo "<span class='fw-bold' style='color: var(--pharaoh-gold);'>" . number_format($available_packages, 1) . "</span> عبوة/كوب متاح";
                                echo " <small class='text-muted-pharaoh'>(يسحب من: " . number_format($p['current_balance'], 2) . " كيلو خام)</small>";
                            } else {
                                echo number_format($p['current_balance'], 2) . " " . $p['unit'];
                            }
                        } else {
                            echo "<strong style='color: var(--pharaoh-gold);'>" . number_format($p['current_balance'], 2) . "</strong> " . $p['unit'];
                        }
                        ?>
                    </td>
                    
                    <td><strong class="text-success"><?= number_format($p['total_sold'], 2) ?></strong> <?= $p['unit'] ?></td>

                    <td>
                        <?php 
                        $is_low = false;
                        if($p['is_composite']) {
                            if(($p['raw_unit'] == 'كيلو' || $p['raw_unit'] == 'kg') && $p['consumption_qty'] > 0) {
                                $available_qty = ($p['current_balance'] * 1000) / $p['consumption_qty'];
                                if($available_qty <= $p['min_limit']) { $is_low = true; }
                            }
                        } else {
                            if($p['current_balance'] <= $p['min_limit']) { $is_low = true; }
                        }
                        
                        if($is_low): ?>
                            <span class="status-pill bg-danger-light">منخفض</span>
                        <?php else: ?>
                            <span class="status-pill bg-success-light">متوفر</span>
                        <?php endif; ?>
                    </td>

                    <td class="text-center">
                        <button type="button" class="btn btn-sm btn-outline-light" onclick="event.stopPropagation(); printBarcode('<?= htmlspecialchars($p['barcode'] ?? '') ?>', '<?= htmlspecialchars(addslashes($p['product_name'])) ?>', '<?= number_format($p['price'], 2) ?>')" title="طباعة ملصق الباركود" style="border-color: rgba(212,175,55,0.4); color: var(--pharaoh-gold); background: transparent;">
                            <i class="fa fa-print"></i>
                        </button>
                    </td>

                    <td class="text-center"><i class="fa fa-pencil-alt text-muted-pharaoh small"></i></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal تفاصيل الصنف -->
<div class="modal fade" id="odooModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form method="POST" class="modal-content o_form_view text-end" onsubmit="return handleFormSubmit(event)">
            <div class="modal-header border-0 bg-light">
                <h5 class="modal-title fw-bold" id="m_title">تفاصيل الصنف</h5>
                <button type="button" class="btn-close ms-0 me-auto" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4" dir="rtl">
                <input type="hidden" name="p_id" id="f_id">
                
                <div class="row g-3">
                    <div class="col-md-6 mb-2">
                        <label class="text-muted-pharaoh small fw-bold">اسم المنتج <span class="text-danger">*</span></label>
                        <input type="text" name="p_name" id="f_name" class="form-control fw-bold border-0 p-3" placeholder="مثال: بن ساده 100 جرام أو كابتشينو..." required>
                    </div>
                    <div class="col-md-6 mb-2">
                        <label class="text-muted-pharaoh small fw-bold"><i class="fa fa-barcode text-secondary"></i> الباركود</label>
                        <input type="text" name="p_barcode" id="f_barcode" class="form-control fw-bold border-0 p-3" placeholder="امسح الباركود هنا أو سيتم توليده تلقائياً">
                    </div>
                    
                    <div class="col-md-6">
                        <label class="text-muted-pharaoh small fw-bold">سعر البيع</label>
                        <input type="number" step="0.01" name="p_price" id="f_price" class="form-control shadow-none" required>
                    </div>
                    <div class="col-md-6">
                        <label class="text-muted-pharaoh small fw-bold">الوحدة (التي تظهر بالفاتورة)</label>
                        <select name="p_unit" id="f_unit" class="form-select shadow-none">
                            <option value="قطعة">قطعة</option>
                            <option value="جرام">جرام</option>
                            <option value="كيلو">كيلو</option>
                            <option value="كوب">كوب</option>
                        </select>
                    </div>

                    <div class="col-12 mt-4">
                        <div class="p-4 border rounded" style="background: rgba(255,255,255,0.02); border-color: rgba(212,175,55,0.1) !important;">
                            <div class="form-check form-switch mb-0 d-flex align-items-center gap-3">
                                <input class="form-check-input" type="checkbox" name="is_composite" id="f_is_comp" onchange="toggleBox()" style="cursor:pointer;">
                                <label class="form-check-label fw-bold" for="f_is_comp" style="color: var(--pharaoh-gold); cursor:pointer;">هذا صنف مركب (يسحب من وزن صنف خام رئيسي)</label>
                            </div>

                            <div id="compBox" class="composite-box p-3 mt-3 border-info border-start border-4">
                                <div class="row g-3">
                                    <div class="col-md-12">
                                        <label class="small fw-bold text-info">يرتبط بالخامة الكبيرة (البن الرئيسي):</label>
                                        <select name="raw_product_id" id="f_raw_id" class="form-select border-info border-opacity-25 shadow-none">
                                            <option value="">-- اختر الصنف الخام (البن الكبير بالكيلو) --</option>
                                            <?php foreach($raw_materials as $raw): ?>
                                                <option value="<?= $raw['id'] ?>"><?= htmlspecialchars($raw['product_name']) ?> (يقاس بـ <?= $raw['unit'] ?>)</option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="small fw-bold text-info">الوزن المستهلك عند البيع (بالجرام):</label>
                                        <input type="number" step="0.001" name="consumption_qty" id="f_cons" class="form-control border-info border-opacity-25" placeholder="مثال: 100 جرام">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="small fw-bold text-danger">حد التنبيه (كم قطعة متبقية بالخام):</label>
                                        <input type="number" step="0.001" name="comp_grams_limit" id="f_comp_limit" class="form-control border-danger border-opacity-25" placeholder="مثال: لو متبقي أقل من 5 قطع نبهني">
                                    </div>
                                </div>
                            </div>

                            <div id="normalFields" class="row mt-3 g-3">
                                <div class="col-md-6">
                                    <label class="small fw-bold text-muted-pharaoh">الكمية الافتتاحية الحالية بالمخزن:</label>
                                    <input type="number" step="0.001" name="initial_qty" id="f_qty" class="form-control" placeholder="مثال: أدخل 4 ليكون رصيدك 4 كيلو">
                                </div>
                                <div class="col-md-6">
                                    <label class="small fw-bold text-muted-pharaoh">حد تنبيه النقصان:</label>
                                    <input type="number" step="0.001" name="p_limit" id="f_limit" class="form-control" placeholder="مثال: 0.5 كيلو">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer border-0 p-4">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                <button type="submit" name="save_product" class="btn btn-pharaoh px-5 fw-bold">حفظ البيانات</button>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.0/dist/JsBarcode.all.min.js"></script>

<script>
var myModal;
document.addEventListener('DOMContentLoaded', function() {
    myModal = new bootstrap.Modal(document.getElementById('odooModal'));

    document.getElementById('f_barcode').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            document.getElementById('f_price').focus();
        }
    });
});

function toggleBox() {
    const isComp = document.getElementById('f_is_comp').checked;
    document.getElementById('compBox').style.display = isComp ? 'block' : 'none';
    document.getElementById('normalFields').style.display = isComp ? 'none' : 'flex';
    
    document.getElementById('f_raw_id').required = isComp;
    document.getElementById('f_cons').required = isComp;
}

function openCreateModal() {
    document.getElementById('f_id').value = "";
    document.getElementById('m_title').innerText = "إضافة صنف جديد للمخزن";
    
    const inputs = document.querySelectorAll('#odooModal input:not([type=checkbox])');
    inputs.forEach(i => i.value = "");
    
    document.getElementById('f_is_comp').checked = false;
    toggleBox();
    myModal.show();
    
    setTimeout(() => {
        let barcodeInput = document.getElementById('f_barcode');
        if(barcodeInput.value === "") {
            barcodeInput.value = "2026" + Math.floor(10000000 + Math.random() * 90000000);
        }
        barcodeInput.focus();
    }, 500);
}

function editProduct(data) {
    document.getElementById('f_id').value = data.id;
    document.getElementById('m_title').innerText = "تعديل بيانات: " + data.product_name;
    document.getElementById('f_name').value = data.product_name;
    document.getElementById('f_barcode').value = data.barcode ? data.barcode : "";
    document.getElementById('f_price').value = data.price;
    document.getElementById('f_unit').value = data.unit;
    
    const isComp = (data.is_composite == 1);
    document.getElementById('f_is_comp').checked = isComp;
    
    if(isComp) {
        document.getElementById('f_raw_id').value = data.raw_product_id;
        document.getElementById('f_cons').value = data.consumption_qty;
        document.getElementById('f_comp_limit').value = data.min_limit;
    } else {
        document.getElementById('f_qty').value = data.current_balance;
        document.getElementById('f_limit').value = data.min_limit;
    }
    
    toggleBox();
    myModal.show();
}

function printBarcode(code, name, price) {
    if (!code || code === '') { alert('لا يوجد باركود لهذا المنتج للطباعة!'); return; }
    
    var printWindow = window.open('', '_blank', 'width=400,height=400');
    
    var htmlContent = '<html>' +
        '<head>' +
            '<title>طباعة الباركود</title>' +
            '<style>' +
                '@media print {' +
                    '@page { size: 38mm 25mm; margin: 0; }' +
                    'body { ' +
                        'margin: 0; ' +
                        'padding: 1mm; ' +
                        'text-align: center; ' +
                        'font-family: Arial, sans-serif; ' +
                        'display: flex; ' +
                        'flex-direction: column; ' +
                        'justify-content: center; ' +
                        'align-items: center; ' +
                        'height: 100vh; ' +
                        'box-sizing: border-box;' +
                        'overflow: hidden;' +
                    '}' +
                    '.info-row {' +
                        'display: flex;' +
                        'justify-content: space-between;' +
                        'width: 100%;' +
                        'font-size: 11px;' +
                        'font-weight: bold;' +
                        'margin-bottom: 2px;' +
                        'box-sizing: border-box;' +
                        'padding: 0 2mm;' +
                        'direction: rtl;' +
                    '}' +
                    '.name { ' +
                        'white-space: nowrap; ' +
                        'overflow: hidden; ' +
                        'text-overflow: ellipsis; ' +
                        'max-width: 60%;' +
                        'text-align: right;' +
                    '}' +
                    '.price {' +
                        'color: #000;' +
                        'max-width: 40%;' +
                        'text-align: left;' +
                        'white-space: nowrap;' +
                    '}' +
                    'svg { width: 100%; max-height: 14mm; }' +
                '}' +
            '</style>' +
        '</head>' +
        '<body>' +
            '<div class="info-row">' +
                '<span class="name">' + name + '</span>' +
                '<span class="price">' + price + ' ج.م</span>' +
            '</div>' +
            '<svg id="barcode"></svg>' +
            '<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.0/dist/JsBarcode.all.min.js"><\/script>' +
            '<script>' +
                'JsBarcode("#barcode", "' + code + '", {' +
                    'format: "CODE128",' +
                    'displayValue: true,' +
                    'fontSize: 12,' +
                    'margin: 0,' +
                    'height: 35' +
                '});' +
                'setTimeout(function() {' +
                    'window.print();' +
                    'window.close();' +
                '}, 500);' +
            '<\/script>' +
        '</body>' +
        '</html>';
        
    printWindow.document.write(htmlContent);
    printWindow.document.close();
}
</script>

<?php include 'footer.php'; ?>