<?php
require_once 'auth.php';
requireLogin();

$success = '';
$error = '';

// المحافظات والقطاعات
$govResult = @$conn->query("SELECT * FROM governorates ORDER BY name_ar");
$governorates_list = [];
if ($govResult) { while ($r = $govResult->fetch_assoc()) $governorates_list[] = $r; }
$chk_resp = @$conn->query("SHOW COLUMNS FROM hospitals LIKE 'responsible_person'");
$has_resp = $chk_resp && $chk_resp->num_rows > 0;
$hosp_cols = $has_resp ? "h.id, h.name, h.responsible_person, h.governorate_id, g.name_ar as gov_name, h.phone, h.sector" : "h.id, h.name, h.governorate_id, g.name_ar as gov_name, h.phone, h.sector";

// القطاعات للمستشفيات
$sectors_res = @$conn->query("SELECT name FROM sectors WHERE for_hospitals=1");
if (!$sectors_res) $sectors_res = @$conn->query("SELECT name FROM sectors");
$sectors_for_hospitals = [];
if ($sectors_res) while ($r = $sectors_res->fetch_assoc()) $sectors_for_hospitals[] = $r['name'];

// البحث والفلاتر
$search = trim($_GET['q'] ?? '');
$filter_gov = (int)($_GET['gov'] ?? 0);
$filter_sector = trim($_GET['sector'] ?? '');
$where_parts = [];
$params = [];
$types = '';
if ($search) {
    $where_parts[] = "(h.name LIKE ? OR g.name_ar LIKE ? OR h.phone LIKE ?)";
    $s = "%$search%";
    $params[] = $s; $params[] = $s; $params[] = $s;
    $types .= 'sss';
}
if ($filter_gov) {
    $where_parts[] = "h.governorate_id = ?";
    $params[] = $filter_gov;
    $types .= 'i';
}
if ($filter_sector && in_array($filter_sector, $sectors_for_hospitals)) {
    $where_parts[] = "h.sector = ?";
    $params[] = $filter_sector;
    $types .= 's';
}
$where = $where_parts ? ' WHERE ' . implode(' AND ', $where_parts) : '';
$orderBy = ' ORDER BY h.name ASC';

$sql = "SELECT $hosp_cols FROM hospitals h LEFT JOIN governorates g ON h.governorate_id = g.id $where $orderBy";
if ($params) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $hospitals_list = $stmt->get_result();
} else {
    $hospitals_list = @$conn->query($sql);
}
if (!$hospitals_list) $hospitals_list = null;

