<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
function b_h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function b_json($d){ header('Content-Type: application/json; charset=utf-8'); echo json_encode($d, JSON_UNESCAPED_UNICODE); exit; }
function b_has_column(mysqli $conn, string $table, string $column): bool {
    $stmt = $conn->prepare("SELECT COUNT(*) AS c FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?");
    $stmt->bind_param('ss', $table, $column);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc() ?: ['c' => 0];
    $stmt->close();
    return (int)($row['c'] ?? 0) > 0;
}
function b_build_insert(mysqli $conn, array $payload, string $table='branches'): array {
    $columns=[]; $values=[]; $types='';
    foreach($payload as $column=>$value){
        if(!b_has_column($conn, $table, $column)) continue;
        $columns[]='`'.$column.'`';
        $values[]=$value;
        $types .= is_int($value) ? 'i' : (is_float($value) ? 'd' : 's');
    }
    $sql='INSERT INTO '.$table.' ('.implode(', ', $columns).') VALUES ('.implode(', ', array_fill(0, count($columns), '?')).')';
    return [$sql,$types,$values];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = (string)$_POST['action'];
    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $name = trim((string)($_POST['name'] ?? ''));
        $code = trim((string)($_POST['code'] ?? ''));
        $provinceId = (int)($_POST['province_id'] ?? 0);
        $address = trim((string)($_POST['address'] ?? ''));
        $phone = trim((string)($_POST['phone'] ?? ''));
        $hours = trim((string)($_POST['working_hours'] ?? ''));
        $pickupNote = trim((string)($_POST['pickup_note'] ?? ''));
        $pickupAvailable = (int)($_POST['pickup_available'] ?? 1) === 1 ? 1 : 0;
        $status = (int)($_POST['status'] ?? 1) === 1 ? 1 : 0;
        $sort = (int)($_POST['sort_order'] ?? 0);
        if ($name === '') b_json(['ok'=>false,'msg'=>'اسم الفرع مطلوب']);
        if ($code === '') $code = strtoupper(trim((string)preg_replace('/[^A-Za-z0-9]+/', '_', $name), '_'));

        if ($id > 0) {
            $stmt = $conn->prepare("UPDATE branches SET name=?, code=?, province_id=?, address=?, phone=?, working_hours=?, pickup_note=?, pickup_available=?, status=?, sort_order=?, updated_at=NOW() WHERE id=? LIMIT 1");
            $stmt->bind_param('ssissssiiii', $name, $code, $provinceId, $address, $phone, $hours, $pickupNote, $pickupAvailable, $status, $sort, $id);
        } else {
            [$sql, $types, $values] = b_build_insert($conn, [
                'name' => $name,
                'code' => $code,
                'province_id' => $provinceId,
                'address' => $address,
                'phone' => $phone,
                'working_hours' => $hours,
                'pickup_note' => $pickupNote,
                'pickup_available' => $pickupAvailable,
                'status' => $status,
                'sort_order' => $sort,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
            $stmt = $conn->prepare($sql);
            $stmt->bind_param($types, ...$values);
        }
        $ok = $stmt && $stmt->execute();
        $msg = $ok ? 'تم حفظ الفرع' : ('تعذر الحفظ: ' . ($stmt ? $stmt->error : $conn->error));
        if ($stmt) $stmt->close();
        b_json(['ok'=>$ok,'msg'=>$msg]);
    }
    if ($action === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $conn->query("UPDATE branches SET status = IF(status=1,0,1), updated_at=NOW() WHERE id={$id}");
        b_json(['ok'=>true,'msg'=>'تم تحديث حالة الفرع']);
    }
    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $conn->query("DELETE FROM branches WHERE id={$id} LIMIT 1");
        b_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 b.*, p.name AS province_name FROM branches b LEFT JOIN provinces p ON p.id = b.province_id ORDER BY b.sort_order ASC, b.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(840px,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}.hint{font-size:12px;color:#64748b}.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
$branchStats = ['total' => count($rows), 'active' => 0, 'pickup' => 0];
foreach ($rows as $row) {
    if ((int)($row['status'] ?? 0) === 1) $branchStats['active']++;
    if ((int)($row['pickup_available'] ?? 0) === 1) $branchStats['pickup']++;
}
?>
<div class="quick-stats-grid">
    <div class="quick-stat-card"><small>كل الفروع</small><strong><?= number_format($branchStats['total']) ?></strong></div>
    <div class="quick-stat-card"><small>المفعلة</small><strong><?= number_format($branchStats['active']) ?></strong></div>
    <div class="quick-stat-card"><small>الاستلام متاح</small><strong><?= number_format($branchStats['pickup']) ?></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><?= b_h($row['name']) ?></strong><div class="hint"><?= b_h($row['code'] ?? '') ?></div></td><td><?= !empty($row['province_name']) ? b_h($row['province_name']) : '—' ?></td><td><div class="hint"><?= b_h($row['address'] ?? '') ?></div><?php if(!empty($row['phone'])): ?><div class="hint">هاتف: <?= b_h($row['phone']) ?></div><?php endif; ?><?php if(!empty($row['working_hours'])): ?><div class="hint">الدوام: <?= b_h($row['working_hours']) ?></div><?php endif; ?></td><td><?= (int)($row['pickup_available'] ?? 1)===1 ? '<span class="mod-chip green">مسموح</span>' : '<span class="mod-chip gray">مغلق</span>' ?></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="name" id="f_name" required></div><div class="mod-field"><label>الكود الداخلي</label><input name="code" id="f_code"></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'] ?>"><?= b_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" style="grid-column:1/-1"><label>العنوان</label><textarea name="address" id="f_address"></textarea></div><div class="mod-field"><label>الهاتف</label><input name="phone" id="f_phone"></div><div class="mod-field"><label>ساعات العمل</label><input name="working_hours" id="f_working_hours"></div><div class="mod-field" style="grid-column:1/-1"><label>ملاحظة الاستلام</label><textarea name="pickup_note" id="f_pickup_note"></textarea></div><div class="mod-field"><label>السماح بالاستلام</label><select name="pickup_available" id="f_pickup_available"><option value="1">مسموح</option><option value="0">مغلق</option></select></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-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'; ?>
