<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/functions.php';
$conn = offers_db();
if (!$conn) die('Database connection not found.');

$products = offers_fetch_products_with_variants($conn);
$companies = offers_fetch_companies($conn);
$hasVariantInIndividual = offers_table_has_column($conn, 'individual_offers', 'variant_id');
$hasVariantInQuantity = offers_table_has_column($conn, 'quantity_offers', 'variant_id');
$hasVariantInBundle = offers_table_has_column($conn, 'bundle_offer_items', 'variant_id');
$type = $_GET['type'] ?? ($_POST['type'] ?? 'individual');
$errors = [];
$form = ['title'=>'','status'=>1,'notes'=>'','start_date'=>'','end_date'=>'','product_id'=>0,'variant_id'=>0,'required_qty'=>2,'new_price'=>'','new_price_total'=>'','company_id'=>0,'discount_type'=>'percent','discount_value'=>''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = $_POST['type'] ?? 'individual';
    $title = trim((string)($_POST['title'] ?? ''));
    $status = isset($_POST['status']) ? (int)$_POST['status'] : 1;
    $notes = trim((string)($_POST['notes'] ?? ''));
    $start = offers_parse_datetime($_POST['start_date'] ?? '') ?: null;
    $end = offers_parse_datetime($_POST['end_date'] ?? '') ?: null;
    $form = array_merge($form, $_POST);
    if ($title === '') $errors[] = 'عنوان العرض مطلوب.';

    try {
        if ($type === 'individual') {
            $productId = (int)($_POST['product_id'] ?? 0);
            $variantId = $hasVariantInIndividual ? (int)($_POST['variant_id'] ?? 0) : 0;
            $newPrice = (float)($_POST['new_price'] ?? 0);
            if ($productId <= 0) $errors[] = 'اختر المنتج.';
            $basePrice = 0.0;
            foreach ($products as $p) {
                if ((int)$p['id'] !== $productId) continue;
                $basePrice = (float)$p['price'];
                if ($variantId > 0) {
                    foreach ($p['variants'] as $v) if ((int)$v['id'] === $variantId) $basePrice = (float)$v['price'];
                }
                break;
            }
            if ($newPrice <= 0 || $newPrice >= $basePrice) $errors[] = 'السعر الجديد يجب أن يكون أقل من السعر الأصلي.';
            if (!$errors) {
                $sql = "INSERT INTO individual_offers (title, product_id, " . ($hasVariantInIndividual ? 'variant_id, ' : '') . " old_price, new_price, start_date, end_date, status, notes, created_at, updated_at) VALUES (?, ?, " . ($hasVariantInIndividual ? '?, ' : '') . " ?, ?, ?, ?, ?, ?, NOW(), NOW())";
                $stmt = $conn->prepare($sql);
                if ($hasVariantInIndividual) {
                    $stmt->bind_param('siiddssis', $title, $productId, $variantId, $basePrice, $newPrice, $start, $end, $status, $notes);
                } else {
                    $stmt->bind_param('siddssis', $title, $productId, $basePrice, $newPrice, $start, $end, $status, $notes);
                }
                $stmt->execute(); $stmt->close();
            }
        } elseif ($type === 'quantity') {
            $productId = (int)($_POST['product_id'] ?? 0);
            $variantId = $hasVariantInQuantity ? (int)($_POST['variant_id'] ?? 0) : 0;
            $requiredQty = max(2, (int)($_POST['required_qty'] ?? 2));
            $newTotal = (float)($_POST['new_price_total'] ?? 0);
            $basePrice = 0.0;
            foreach ($products as $p) {
                if ((int)$p['id'] !== $productId) continue;
                $basePrice = (float)$p['price'];
                if ($variantId > 0) { foreach ($p['variants'] as $v) if ((int)$v['id'] === $variantId) $basePrice = (float)$v['price']; }
                break;
            }
            $oldTotal = $basePrice * $requiredQty;
            if ($productId <= 0) $errors[] = 'اختر المنتج.';
            if ($newTotal <= 0 || $newTotal >= $oldTotal) $errors[] = 'السعر النهائي للكمية لازم يكون أقل من مجموع السعر الأصلي.';
            if (!$errors) {
                $sql = "INSERT INTO quantity_offers (title, product_id, " . ($hasVariantInQuantity ? 'variant_id, ' : '') . " required_qty, old_price_total, new_price_total, start_date, end_date, status, notes, created_at, updated_at) VALUES (?, ?, " . ($hasVariantInQuantity ? '?, ' : '') . " ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
                $stmt = $conn->prepare($sql);
                if ($hasVariantInQuantity) {
                    $stmt->bind_param('siiiddssis', $title, $productId, $variantId, $requiredQty, $oldTotal, $newTotal, $start, $end, $status, $notes);
                } else {
                    $stmt->bind_param('siiddssis', $title, $productId, $requiredQty, $oldTotal, $newTotal, $start, $end, $status, $notes);
                }
                $stmt->execute(); $stmt->close();
            }
        } elseif ($type === 'bundle') {
            $bundleIds = $_POST['bundle_product_id'] ?? [];
            $bundleVar = $_POST['bundle_variant_id'] ?? [];
            $bundleQty = $_POST['bundle_qty'] ?? [];
            $items = []; $oldTotal = 0.0;
            foreach ($bundleIds as $i => $pidRaw) {
                $pid = (int)$pidRaw; $vid = $hasVariantInBundle ? (int)($bundleVar[$i] ?? 0) : 0; $qty = max(0, (int)($bundleQty[$i] ?? 0));
                if ($pid <= 0 || $qty <= 0) continue;
                foreach ($products as $p) {
                    if ((int)$p['id'] !== $pid) continue;
                    $price = (float)$p['price'];
                    if ($vid > 0) { foreach ($p['variants'] as $v) if ((int)$v['id'] === $vid) $price = (float)$v['price']; }
                    $items[] = ['product_id'=>$pid,'variant_id'=>$vid,'qty'=>$qty,'unit_price'=>$price,'line_total'=>$price*$qty];
                    $oldTotal += $price*$qty;
                    break;
                }
            }
            $newTotal = (float)($_POST['new_price_total'] ?? 0);
            if (count($items) < 2) $errors[] = 'الباقة تحتاج عنصرين على الأقل.';
            if ($newTotal <= 0 || $newTotal >= $oldTotal) $errors[] = 'سعر الباقة النهائي لازم يكون أقل من مجموعها الأصلي.';
            if (!$errors) {
                $conn->begin_transaction();
                $stmt = $conn->prepare("INSERT INTO bundle_offers (title, item_count, old_price_total, new_price_total, start_date, end_date, status, notes, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
                $itemCount = count($items);
                $stmt->bind_param('siddssis', $title, $itemCount, $oldTotal, $newTotal, $start, $end, $status, $notes);
                $stmt->execute(); $offerId = (int)$conn->insert_id; $stmt->close();
                $sql = "INSERT INTO bundle_offer_items (bundle_offer_id, product_id, " . ($hasVariantInBundle ? 'variant_id, ' : '') . " qty, unit_price, line_total, created_at) VALUES (?, ?, " . ($hasVariantInBundle ? '?, ' : '') . " ?, ?, ?, NOW())";
                $stmt = $conn->prepare($sql);
                foreach ($items as $item) {
                    if ($hasVariantInBundle) $stmt->bind_param('iiiidd', $offerId, $item['product_id'], $item['variant_id'], $item['qty'], $item['unit_price'], $item['line_total']);
                    else $stmt->bind_param('iiidd', $offerId, $item['product_id'], $item['qty'], $item['unit_price'], $item['line_total']);
                    $stmt->execute();
                }
                $stmt->close();
                $conn->commit();
            }
        } else {
            $companyId = (int)($_POST['company_id'] ?? 0);
            $discountType = $_POST['discount_type'] ?? 'percent';
            $discountValue = (float)($_POST['discount_value'] ?? 0);
            if ($companyId <= 0) $errors[] = 'اختر البراند.';
            if ($discountValue <= 0) $errors[] = 'قيمة الخصم غير صالحة.';
            if (!$errors) {
                $stmt = $conn->prepare("INSERT INTO company_offers (title, company_id, discount_type, discount_value, start_date, end_date, status, notes, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
                $stmt->bind_param('sisdssis', $title, $companyId, $discountType, $discountValue, $start, $end, $status, $notes);
                $stmt->execute(); $stmt->close();
            }
        }

        if (!$errors) {
            offers_flash_set('success', 'تم إنشاء العرض بنجاح.');
            header('Location: list.php'); exit;
        }
    } catch (Throwable $e) {
        $errors[] = 'تعذر حفظ العرض: ' . $e->getMessage();
        if ($conn->errno) @$conn->rollback();
    }
}
$page_title = 'العروض';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<link rel="stylesheet" href="assets/offers.css">
<div class="ofr-wrap"><div class="ofr-page-title"><div><h1>إضافة عرض جديد</h1><div class="ofr-muted">تم دعم اختيار الفاريانت داخل العروض وربطها لاحقاً داخل الطلبات.</div></div><div class="ofr-actions"><a class="btn btn-light" href="index.php">رجوع</a><a class="btn btn-dark" href="list.php">كل العروض</a></div></div>
<?php if ($errors): ?><div class="notice error"><?php foreach($errors as $err): ?><div><?= offers_h($err); ?></div><?php endforeach; ?></div><?php endif; ?>
<form method="get" class="box"><div class="row3"><div class="field"><label>نوع العرض</label><select name="type" onchange="this.form.submit()"><option value="individual" <?= $type==='individual'?'selected':''; ?>>فردي</option><option value="bundle" <?= $type==='bundle'?'selected':''; ?>>باقة</option><option value="quantity" <?= $type==='quantity'?'selected':''; ?>>كمية</option><option value="company" <?= $type==='company'?'selected':''; ?>>شركة/براند</option></select></div><div class="price-preview"><strong>مهم</strong><div class="tiny">إذا تريد عرض على فاريانت محدد، اختر المنتج ثم الفاريانت.</div></div></div></form>
<form method="post" id="offer-form"><input type="hidden" name="type" value="<?= offers_h($type); ?>"><div class="box"><h3>البيانات الأساسية</h3><div class="row2"><div class="field"><label>عنوان العرض</label><input type="text" name="title" value="<?= offers_h($form['title']); ?>" required></div><div class="field"><label>الحالة</label><select name="status"><option value="1" <?= ((int)$form['status']===1)?'selected':''; ?>>مفعّل</option><option value="0" <?= ((int)$form['status']===0)?'selected':''; ?>>معطّل</option></select></div></div><div class="row2"><div class="field"><label>تاريخ البداية</label><input type="datetime-local" name="start_date" value="<?= offers_h(str_replace(' ', 'T', substr((string)$form['start_date'],0,16))); ?>"></div><div class="field"><label>تاريخ النهاية</label><input type="datetime-local" name="end_date" value="<?= offers_h(str_replace(' ', 'T', substr((string)$form['end_date'],0,16))); ?>"></div></div><div class="field"><label>ملاحظات</label><textarea name="notes"><?= offers_h($form['notes']); ?></textarea></div></div>
<?php if ($type === 'individual' || $type === 'quantity'): ?>
  <div class="box"><h3><?= $type==='individual' ? 'العرض الفردي' : 'عرض الكمية'; ?></h3><div class="row3"><div class="field"><label>المنتج</label><select name="product_id" id="main_product_id" onchange="refreshMainVariantAndPrice()"><option value="">اختر المنتج</option><?php foreach($products as $p): ?><option value="<?= (int)$p['id'] ?>" <?= ((int)($form['product_id'] ?? 0)===(int)$p['id'])?'selected':''; ?>><?= offers_h($p['name']) ?> - <?= offers_format_money($p['price']) ?></option><?php endforeach; ?></select></div><div class="field"><label>الفاريانت (اختياري)</label><select name="variant_id" id="main_variant_id" data-selected="<?= (int)($form['variant_id'] ?? 0) ?>" onchange="refreshMainVariantAndPrice()"><option value="0">بدون</option></select></div><div class="field"><label>السعر الأصلي</label><input type="text" id="main_old_price" readonly></div></div><?php if($type==='quantity'): ?><div class="row2"><div class="field"><label>الكمية المطلوبة</label><input type="number" min="2" name="required_qty" value="<?= (int)$form['required_qty'] ?>"></div><div class="field"><label>السعر النهائي للكمية</label><input type="number" step="0.01" min="0" name="new_price_total" value="<?= offers_h($form['new_price_total']); ?>" required></div></div><?php else: ?><div class="field"><label>السعر الجديد</label><input type="number" step="0.01" min="0" name="new_price" value="<?= offers_h($form['new_price']); ?>" required></div><?php endif; ?></div>
<?php elseif ($type === 'bundle'): ?>
  <div class="box"><h3>عرض الباقة</h3><div id="bundle-items"><div class="item-row bundle-row"><div class="field"><label>منتج الباقة</label><select name="bundle_product_id[]" class="bundle-product" onchange="refreshBundleRow(this)"><option value="">اختر المنتج</option><?php foreach($products as $p): ?><option value="<?= (int)$p['id'] ?>"><?= offers_h($p['name']) ?> - <?= offers_format_money($p['price']) ?></option><?php endforeach; ?></select></div><div class="field"><label>الفاريانت (اختياري)</label><select name="bundle_variant_id[]" class="bundle-variant" onchange="updateBundlePreview()"><option value="0">بدون</option></select></div><div class="field"><label>الكمية</label><input type="number" min="1" name="bundle_qty[]" class="bundle-qty" value="1" onchange="updateBundlePreview()"></div><div class="actions-inline"><button class="btn btn-danger" type="button" onclick="removeBundleRow(this)">حذف</button></div></div></div><div class="actions-inline" style="margin-bottom:12px"><button class="btn btn-light" type="button" onclick="addBundleRow()">إضافة عنصر جديد</button></div><div class="row2"><div class="field"><label>المجموع الأصلي</label><input type="text" id="bundle_old_total" readonly></div><div class="field"><label>سعر الباقة النهائي</label><input type="number" step="0.01" min="0" name="new_price_total" value="<?= offers_h($form['new_price_total']); ?>" required></div></div></div>
<?php else: ?>
  <div class="box"><h3>عرض شركة / براند</h3><div class="row3"><div class="field"><label>البراند</label><select name="company_id"><option value="">اختر البراند</option><?php foreach($companies as $c): ?><option value="<?= (int)$c['id'] ?>"><?= offers_h($c['name']) ?></option><?php endforeach; ?></select></div><div class="field"><label>نوع الخصم</label><select name="discount_type"><option value="percent">نسبة مئوية</option><option value="fixed">مبلغ ثابت</option></select></div><div class="field"><label>قيمة الخصم</label><input type="number" step="0.01" min="0" name="discount_value" value="<?= offers_h($form['discount_value']); ?>"></div></div></div>
<?php endif; ?>
<div class="box"><button class="btn btn-dark" type="submit">حفظ العرض</button></div></form></div>
<script>
const offerProducts = <?= json_encode($products, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
function getOfferProduct(id){ return offerProducts.find(p => String(p.id) === String(id)); }
function renderVariantOptions(productId, selectEl, selected='0'){
  const p = getOfferProduct(productId); let html='<option value="0">بدون</option>'; if (p && Array.isArray(p.variants)) p.variants.forEach(v => html += `<option value="${v.id}" ${String(selected)===String(v.id)?'selected':''}>${v.variant_name} - ${Number(v.price).toLocaleString()}</option>`); selectEl.innerHTML = html;
}
function getSelectedPrice(productId, variantId){ const p = getOfferProduct(productId); if(!p) return 0; let price = Number(p.price || 0); if(variantId){ const v = (p.variants||[]).find(x => String(x.id)===String(variantId)); if(v) price = Number(v.price||0); } return price; }
function refreshMainVariantAndPrice(){ const productId = document.getElementById('main_product_id'); const variantSel = document.getElementById('main_variant_id'); if(productId && variantSel){ const selected = variantSel.dataset.selected || variantSel.value || '0'; renderVariantOptions(productId.value, variantSel, selected); variantSel.dataset.selected=''; document.getElementById('main_old_price').value = getSelectedPrice(productId.value, variantSel.value).toLocaleString() + ' د.ع'; } }
function refreshBundleRow(select){ const row = select.closest('.bundle-row'); const variantSel = row.querySelector('.bundle-variant'); renderVariantOptions(select.value, variantSel, variantSel.dataset.selected||'0'); updateBundlePreview(); }
function updateBundlePreview(){ let total = 0; document.querySelectorAll('.bundle-row').forEach(row => { total += getSelectedPrice(row.querySelector('.bundle-product').value, row.querySelector('.bundle-variant').value) * Number(row.querySelector('.bundle-qty').value || 0); }); const el = document.getElementById('bundle_old_total'); if (el) el.value = total.toLocaleString() + ' د.ع'; }
function addBundleRow(){ const wrapper = document.getElementById('bundle-items'); const row = wrapper.querySelector('.bundle-row').cloneNode(true); row.querySelectorAll('select,input').forEach(el => { if(el.name==='bundle_qty[]') el.value = 1; else el.value='0'; }); wrapper.appendChild(row); }
function removeBundleRow(btn){ const rows = document.querySelectorAll('.bundle-row'); if(rows.length > 1) btn.closest('.bundle-row').remove(); updateBundlePreview(); }
document.addEventListener('change', function(e){ if(e.target.matches('.bundle-variant,.bundle-qty')) updateBundlePreview(); });
refreshMainVariantAndPrice(); updateBundlePreview();
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