// إحصائيات
$stats_total = 0;
$st = @$conn->query("SELECT COUNT(*) c FROM hospitals");
if ($st && $row = $st->fetch_assoc()) $stats_total = (int)($row['c'] ?? 0);
$stats_by_sector = @$conn->query("SELECT sector, COUNT(*) c FROM hospitals GROUP BY sector");
$results_count = $hospitals_list ? $hospitals_list->num_rows : 0;
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <?php include 'includes/favicon.php'; ?>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>قائمة المستشفيات - الزبائن</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <link href="assets/css/dashboard.css" rel="stylesheet">
    <style>
        .hosp-stat-card { border-radius: 16px; transition: transform 0.2s; }
        .hosp-stat-card:hover { transform: translateY(-2px); }
        .hosp-table-cust thead th { background: linear-gradient(135deg, #1e3a5f 0%, #0f172a 100%) !important; color: #fff !important; font-weight: 600; border: none; padding: 0.75rem 1rem; }
        .hosp-table-cust tbody td { padding: 0.7rem 1rem; vertical-align: middle; }
        .hosp-table-cust tbody tr:hover { background-color: #f8fafc; }
        .hosp-table-cust .badge { font-weight: 500; padding: 0.35em 0.6em; border-radius: 8px; font-size: 0.8rem; }
        .hosp-table-cust .btn-sm { width: 34px; height: 34px; padding: 0; display: inline-flex; align-items: center; justify-content: center; border-radius: 8px; margin: 0 2px; }
    </style>
</head>
<body class="dashboard-body">
    <?php include 'includes/header.php'; ?>
    
    <div class="main-content">
        <div class="container-fluid py-4 px-4">
            <nav aria-label="breadcrumb" class="mb-3">
                <ol class="breadcrumb mb-0">
                    <li class="breadcrumb-item"><a href="dashboard.php">الرئيسية</a></li>
                    <li class="breadcrumb-item active">قائمة المستشفيات</li>
                </ol>
            </nav>

            <?php if ($success): ?>
            <div class="alert alert-success d-flex align-items-center mb-4">
                <i class="bi bi-check-circle me-2"></i><?= $success ?>
            </div>
            <?php endif; ?>

            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
                <h2 class="page-title mb-0"><i class="bi bi-hospital me-2"></i>قائمة المستشفيات</h2>
                <div class="d-flex gap-2">
                    <?php if (canExport()): ?><a href="export.php?type=hospitals" class="btn btn-success btn-sm"><i class="bi bi-file-excel me-1"></i> تصدير Excel</a><?php endif; ?>
                    <a href="hospitals.php" class="btn btn-primary btn-sm"><i class="bi bi-plus-circle me-1"></i> إضافة مستشفى</a>
                </div>
            </div>

            <!-- بطاقات الإحصائيات -->
            <div class="row g-3 mb-4">
                <div class="col-6 col-md-3">
                    <div class="card hosp-stat-card h-100" style="background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%); border: 1px solid #93c5fd;">
                        <div class="card-body d-flex align-items-center gap-3 py-3">
                            <div class="rounded-circle bg-primary bg-opacity-25 p-2">
                                <i class="bi bi-hospital text-primary"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $stats_total ?></h3>
                                <small class="text-primary fw-600">إجمالي المستشفيات</small>
                            </div>
                        </div>
                    </div>
                </div>
                <?php if ($stats_by_sector): $si = 0; $statStyles = [['#dcfce7','#bbf7d0','#86efac'],['#fef3c7','#fde68a','#fcd34d'],['#fce7f3','#fbcfe8','#f9a8d4'],['#e0e7ff','#c7d2fe','#a5b4fc']]; while ($st = $stats_by_sector->fetch_assoc()): $ss = $statStyles[$si % 4]; ?>
                <div class="col-6 col-md-3">
                    <div class="card hosp-stat-card h-100" style="background: linear-gradient(135deg, <?= $ss[0] ?> 0%, <?= $ss[1] ?> 100%); border: 1px solid <?= $ss[2] ?>;">
                        <div class="card-body d-flex align-items-center gap-3 py-3">
                            <div class="rounded-circle bg-primary bg-opacity-25 p-2">
                                <i class="bi bi-building text-primary"></i>
                            </div>
                            <div>
                                <h3 class="mb-0 fw-700"><?= $st['c'] ?></h3>
                                <small class="fw-600"><?= htmlspecialchars($st['sector']) ?></small>
                            </div>
                        </div>
                    </div>
                </div>
                <?php $si++; endwhile; endif; ?>
            </div>

            <!-- جدول المستشفيات مع البحث -->
            <div class="card mb-4" style="border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 2px 8px rgba(0,0,0,0.06); overflow: hidden;">
                <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-3 py-3" style="background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); color: #fff; border: none;">
                    <h5 class="mb-0 fw-600"><i class="bi bi-hospital me-2"></i>قائمة المستشفيات <span class="badge bg-light text-dark ms-2"><?= $results_count ?></span></h5>
                    <form method="GET" class="d-flex flex-wrap gap-2 align-items-center">
                        <input type="text" name="q" class="form-control form-control-sm" placeholder="بحث..." value="<?= htmlspecialchars($search) ?>" style="max-width: 160px;">
                        <select name="gov" class="form-select form-select-sm" style="max-width: 140px;">
                            <option value="">كل المحافظات</option>
                            <?php foreach ($governorates_list as $g): ?>
                            <option value="<?= $g['id'] ?>" <?= $filter_gov == $g['id'] ? 'selected' : '' ?>><?= htmlspecialchars($g['name_ar']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select name="sector" class="form-select form-select-sm" style="max-width: 130px;">
                            <option value="">كل القطاعات</option>
                            <?php foreach ($sectors_for_hospitals as $sec): ?>
                            <option value="<?= htmlspecialchars($sec) ?>" <?= $filter_sector === $sec ? 'selected' : '' ?>><?= htmlspecialchars($sec) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button type="submit" class="btn btn-light btn-sm"><i class="bi bi-search me-1"></i>بحث</button>
                        <?php if ($search || $filter_gov || $filter_sector): ?>
                        <a href="customers.php" class="btn btn-outline-light btn-sm">إلغاء</a>
                        <?php endif; ?>
                    </form>
                </div>
                <div class="card-body p-0 overflow-auto" style="max-height: 55vh;">
                    <table class="table table-hover mb-0 hosp-table-cust">
                        <thead>
                            <tr>
                                <th>#</th><th>الاسم</th><?php if ($has_resp): ?><th>المسؤول</th><?php endif; ?><th>المحافظة</th><th>الهاتف</th><th>القطاع</th><?php if (canEdit() || canDelete()): ?><th>إجراء</th><?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($hospitals_list && $hospitals_list->num_rows > 0): while ($h = $hospitals_list->fetch_assoc()): ?>
                        <tr class="align-middle" data-id="<?= $h['id'] ?>" data-name="<?= htmlspecialchars($h['name']) ?>" data-phone="<?= htmlspecialchars($h['phone']) ?>" data-sector="<?= htmlspecialchars($h['sector'] ?? '') ?>" data-gov="<?= $h['governorate_id'] ?? '' ?>" data-responsible="<?= htmlspecialchars($h['responsible_person'] ?? '') ?>">
                            <td><?= $h['id'] ?></td>
                            <td class="fw-500"><?= htmlspecialchars($h['name']) ?></td>
                            <?php if ($has_resp): ?><td><?= htmlspecialchars($h['responsible_person'] ?? '-') ?></td><?php endif; ?>
                            <td><span class="badge bg-light text-dark"><?= htmlspecialchars($h['gov_name'] ?? '-') ?></span></td>
                            <td dir="ltr" class="text-end"><?= htmlspecialchars($h['phone'] ?? '-') ?></td>
                            <td>
                                <?php $sc = $h['sector'] ?? ''; $sectorClass = ($sc === 'اهلي' || $sc === 'اهلی') ? 'bg-success' : ($sc === 'حكومي' ? 'bg-warning text-dark' : ($sc === 'مركز جراحي' ? 'bg-info' : 'bg-secondary')); ?>
                                <span class="badge <?= $sectorClass ?>"><?= htmlspecialchars($sc ?: '-') ?></span>
                            </td>
                            <?php if (canEdit() || canDelete()): ?><td>
                                <?php if (canEdit()): ?><button type="button" class="btn btn-sm btn-outline-primary btn-edit-hospital" data-bs-toggle="modal" data-bs-target="#editModal" title="تعديل"><i class="bi bi-pencil"></i></button><?php endif; ?>
                                <?php if (canDelete()): ?><button type="button" class="btn btn-sm btn-outline-danger btn-delete-hospital" data-id="<?= $h['id'] ?>" data-name="<?= htmlspecialchars($h['name']) ?>" title="حذف"><i class="bi bi-trash"></i></button><?php endif; ?>
                            </td><?php endif; ?>
                        </tr>
                        <?php endwhile; else: ?>
                        <tr>
                            <td colspan="<?= ($has_resp ? 6 : 5) + (canEdit() || canDelete() ? 1 : 0) ?>" class="text-center text-muted py-5">
                                <i class="bi bi-hospital fs-1 d-block mb-2 opacity-50"></i>
                                <?= ($search || $filter_gov || $filter_sector) ? 'لا توجد نتائج مطابقة للبحث' : 'لا توجد مستشفيات مسجلة' ?>
                                <p class="small mt-2 mb-0"><a href="hospitals.php">أضف مستشفى من هنا</a></p>
                            </td>
                        </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- نافذة التعديل -->
    <?php if (canEdit()): ?>
    <div class="modal fade" id="editModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header"><h5 class="modal-title">تعديل المستشفى</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <input type="hidden" id="edit_id">
                    <div class="mb-2"><label class="form-label">الاسم</label><input type="text" id="edit_name" class="form-control" required></div>
                    <?php if ($has_resp): ?><div class="mb-2"><label class="form-label">المسؤول</label><input type="text" id="edit_responsible" class="form-control"></div><?php endif; ?>
                    <div class="mb-2"><label class="form-label">المحافظة</label><select id="edit_governorate" class="form-select"><?php foreach ($governorates_list as $g): ?><option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['name_ar']) ?></option><?php endforeach; ?></select></div>
                    <div class="mb-2"><label class="form-label">الهاتف</label><input type="tel" id="edit_phone" class="form-control" pattern="07[0-9]{9}" maxlength="11" required></div>
                    <div class="mb-2"><label class="form-label">القطاع</label><select id="edit_sector" class="form-select"><?php foreach ($sectors_for_hospitals as $sec): ?><option value="<?= htmlspecialchars($sec) ?>"><?= htmlspecialchars($sec) ?></option><?php endforeach; ?></select></div>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button><button type="button" class="btn btn-primary" id="saveEdit">حفظ</button></div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    var editModal = document.getElementById('editModal');
    if (editModal) {
        editModal.addEventListener('show.bs.modal', function(e) {
            var btn = e.relatedTarget;
            var row = btn ? btn.closest('tr') : null;
            if (row) {
                document.getElementById('edit_id').value = row.dataset.id || '';
                document.getElementById('edit_name').value = row.dataset.name || '';
                document.getElementById('edit_phone').value = row.dataset.phone || '';
                document.getElementById('edit_sector').value = row.dataset.sector || '';
                document.getElementById('edit_governorate').value = row.dataset.gov || '';
                var ep = document.getElementById('edit_responsible');
                if (ep) ep.value = row.dataset.responsible || '';
            }
        });
    }
    document.getElementById('saveEdit')?.addEventListener('click', function() {
        var fd = new FormData();
        fd.append('action', 'update');
        fd.append('id', document.getElementById('edit_id').value);
        fd.append('name', document.getElementById('edit_name').value);
        fd.append('phone', document.getElementById('edit_phone').value);
        fd.append('sector', document.getElementById('edit_sector').value);
        fd.append('governorate_id', document.getElementById('edit_governorate').value);
        var ep = document.getElementById('edit_responsible');
        if (ep) fd.append('responsible_person', ep.value);
        if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
        fetch('api/hospitals.php', { method: 'POST', body: fd }).then(function(r) { return r.json(); }).then(function(d) {
            if (d.success) location.reload();
            else alert(d.message || 'فشل التحديث');
        });
    });
    document.querySelectorAll('.btn-delete-hospital').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var name = this.dataset.name || 'المستشفى';
            if (!confirm('حذف ' + name + '؟')) return;
            var url = 'api/hospitals.php?action=delete&id=' + this.dataset.id;
            if (typeof window.csrfToken !== 'undefined') url += '&csrf_token=' + window.csrfToken;
            fetch(url).then(function(r) { return r.json(); }).then(function(d) {
                if (d.success) location.reload();
                else alert(d.message || 'فشل الحذف');
            }).catch(function() { alert('حدث خطأ'); });
        });
    });
    </script>
    <?php include 'includes/footer.php'; ?>
</body>
</html>
