<?php
require_once '../includes/auth.php';
require_once '../includes/config.php';
require_once '../includes/module_hub_helpers.php';

if (isset($_POST['action'])) {
    header('Content-Type: application/json; charset=utf-8');

    if ($_POST['action'] === 'add') {
        $stmt = $conn->prepare("INSERT INTO provinces (name, delivery_price, status, created_at) VALUES (?, ?, 1, NOW())");
        $stmt->bind_param('sd', $_POST['name'], $_POST['price']);
        $stmt->execute();
        echo json_encode(['status' => 'success']);
        exit;
    }

    if ($_POST['action'] === 'edit') {
        $stmt = $conn->prepare("UPDATE provinces SET name=?, delivery_price=? WHERE id=?");
        $stmt->bind_param('sdi', $_POST['name'], $_POST['price'], $_POST['id']);
        $stmt->execute();
        echo json_encode(['status' => 'success']);
        exit;
    }

    if ($_POST['action'] === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $conn->query("UPDATE provinces SET status = IF(status=1,0,1) WHERE id={$id}");
        echo json_encode(['status' => 'success']);
        exit;
    }

    if ($_POST['action'] === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $check = hub_fetch_value($conn, "SELECT COUNT(*) AS c FROM customers WHERE province_id={$id}");
        if ($check > 0) {
            echo json_encode(['status' => 'error', 'msg' => 'مرتبطة بزبائن']);
            exit;
        }
        $conn->query("DELETE FROM provinces WHERE id={$id}");
        echo json_encode(['status' => 'success']);
        exit;
    }
}

