<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
function a_h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function a_json($d){ header('Content-Type: application/json; charset=utf-8'); echo json_encode($d, JSON_UNESCAPED_UNICODE); exit; }
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = (string)$_POST['action'];
    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $title = trim((string)($_POST['title'] ?? ''));
        $code = trim((string)($_POST['code'] ?? ''));
        $fee = max(0, (float)($_POST['fee'] ?? 0));
        $provinceId = (int)($_POST['province_id'] ?? 0);
        $description = trim((string)($_POST['description'] ?? ''));
        $status = (int)($_POST['status'] ?? 1) === 1 ? 1 : 0;
        $sort = (int)($_POST['sort_order'] ?? 0);
        if ($title === '') a_json(['ok'=>false,'msg'=>'اسم الإضافة مطلوب']);
        if ($code === '') $code = strtoupper(preg_replace('/[^A-Za-z0-9_]+/', '_', $title));
        if ($id > 0) {
            $stmt = $conn->prepare("UPDATE order_addons SET title=?, code=?, fee=?, province_id=?, description=?, status=?, sort_order=?, updated_at=NOW() WHERE id=?");
            $stmt->bind_param('ssdissii', $title, $code, $fee, $provinceId, $description, $status, $sort, $id);
        } else {
            $stmt = $conn->prepare("INSERT INTO order_addons (title, code, fee, province_id, description, status, sort_order, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
            $stmt->bind_param('ssdissi', $title, $code, $fee, $provinceId, $description, $status, $sort);
        }
        $ok = $stmt && $stmt->execute();
        $msg = $ok ? 'تم حفظ الإضافة' : ('تعذر الحفظ: ' . ($stmt ? $stmt->error : $conn->error));
        if ($stmt) $stmt->close();
        a_json(['ok'=>$ok,'msg'=>$msg]);
    }
    if ($action === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $conn->query("UPDATE order_addons SET status = IF(status=1,0,1), updated_at=NOW() WHERE id={$id}");
        a_json(['ok'=>true,'msg'=>'تم تحديث الحالة']);
    }
    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $conn->query("DELETE FROM order_addons WHERE id={$id} LIMIT 1");
        a_json(['ok'=>true,'msg'=>'تم حذف الإضافة']);
    }
}
$provinces = [];
if ($res = $conn->query("SELECT id, name FROM provinces WHERE status = 1 ORDER BY name ASC")) { while($row=$res->fetch_assoc()) $provinces[]=$row; $res->close(); }
$rows = [];
$sql = "SELECT oa.*, p.name AS province_name FROM order_addons oa LEFT JOIN provinces p ON p.id = oa.province_id ORDER BY oa.sort_order ASC, oa.id DESC";
if ($res = $conn->query($sql)) { while($row=$res->fetch_assoc()) $rows[]=$row; $res->close(); }
$pageTitle = 'الإضافات المدفوعة';
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>
<style>.mod-actions{display:flex;gap:8px;flex-wrap:wrap}.mod-btn{border:0;border-radius:12px;padding:8px 12px;cursor:pointer;font-weight:700}.mod-btn.warn{background:#f59e0b;color:#fff}.mod-btn.success{background:#16a34a;color:#fff}.mod-btn.danger{background:#dc2626;color:#fff}.mod-btn.dark{background:#0f172a;color:#fff}.mod-modal{display:none;position:fixed;inset:0;background:rgba(15,23,42,.45);z-index:1500;align-items:center;justify-content:center;padding:16px}.mod-modal.open{display:flex}.mod-card{width:min(760px,100%);background:#fff;border-radius:22px;padding:20px;box-shadow:0 24px 60px rgba(15,23,42,.2)}.mod-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.mod-field{display:flex;flex-direction:column;gap:8px}.mod-field input,.mod-field select,.mod-field textarea{width:100%;padding:11px 12px;border:1px solid #dbe3ef;border-radius:12px}.mod-field textarea{min-height:90px;resize:vertical}.mod-chip{display:inline-flex;padding:5px 10px;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-weight:700;font-size:12px}.mod-chip.gray{background:#f1f5f9;color:#475569}.mod-chip.green{background:#ecfdf5;color:#166534}.mod-toast{position:fixed;top:16px;left:16px;background:#16a34a;color:#fff;padding:12px 16px;border-radius:12px;display:none;z-index:1600}.mod-toast.error{background:#dc2626}.quick-stats-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-bottom:16px}.quick-stat-card{background:#fff;border:1px solid #e2e8f0;border-radius:16px;padding:14px}.quick-stat-card small{display:block;color:#64748b;margin-bottom:6px}.quick-stat-card strong{font-size:24px}@media(max-width:768px){.mod-grid,.quick-stats-grid{grid-template-columns:1fr}}</style>
<div class="content-wrapper">
<div class="page-header"><h1>الإضافات المدفوعة</h1><button class="btnx" type="button" onclick="openModal()">إضافة خدمة</button></div>

<?php
$addonStats = ['total' => count($rows), 'active' => 0, 'province_specific' => 0];
foreach ($rows as $row) {
    if ((int)($row['status'] ?? 0) === 1) $addonStats['active']++;
    if ((int)($row['province_id'] ?? 0) > 0) $addonStats['province_specific']++;
}
?>
<div class="quick-stats-grid">
    <div class="quick-stat-card"><small>كل الإضافات</small><strong><?= number_format($addonStats['total']) ?></strong></div>
    <div class="quick-stat-card"><small>المفعلة</small><strong><?= number_format($addonStats['active']) ?></strong></div>
    <div class="quick-stat-card"><small>مقيدة بمحافظة</small><strong><?= number_format($addonStats['province_specific']) ?></strong></div>
</div>

<div class="box"><table class="items-table"><thead><tr><th>#</th><th>الخدمة</th><th>الكود</th><th>الرسوم</th><th>التقييد</th><th>الحالة</th><th>التحكم</th></tr></thead><tbody><?php foreach($rows as $row): ?><tr><td><?= (int)$row['id'] ?></td><td><strong><?= a_h($row['title']) ?></strong><div class="hint"><?= a_h($row['description'] ?? '') ?></div></td><td><span class="mod-chip gray"><?= a_h($row['code']) ?></span></td><td><?= number_format((float)$row['fee'],0) ?> د.ع</td><td><?= !empty($row['province_name']) ? a_h($row['province_name']) : 'كل المحافظات' ?></td><td><?= (int)$row['status']===1 ? '<span class="mod-chip green">مفعلة</span>' : '<span class="mod-chip gray">موقوفة</span>' ?></td><td><div class="mod-actions"><button class="mod-btn warn" type="button" onclick='openModal(<?= json_encode($row, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>)'>تعديل</button><button class="mod-btn dark" type="button" onclick="toggleRow(<?= (int)$row['id'] ?>)">حالة</button><button class="mod-btn danger" type="button" onclick="deleteRow(<?= (int)$row['id'] ?>)">حذف</button></div></td></tr><?php endforeach; ?></tbody></table></div></div>
<div class="mod-modal" id="modModal"><div class="mod-card"><h3 id="modalTitle">إضافة خدمة</h3><form id="saveForm" class="mod-grid" onsubmit="saveRow(event)"><input type="hidden" name="action" value="save"><input type="hidden" name="id" id="f_id"><div class="mod-field"><label>اسم الخدمة</label><input name="title" id="f_title" required></div><div class="mod-field"><label>الكود الداخلي</label><input name="code" id="f_code"></div><div class="mod-field"><label>السعر الإضافي</label><input type="number" step="0.01" min="0" name="fee" id="f_fee" value="0"></div><div class="mod-field"><label>المحافظة المقيدة</label><select name="province_id" id="f_province_id"><option value="0">كل المحافظات</option><?php foreach($provinces as $p): ?><option value="<?= (int)$p['id'] ?>"><?= a_h($p['name']) ?></option><?php endforeach; ?></select></div><div class="mod-field"><label>الترتيب</label><input type="number" step="1" name="sort_order" id="f_sort_order" value="0"></div><div class="mod-field"><label>الحالة</label><select name="status" id="f_status"><option value="1">مفعلة</option><option value="0">موقوفة</option></select></div><div class="mod-field" style="grid-column:1/-1"><label>الوصف</label><textarea name="description" id="f_description"></textarea></div><div class="mod-actions" style="justify-content:flex-end;grid-column:1/-1"><button class="mod-btn success" type="submit">حفظ</button><button class="mod-btn" type="button" onclick="closeModal()">إلغاء</button></div></form></div></div><div class="mod-toast" id="toast"></div>
<script>
function toast(msg, err=false){const t=document.getElementById('toast');t.textContent=msg;t.className='mod-toast'+(err?' error':'');t.style.display='block';setTimeout(()=>t.style.display='none',2200)}
function closeModal(){document.getElementById('modModal').classList.remove('open');}
function openModal(row=null){document.getElementById('saveForm').reset();document.getElementById('f_id').value='';document.getElementById('modalTitle').textContent=row?'تعديل الخدمة':'إضافة خدمة';if(row){for(const k in row){const el=document.getElementById('f_'+k); if(el) el.value=row[k]??'';}}document.getElementById('modModal').classList.add('open');}
async function postData(data){const body = new URLSearchParams(data instanceof FormData ? [...data.entries()] : Object.entries(data)); const res=await fetch('index.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body}); return res.json();}
async function saveRow(e){e.preventDefault(); const res=await postData(new FormData(e.target)); toast(res.msg,!res.ok); if(res.ok) setTimeout(()=>location.reload(),600)}
async function toggleRow(id){const res=await postData({action:'toggle',id}); toast(res.msg,!res.ok); if(res.ok) setTimeout(()=>location.reload(),400)}
async function deleteRow(id){ if(!confirm('تأكيد الحذف؟')) return; const res=await postData({action:'delete',id}); toast(res.msg,!res.ok); if(res.ok) setTimeout(()=>location.reload(),400)}
</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
