<?php
require_once '../includes/auth.php';
require_once 'functions.php';

$errors = [];
$customers = order_fetch_customers($conn);
$products = order_get_products_for_select($conn);
$paymentMethods = payment_methods_active($conn);
$promos = order_get_promos($conn);
$addons = order_fetch_active_addons($conn);
$adminId = $_SESSION['admin_id'] ?? null;
$customerAddressesMap = [];
foreach ($customers as $customer) {
    $customerAddressesMap[(int)$customer['id']] = order_find_customer_addresses($conn, (int)$customer['id']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $items = [];
    $productIds = $_POST['product_id'] ?? [];
    $variantIds = $_POST['variant_id'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    foreach ($productIds as $idx => $productId) {
        $items[] = [
            'product_id' => $productId,
            'variant_id' => $variantIds[$idx] ?? 0,
            'quantity' => $quantities[$idx] ?? 0,
        ];
    }

    $payload = [
        'customer_id' => $_POST['customer_id'] ?? null,
        'customer_address_id' => $_POST['customer_address_id'] ?? null,
        'customer_name' => $_POST['customer_name'] ?? '',
        'customer_phone' => $_POST['customer_phone'] ?? '',
        'customer_email' => $_POST['customer_email'] ?? '',
        'province' => $_POST['province'] ?? '',
        'city' => $_POST['city'] ?? '',
        'area' => $_POST['area'] ?? '',
        'full_address' => $_POST['full_address'] ?? '',
        'order_type' => $_POST['order_type'] ?? 'delivery',
        'pickup_branch' => $_POST['pickup_branch'] ?? '',
        'preorder_expected_at' => $_POST['preorder_expected_at'] ?? '',
        'deposit_amount' => $_POST['deposit_amount'] ?? 0,
        'payment_method_id' => $_POST['payment_method_id'] ?? 0,
        'payment_status' => $_POST['payment_status'] ?? 'unpaid',
        'order_status' => $_POST['order_status'] ?? 'pending',
        'promo_code_id' => $_POST['promo_code_id'] ?? 0,
        'delivery_fee' => $_POST['delivery_fee'] ?? 0,
        'notes' => $_POST['notes'] ?? '',
        'admin_notes' => $_POST['admin_notes'] ?? '',
        'transaction_reference' => $_POST['transaction_reference'] ?? '',
        'payment_notes' => $_POST['payment_notes'] ?? '',
        'addon_ids' => $_POST['addon_ids'] ?? [],
        'items' => $items,
    ];

    [$ok, $errors, $orderId] = order_create($conn, $payload, $adminId ? (int)$adminId : null);
    if ($ok && $orderId) {
        redirect_to(base_admin_url('orders/view.php?id=' . $orderId));
    }
}

$pageTitle = 'إنشاء طلب';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>
<style>
.box{background:#fff;border-radius:20px;padding:20px;box-shadow:0 12px 32px rgba(25,68,107,.08);margin-bottom:18px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px}.field label{display:block;margin-bottom:7px;font-weight:700;color:#23465f}.field input,.field select,.field textarea{width:100%;padding:11px 13px;border:1px solid #d5e2ec;border-radius:12px}.field textarea{min-height:90px}.field input[readonly],.field textarea[readonly]{background:#f6fafc}.btnx{background:#96b8cc;color:#fff;border:0;border-radius:12px;padding:12px 18px;font-weight:800;cursor:pointer}.btn-add{background:#183b56}.items-table{width:100%;border-collapse:collapse}.items-table th,.items-table td{padding:10px;border-bottom:1px solid #edf3f7}.danger{background:#fff0f0;color:#9e1d1d;padding:12px;border-radius:12px;margin-bottom:14px}.hidden{display:none}.hint{font-size:12px;color:#71839a;margin-top:6px}.addon-list{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}.addon-card{border:1px solid #dbe6ef;border-radius:16px;padding:14px;background:#fbfdff}.addon-card.disabled{opacity:.45}.addon-head{display:flex;align-items:center;justify-content:space-between;gap:10px}.badge-soft{display:inline-flex;padding:4px 10px;border-radius:999px;background:#edf6ff;color:#1d4ed8;font-size:12px;font-weight:700}.soft-note{background:#f8fbfe;border:1px dashed #d2dfeb;border-radius:16px;padding:14px;color:#46627a;line-height:1.8}
</style>
<div class="content-wrapper">
    <div class="page-header"><h1>إنشاء طلب جديد</h1></div>
    <?php if ($errors): ?><div class="danger"><?= e(implode(' | ', $errors)) ?></div><?php endif; ?>

    <form method="post" id="order-form">
        <div class="box">
            <div class="grid">
                <div class="field">
                    <label>الزبون</label>
                    <select name="customer_id" id="customer_id" required>
                        <option value="">اختر الزبون</option>
                        <?php foreach ($customers as $customer): ?>
                            <option value="<?= (int)$customer['id'] ?>" data-name="<?= e($customer['full_name']) ?>" data-phone="<?= e($customer['phone']) ?>" data-email="<?= e($customer['email'] ?? '') ?>" <?= ((string)($_POST['customer_id'] ?? '') === (string)$customer['id']) ? 'selected' : '' ?>><?= e($customer['full_name']) ?> - <?= e($customer['phone']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="field">
                    <label>عنوان الزبون</label>
                    <select name="customer_address_id" id="customer_address_id"></select>
                    <div class="hint">يتم سحب المحافظة والعنوان وأجور التوصيل تلقائياً من العنوان المختار.</div>
                </div>
                <div class="field"><label>اسم الزبون</label><input type="text" name="customer_name" id="customer_name" value="<?= e($_POST['customer_name'] ?? '') ?>" readonly></div>
                <div class="field"><label>رقم الهاتف</label><input type="text" name="customer_phone" id="customer_phone" value="<?= e($_POST['customer_phone'] ?? '') ?>" readonly></div>
                <div class="field"><label>البريد الإلكتروني</label><input type="text" name="customer_email" id="customer_email" value="<?= e($_POST['customer_email'] ?? '') ?>" readonly></div>
                <div class="field"><label>نوع الطلب</label><select name="order_type" id="order_type"><?php foreach(order_type_options() as $k=>$v): ?><option value="<?= e($k) ?>" <?= (($_POST['order_type'] ?? 'delivery')===$k)?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select></div>
                <div class="field type-pickup hidden"><label>فرع / نقطة الاستلام</label><input type="text" name="pickup_branch" value="<?= e($_POST['pickup_branch'] ?? '') ?>"></div>
                <div class="field type-preorder hidden"><label>موعد متوقع للتجهيز</label><input type="datetime-local" name="preorder_expected_at" value="<?= e($_POST['preorder_expected_at'] ?? '') ?>"></div>
                <div class="field type-preorder hidden"><label>العربون</label><input type="number" step="0.01" name="deposit_amount" value="<?= e((string)($_POST['deposit_amount'] ?? 0)) ?>"></div>
                <div class="field"><label>المحافظة</label><input type="text" name="province" id="province" value="<?= e($_POST['province'] ?? '') ?>" readonly></div>
                <div class="field"><label>المدينة</label><input type="text" name="city" id="city" value="<?= e($_POST['city'] ?? '') ?>" readonly></div>
                <div class="field"><label>المنطقة</label><input type="text" name="area" id="area" value="<?= e($_POST['area'] ?? '') ?>" readonly></div>
                <div class="field" style="grid-column:1/-1"><label>العنوان الكلي</label><textarea name="full_address" id="full_address" readonly><?= e($_POST['full_address'] ?? '') ?></textarea></div>
            </div>
        </div>

        <div class="box">
            <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:10px">
                <h3 style="margin:0">المنتجات</h3>
                <button type="button" class="btnx btn-add" id="add-row">إضافة منتج</button>
            </div>
            <table class="items-table" id="items-table">
                <thead><tr><th>المنتج</th><th>الفاريانت</th><th>الكمية</th><th>حذف</th></tr></thead>
                <tbody>
                    <tr>
                        <td>
                            <select name="product_id[]" class="product-select" required>
                                <option value="">اختر المنتج</option>
                                <?php foreach ($products as $product): ?>
                                    <option value="<?= (int)$product['id'] ?>" data-has-variants="<?= (int)$product['has_variants'] ?>"><?= e($product['name']) ?> - <?= number_format((float)$product['price']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td><select name="variant_id[]" class="variant-select"><option value="">بدون</option></select></td>
                        <td><input type="number" name="quantity[]" min="1" value="1" required></td>
                        <td><button type="button" class="btnx remove-row" style="background:#b84f4f">حذف</button></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="box">
            <h3 style="margin:0 0 12px">الإضافات المدفوعة</h3>
            <div class="soft-note">يمكنك اختيار خدمات مثل تغليف هدية أو توصيل نفس اليوم. بعض الخدمات قد تظهر فقط لمحافظة معينة. عروض الحد الأدنى للسلة والشحن المجاني تُطبَّق تلقائياً عند تحقق الشروط.</div>
            <div class="addon-list" id="addon-list" style="margin-top:14px"></div>
        </div>

        <div class="box">
            <div class="grid">
                <div class="field"><label>طريقة الدفع</label><select name="payment_method_id" id="payment_method_id"><option value="">اختر</option><?php foreach($paymentMethods as $m): ?><option value="<?= (int)$m['id'] ?>" data-manual="<?= (int)$m['requires_manual_confirmation'] ?>"><?= e($m['name']) ?></option><?php endforeach; ?></select></div>
                <div class="field"><label>حالة الدفع</label><select name="payment_status" id="payment_status"><?php foreach(payment_status_options() as $k=>$v): ?><option value="<?= e($k) ?>" <?= (($_POST['payment_status'] ?? 'unpaid')===$k)?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select></div>
                <div class="field"><label>حالة الطلب</label><select name="order_status"><?php foreach(order_status_options() as $k=>$v): ?><option value="<?= e($k) ?>" <?= (($_POST['order_status'] ?? 'pending')===$k)?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select></div>
                <div class="field"><label>بروموكود</label><select name="promo_code_id"><option value="">بدون</option><?php foreach($promos as $promo): ?><option value="<?= (int)$promo['id'] ?>" <?= ((string)($_POST['promo_code_id'] ?? '') === (string)$promo['id']) ? 'selected' : '' ?>><?= e($promo['code']) ?> (<?= e($promo['discount_type']) ?> - <?= e((string)$promo['discount_value']) ?>)</option><?php endforeach; ?></select></div>
                <div class="field"><label>أجور التوصيل</label><input type="number" step="0.01" name="delivery_fee" id="delivery_fee" value="<?= e((string)($_POST['delivery_fee'] ?? 0)) ?>" readonly></div>
                <div class="field manual-payment hidden"><label>رقم العملية / التحويل</label><input type="text" name="transaction_reference"></div>
                <div class="field manual-payment hidden" style="grid-column:1/-1"><label>ملاحظات الدفع</label><textarea name="payment_notes"></textarea></div>
                <div class="field" style="grid-column:1/-1"><label>ملاحظات الزبون</label><textarea name="notes"><?= e($_POST['notes'] ?? '') ?></textarea></div>
                <div class="field" style="grid-column:1/-1"><label>ملاحظات الإدارة</label><textarea name="admin_notes"><?= e($_POST['admin_notes'] ?? '') ?></textarea></div>
            </div>
        </div>

        <button class="btnx" type="submit">حفظ الطلب</button>
    </form>
</div>
<script>
const products = <?= json_encode($products, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
const customerAddressesMap = <?= json_encode($customerAddressesMap, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
const addons = <?= json_encode($addons, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
const selectedAddonIds = <?= json_encode(array_map('intval', $_POST['addon_ids'] ?? []), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
const customerSelect = document.getElementById('customer_id');
const addressSelect = document.getElementById('customer_address_id');
function fillCustomerFields(){ const opt=customerSelect.options[customerSelect.selectedIndex]; document.getElementById('customer_name').value=opt?.dataset?.name||''; document.getElementById('customer_phone').value=opt?.dataset?.phone||''; document.getElementById('customer_email').value=opt?.dataset?.email||''; }
function setAddressData(address){ document.getElementById('province').value=address?.province||''; document.getElementById('city').value=address?.city||''; document.getElementById('area').value=address?.area||''; document.getElementById('full_address').value=address?.full_address||''; document.getElementById('delivery_fee').value=address?.delivery_fee||0; renderAddons(address); }
function fillAddressOptions(){ const cid = customerSelect.value; const addresses = customerAddressesMap[cid] || []; addressSelect.innerHTML=''; if(!addresses.length){ addressSelect.innerHTML='<option value="">لا يوجد عنوان محفوظ</option>'; setAddressData(null); return; } addresses.forEach((addr,idx)=>{ const opt=document.createElement('option'); opt.value=addr.id; opt.textContent=(addr.title?addr.title+' - ':'') + (addr.full_address||'عنوان'); if((<?= json_encode((int)($_POST['customer_address_id'] ?? 0)) ?> && String(<?= json_encode((int)($_POST['customer_address_id'] ?? 0)) ?>)===String(addr.id)) || (!<?= json_encode((int)($_POST['customer_address_id'] ?? 0)) ?> && idx===0)) opt.selected=true; addressSelect.appendChild(opt); }); const chosen=addresses.find(a=>String(a.id)===String(addressSelect.value)) || addresses[0]; setAddressData(chosen); }
function renderAddons(address){ const province = String(address?.province || ''); const box = document.getElementById('addon-list'); box.innerHTML=''; if(!addons.length){ box.innerHTML='<div class="soft-note">ماكو إضافات مدفوعة مفعلة حالياً.</div>'; return; } addons.forEach(addon=>{ const restricted = addon.province_name && addon.province_name !== province; const checked = selectedAddonIds.includes(parseInt(addon.id,10)); const card=document.createElement('label'); card.className='addon-card'+(restricted?' disabled':''); card.innerHTML=`<div class="addon-head"><strong>${addon.title}</strong><span class="badge-soft">${Number(addon.fee||0).toLocaleString()} د.ع</span></div><div style="margin-top:8px;color:#5d7488">${addon.description||''}</div>${addon.province_name?`<div class="hint">متاحة فقط لمحافظة ${addon.province_name}</div>`:''}<div style="margin-top:10px"><input type="checkbox" name="addon_ids[]" value="${addon.id}" ${checked?'checked':''} ${restricted?'disabled':''}> اختيار الخدمة</div>`; box.appendChild(card); }); }
customerSelect.addEventListener('change', function(){ fillCustomerFields(); fillAddressOptions(); });
addressSelect.addEventListener('change', function(){ const addresses = customerAddressesMap[customerSelect.value] || []; const chosen=addresses.find(a=>String(a.id)===String(this.value)) || null; setAddressData(chosen); });
function syncOrderType() { const type = document.getElementById('order_type').value; document.querySelectorAll('.type-pickup').forEach(el=>el.classList.toggle('hidden',type!=='pickup')); document.querySelectorAll('.type-preorder').forEach(el=>el.classList.toggle('hidden',type!=='preorder')); }
document.getElementById('order_type').addEventListener('change',syncOrderType); syncOrderType();
function buildVariantOptions(productId, selected=''){ const p = products.find(x=>String(x.id)===String(productId)); let html='<option value="">بدون</option>'; if(p && p.variants){ p.variants.forEach(v=>html += `<option value="${v.id}" ${String(selected)===String(v.id)?'selected':''}>${v.variant_name}</option>`); } return html; }
function bindRow(row){ row.querySelector('.product-select').addEventListener('change',function(){ row.querySelector('.variant-select').innerHTML=buildVariantOptions(this.value); }); row.querySelector('.remove-row').addEventListener('click',function(){ if(document.querySelectorAll('#items-table tbody tr').length>1){ row.remove(); } }); }
document.querySelectorAll('#items-table tbody tr').forEach(bindRow);
document.getElementById('add-row').addEventListener('click',function(){const tbody=document.querySelector('#items-table tbody');const row=tbody.rows[0].cloneNode(true);row.querySelectorAll('input,select').forEach(el=>{if(el.name==='quantity[]'){el.value=1;} else {el.value=''; if(el.classList.contains('variant-select')) el.innerHTML='<option value="">بدون</option>';}});tbody.appendChild(row);bindRow(row);});
fillCustomerFields(); fillAddressOptions();
</script>
<?php require_once '../includes/footer.php'; ?>