$rows = hub_fetch_all($conn, "SELECT p.*, (SELECT COUNT(*) FROM customers c WHERE c.province_id = p.id) AS customers_count FROM provinces p ORDER BY p.id DESC");
$total = count($rows);
$active = 0;
$inactive = 0;
$highest = 0.0;
foreach ($rows as $row) {
    if ((int)$row['status'] === 1) $active++; else $inactive++;
    $highest = max($highest, (float)$row['delivery_price']);
}
$page_title = 'الرئيسية - المحافظات';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>
<style>
.prov-actions{display:flex;gap:8px;flex-wrap:wrap}.prov-btn{border:0;border-radius:12px;padding:8px 12px;cursor:pointer;font-weight:700}.prov-btn.primary{background:#2563eb;color:#fff}.prov-btn.warn{background:#f59e0b;color:#fff}.prov-btn.success{background:#16a34a;color:#fff}.prov-btn.danger{background:#dc2626;color:#fff}
.prov-input{width:100%;padding:10px 12px;border:1px solid #dbe3ef;border-radius:12px;background:#fff}.prov-input[readonly]{background:#f8fafc;color:#475569}
.prov-modal{display:none;position:fixed;inset:0;background:rgba(15,23,42,.4);z-index:1300;align-items:center;justify-content:center;padding:16px}.prov-modal.open{display:flex}.prov-modal-card{width:min(420px,100%);background:#fff;border-radius:20px;padding:20px;box-shadow:0 25px 60px rgba(15,23,42,.18)}
.prov-form-grid{display:grid;gap:10px;margin-top:12px}.prov-toast{position:fixed;top:20px;left:20px;background:#16a34a;color:#fff;padding:12px 16px;border-radius:12px;display:none;z-index:1500}.prov-toast.error{background:#dc2626}
.switch{position:relative;display:inline-block;width:48px;height:26px}.switch input{display:none}.slider{position:absolute;inset:0;background:#cbd5e1;border-radius:999px;cursor:pointer;transition:.2s}.slider:before{content:'';position:absolute;width:20px;height:20px;right:4px;top:3px;background:#fff;border-radius:50%;transition:.2s}.switch input:checked + .slider{background:#22c55e}.switch input:checked + .slider:before{transform:translateX(-22px)}
</style>
<div class="nay-dashboard-page">
    <div class="nay-dashboard-main">
        <div class="nay-dashboard-hero">
            <div>
                <h1>الرئيسية - المحافظات والتوصيل</h1>
                <p>واجهة موحدة لمراجعة المحافظات، أسعار التوصيل، وعدد الزبائن المرتبطين بكل محافظة. من هنا تكدر تضيف أو تعدل أو توقف أي محافظة بسرعة.</p>
            </div>
            <div class="nay-actions">
                <button class="nay-btn primary" type="button" onclick="openProvinceModal()"><i class="fa-solid fa-plus"></i> إضافة محافظة</button>
                <a class="nay-btn" href="index.php"><i class="fa-solid fa-rotate-right"></i> تحديث الصفحة</a>
            </div>
        </div>

        <div class="nay-stats-grid">
            <div class="nay-card"><div class="nay-stat-label">إجمالي المحافظات</div><div class="nay-stat-value"><?= number_format($total) ?></div><div class="nay-stat-sub">كل المحافظات المعرفة</div></div>
            <div class="nay-card"><div class="nay-stat-label">مفعّلة</div><div class="nay-stat-value"><?= number_format($active) ?></div><div class="nay-stat-sub">جاهزة للاستخدام</div></div>
            <div class="nay-card"><div class="nay-stat-label">معطّلة</div><div class="nay-stat-value"><?= number_format($inactive) ?></div><div class="nay-stat-sub">موقوفة حالياً</div></div>
            <div class="nay-card"><div class="nay-stat-label">أعلى أجور توصيل</div><div class="nay-stat-value"><?= number_format($highest,0) ?></div><div class="nay-stat-sub">أعلى سعر مسجل</div></div>
        </div>

        <div class="nay-card">
            <h3>قائمة المحافظات</h3>
            <div class="nay-table-wrap">
                <table class="nay-table" id="provinceTable">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>اسم المحافظة</th>
                            <th>أجور التوصيل</th>
                            <th>عدد الزبائن</th>
                            <th>الحالة</th>
                            <th>التحكم</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rows as $row): ?>
                            <tr id="row-<?= (int)$row['id'] ?>">
                                <td><?= (int)$row['id'] ?></td>
                                <td><input class="prov-input" type="text" id="name-<?= (int)$row['id'] ?>" value="<?= htmlspecialchars((string)$row['name']) ?>" readonly></td>
                                <td><input class="prov-input" type="number" id="price-<?= (int)$row['id'] ?>" value="<?= htmlspecialchars((string)$row['delivery_price']) ?>" readonly></td>
                                <td><?= number_format((int)$row['customers_count']) ?></td>
                                <td>
                                    <label class="switch">
                                        <input type="checkbox" <?= (int)$row['status'] === 1 ? 'checked' : '' ?> onchange="toggleProvince(<?= (int)$row['id'] ?>)">
                                        <span class="slider"></span>
                                    </label>
                                </td>
                                <td>
                                    <div class="prov-actions">
                                        <button class="prov-btn warn" type="button" onclick="enableEdit(<?= (int)$row['id'] ?>)">تعديل</button>
                                        <button class="prov-btn success" type="button" onclick="saveProvince(<?= (int)$row['id'] ?>)">حفظ</button>
                                        <button class="prov-btn danger" type="button" onclick="deleteProvince(<?= (int)$row['id'] ?>)">حذف</button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="prov-modal" id="provinceModal">
    <div class="prov-modal-card">
        <h3 style="margin:0 0 10px;">إضافة محافظة جديدة</h3>
        <div class="prov-form-grid">
            <input class="prov-input" type="text" id="new_name" placeholder="اسم المحافظة">
            <input class="prov-input" type="number" id="new_price" placeholder="أجور التوصيل">
            <div class="prov-actions" style="justify-content:flex-end;margin-top:6px;">
                <button class="prov-btn success" type="button" onclick="addProvince()">إضافة</button>
                <button class="prov-btn" type="button" onclick="closeProvinceModal()">إلغاء</button>
            </div>
        </div>
    </div>
</div>
<div class="prov-toast" id="provToast"></div>

<script>
function showToast(msg, type = 'success') {
    const toast = document.getElementById('provToast');
    toast.textContent = msg;
    toast.className = 'prov-toast' + (type === 'error' ? ' error' : '');
    toast.style.display = 'block';
    setTimeout(() => toast.style.display = 'none', 2800);
}
function openProvinceModal(){document.getElementById('provinceModal').classList.add('open');}
function closeProvinceModal(){document.getElementById('provinceModal').classList.remove('open');}
function enableEdit(id){document.getElementById('name-'+id).readOnly=false;document.getElementById('price-'+id).readOnly=false;}
function request(data){return fetch('index.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams(data)}).then(r=>r.json());}
function addProvince(){
    const name=document.getElementById('new_name').value.trim();
    const price=document.getElementById('new_price').value.trim();
    if(!name||price===''){showToast('عبّي الاسم والسعر','error');return;}
    request({action:'add',name,price}).then(res=>{if(res.status==='success'){location.reload();}else{showToast(res.msg||'صار خطأ','error');}});
}
function saveProvince(id){
    request({action:'edit',id,name:document.getElementById('name-'+id).value.trim(),price:document.getElementById('price-'+id).value.trim()})
        .then(res=>{if(res.status==='success'){showToast('تم حفظ التعديل');document.getElementById('name-'+id).readOnly=true;document.getElementById('price-'+id).readOnly=true;}else{showToast(res.msg||'تعذر الحفظ','error');}});
}
function toggleProvince(id){request({action:'toggle',id}).then(()=>showToast('تم تحديث الحالة'));}
function deleteProvince(id){if(!confirm('متأكد من حذف المحافظة؟')) return; request({action:'delete',id}).then(res=>{if(res.status==='success'){document.getElementById('row-'+id)?.remove();showToast('تم حذف المحافظة');}else{showToast(res.msg||'تعذر الحذف','error');}});}
</script>
<?php require_once '../includes/footer.php'; ?>
