<?php
// تشخيص مؤقت - احذف هذا القسم بعد حل المشكلة
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$errLogFile = @is_writable(__DIR__) ? __DIR__ . '/last_error.txt' : (sys_get_temp_dir() . '/hospitals_last_error.txt');
register_shutdown_function(function () use ($errLogFile) {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        $msg = "فشل التحميل (HTTP 500)\n\nالنوع: " . $err['type'] . "\nالرسالة: " . $err['message'] . "\nالملف: " . $err['file'] . ":" . $err['line'];
        @file_put_contents($errLogFile, $msg);
        if (headers_sent() === false) header('Content-Type: text/html; charset=utf-8');
        echo '<pre style="background:#fee;padding:15px;border:2px solid red;direction:ltr;">';
        echo htmlspecialchars($msg);
        echo '</pre><p>تم حفظ الخطأ في: ' . htmlspecialchars($errLogFile) . '</p>';
    }
});

require_once __DIR__ . '/auth.php';
requireLogin();

$data_table = 'hospitals';
$entity = 'المستشفيات';
$entity_single = 'المستشفى';
$page_action = 'إدخال المستشفيات';
$api_url = 'api/hospitals.php';

$success = '';
$error = '';
$has_responsible = (($chk = @$conn->query("SHOW COLUMNS FROM hospitals LIKE 'responsible_person'")) && $chk->num_rows > 0);

if (isset($_GET['imported'])) {
    $imp = (int)$_GET['imported'];
    $skip = (int)($_GET['skipped'] ?? 0);
    $success = "تم استيراد $imp مستشفى بنجاح" . ($skip > 0 ? " وتخطي $skip (موجود مسبقاً)" : "");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['import_file']['name']) && isset($_POST['action']) && $_POST['action'] === 'import') {
    if (function_exists('require_csrf')) require_csrf();
    if (!canEdit()) { header('Location: hospitals.php'); exit; }
    $ext = strtolower(pathinfo($_FILES['import_file']['name'], PATHINFO_EXTENSION));
    $allowed = ['xlsx', 'xls', 'csv'];
    if (!in_array($ext, $allowed)) {
        $error = 'صيغة الملف غير مدعومة. استخدم xlsx أو xls أو csv';
    } elseif ($_FILES['import_file']['error'] !== UPLOAD_ERR_OK) {
        $error = 'فشل رفع الملف';
    } else {
        $tmp = $_FILES['import_file']['tmp_name'];
        $govMap = [];
        $r = @$conn->query("SELECT id, name_ar FROM governorates");
        if ($r) { while ($row = $r->fetch_assoc()) $govMap[trim($row['name_ar'])] = $row['id']; }
        $sectorNames = [];
        $r = @$conn->query("SELECT name FROM sectors WHERE for_hospitals=1");
        if (!$r) $r = @$conn->query("SELECT name FROM sectors");
        if ($r) while ($row = $r->fetch_assoc()) $sectorNames[trim($row['name'])] = 1;
        $existing = [];
        $r = @$conn->query("SELECT name, governorate_id FROM $data_table");
        if ($r) { while ($row = $r->fetch_assoc()) $existing[trim($row['name']).'|'.(int)$row['governorate_id']] = 1; }
        $imported = 0;
        $skipped = 0;
        $processRow = function($name, $govName, $phone, $sector, $responsible = '') use ($conn, $govMap, &$sectorNames, &$existing, &$imported, &$skipped, $data_table, $has_responsible) {
            $name = trim((string)$name);
            $govName = trim((string)$govName);
            $phone = trim((string)$phone);
            $sector = trim((string)$sector);
            $responsible = trim((string)$responsible);
            if (empty($name) || empty($phone) || empty($sector)) return;
            $govId = $govMap[$govName] ?? null;
            if (!$govId) { $skipped++; return; }
            if (!isset($sectorNames[$sector])) {
                $st = $conn->prepare("INSERT IGNORE INTO sectors (name, for_hospitals, for_clinics) VALUES (?, 1, 0)");
                $st->bind_param("s", $sector);
                $st->execute();
                $sectorNames[$sector] = 1;
            }
            $key = $name . '|' . $govId;
            if (isset($existing[$key])) { $skipped++; return; }
            if (!preg_match('/^07\d{9}$/', $phone)) $phone = '07000000000';
            if ($has_responsible) {
                $stmt = $conn->prepare("INSERT INTO $data_table (name, responsible_person, governorate_id, phone, sector) VALUES (?, ?, ?, ?, ?)");
                $stmt->bind_param("ssiss", $name, $responsible, $govId, $phone, $sector);
            } else {
                $stmt = $conn->prepare("INSERT INTO $data_table (name, governorate_id, phone, sector) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("siss", $name, $govId, $phone, $sector);
            }
            if ($stmt->execute()) {
                $imported++;
                $existing[$key] = 1;
                if (function_exists('logActivity')) logActivity('add', $data_table, $conn->insert_id, $name . ' (استيراد)');
            } else $skipped++;
        };
        if ($ext === 'csv') {
            $handle = fopen($tmp, 'r');
            if ($handle) {
                $bom = fread($handle, 3);
                if ($bom !== chr(0xEF).chr(0xBB).chr(0xBF)) rewind($handle);
                $header = fgetcsv($handle);
                $nameCol = 0; $respCol = 1; $govCol = 2; $phoneCol = 3; $sectorCol = 4;
                if ($header && count($header) >= 3) {
                    foreach ($header as $i => $h) {
                        $h = (string)$h;
                        if (stripos($h, 'اسم') !== false && stripos($h, 'مسؤول') === false) $nameCol = $i;
                        elseif (stripos($h, 'مسؤول') !== false) $respCol = $i;
                        elseif (stripos($h, 'محافظ') !== false) $govCol = $i;
                        elseif (stripos($h, 'هاتف') !== false) $phoneCol = $i;
                        elseif (stripos($h, 'قطاع') !== false) $sectorCol = $i;
                    }
                }
                while (($row = fgetcsv($handle)) !== false) {
                    $processRow($row[$nameCol] ?? $row[0] ?? '', $row[$govCol] ?? $row[2] ?? '', $row[$phoneCol] ?? $row[3] ?? '', $row[$sectorCol] ?? $row[4] ?? '', $row[$respCol] ?? $row[1] ?? '');
                }
                fclose($handle);
            }
        } else {
            if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
                $error = 'مكتبة Excel غير متوفرة. استخدم ملف CSV للاستيراد.';
            } else {
                require_once __DIR__ . '/vendor/autoload.php';
                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($ext === 'xlsx' ? 'Xlsx' : 'Xls');
                $spreadsheet = $reader->load($tmp);
                $sheet = $spreadsheet->getActiveSheet();
                $rows = $sheet->toArray();
                $nameCol = 0; $respCol = 1; $govCol = 2; $phoneCol = 3; $sectorCol = 4;
                if (!empty($rows[0]) && count($rows[0]) >= 3) {
                    foreach ($rows[0] as $i => $h) {
                        $h = is_string($h) ? $h : '';
                        if (stripos($h, 'اسم') !== false && stripos($h, 'مسؤول') === false) $nameCol = $i;
                        elseif (stripos($h, 'مسؤول') !== false) $respCol = $i;
                        elseif (stripos($h, 'محافظ') !== false) $govCol = $i;
                        elseif (stripos($h, 'هاتف') !== false) $phoneCol = $i;
                        elseif (stripos($h, 'قطاع') !== false) $sectorCol = $i;
                    }
                }
                for ($i = 1; $i < count($rows); $i++) {
                    $row = $rows[$i] ?? [];
                    $processRow($row[$nameCol] ?? $row[0] ?? '', $row[$govCol] ?? $row[2] ?? '', $row[$phoneCol] ?? $row[3] ?? '', $row[$sectorCol] ?? $row[4] ?? '', $row[$respCol] ?? $row[1] ?? '');
                }
            }
        }
        if (empty($error)) {
            header('Location: hospitals.php?imported=' . $imported . '&skipped=' . $skipped);
            exit;
        }
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (function_exists('require_csrf')) require_csrf();
    if (!canEdit()) { header('Location: hospitals.php'); exit; }
    $name = trim($_POST['name'] ?? '');
    $responsible_person = trim($_POST['responsible_person'] ?? '');
    $governorate_id = (int)($_POST['governorate_id'] ?? 0);
    $phone = trim($_POST['phone'] ?? '');
    $sector = $_POST['sector'] ?? '';
    
    if (empty($name) || empty($governorate_id) || empty($phone) || empty($sector)) {
        $error = 'يرجى تعبئة جميع الحقول';
    } elseif (!preg_match('/^07\d{9}$/', $phone)) {
        $error = 'رقم الهاتف يجب أن يبدأ بـ 07 ويتكون من 11 رقم';
    } else {
        if ($has_responsible) {
            $stmt = $conn->prepare("INSERT INTO $data_table (name, responsible_person, governorate_id, phone, sector) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("ssiss", $name, $responsible_person, $governorate_id, $phone, $sector);
        } else {
            $stmt = $conn->prepare("INSERT INTO $data_table (name, governorate_id, phone, sector) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("siss", $name, $governorate_id, $phone, $sector);
        }
        if ($stmt->execute()) {
            if (function_exists('logActivity')) logActivity('add', $data_table, $conn->insert_id, $name);
            $success = 'تم إضافة المستشفى بنجاح';
            $_POST = [];
        } else {
            $error = 'حدث خطأ أثناء الحفظ';
        }
    }
}

$govResult = @$conn->query("SELECT * FROM governorates ORDER BY name_ar");
$governorates_list = [];
if ($govResult) { while ($r = $govResult->fetch_assoc()) $governorates_list[] = $r; }
$has_responsible = (($chk = @$conn->query("SHOW COLUMNS FROM hospitals LIKE 'responsible_person'")) && $chk->num_rows > 0);
$sectors = @$conn->query("SELECT s.*, 
    (SELECT COUNT(*) FROM hospitals WHERE sector = s.name) as hospital_count
    FROM sectors s ORDER BY s.name");
if (!$sectors) {
    $sectors = @$conn->query("SELECT s.*, 0 as hospital_count FROM sectors s ORDER BY s.name");
}
$sectors_list = [];
$sectors_for_hospitals = [];
if ($sectors) {
    while ($s = $sectors->fetch_assoc()) {
        $s['use_count'] = (int)($s['hospital_count'] ?? 0);
        $sectors_list[] = $s;
        $for_h = isset($s['for_hospitals']) ? (int)$s['for_hospitals'] : 1;
        if ($for_h) $sectors_for_hospitals[] = $s;
    }
}
$sectors_for_page = $sectors_for_hospitals;

$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, array_column($sectors_for_page, 'name'))) {
    $where_parts[] = "h.sector = ?";
    $params[] = $filter_sector;
    $types .= 's';
}
$where = $where_parts ? ' WHERE ' . implode(' AND ', $where_parts) : '';
$orderBy = ' ORDER BY h.id DESC';
if ($params) {
    $stmt = $conn->prepare("SELECT h.*, g.name_ar as gov_name FROM $data_table h JOIN governorates g ON h.governorate_id = g.id $where $orderBy");
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $hospitals = $stmt->get_result();
} else {
    $hospitals = $conn->query("SELECT h.*, g.name_ar as gov_name FROM $data_table h JOIN governorates g ON h.governorate_id = g.id $where $orderBy");
}

$stats_total = 0;
$st = @$conn->query("SELECT COUNT(*) c FROM $data_table");
if ($st && $row = $st->fetch_assoc()) $stats_total = (int)($row['c'] ?? 0);
$stats_by_sector = @$conn->query("SELECT sector, COUNT(*) c FROM $data_table GROUP BY sector");
if (!$stats_by_sector) $stats_by_sector = null;
?>
<!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><?= $page_action ?> - نظام صيانة</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-tabs .nav-link { border-radius: 10px; font-weight: 500; padding: 0.5rem 1rem; }
        .hosp-tabs .nav-link.active { background: #0f172a; color: #fff !important; }
        /* بطاقة القائمة */
        .hosp-list-card { border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 2px 8px rgba(0,0,0,0.06); overflow: hidden; }
        .hosp-list-card .card-header { background: #fff !important; border-bottom: 1px solid #e2e8f0; padding: 1rem 1.25rem; }
        .hosp-filter-form .form-control, .hosp-filter-form .form-select { border-radius: 10px; border-color: #e2e8f0; }
        .hosp-filter-form .form-control:focus, .hosp-filter-form .form-select:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59,130,246,0.15); }
        .hosp-filter-form .btn-primary { border-radius: 10px; padding: 0.35rem 1rem; }
        /* جدول المستشفيات */
        .hosp-table thead th { background: linear-gradient(135deg, #1e3a5f 0%, #0f172a 100%) !important; color: #fff !important; font-weight: 600; border: none; padding: 0.9rem 1rem; font-size: 0.9rem; }
        .hosp-table thead th a { color: #fff !important; opacity: 0.95; }
        .hosp-table thead th a:hover { color: #fff !important; opacity: 1; text-decoration: underline; }
        .hosp-table tbody td { padding: 0.85rem 1rem; vertical-align: middle; }
        .hosp-table tbody tr:hover { background-color: #f8fafc; }
        .hosp-table .badge { font-weight: 500; padding: 0.35em 0.65em; border-radius: 8px; font-size: 0.8rem; }
        .hosp-table .badge.bg-light { background-color: #f1f5f9 !important; color: #475569; border: 1px solid #e2e8f0; }
        .hosp-table .btn-sm { width: 32px; height: 32px; padding: 0; display: inline-flex; align-items: center; justify-content: center; border-radius: 8px; margin: 0 2px; transition: all 0.2s; }
        .hosp-table .btn-sm:hover { transform: scale(1.05); }
    </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"><a href="hospitals.php">المستشفيات</a></li>
                    <li class="breadcrumb-item active"><?= $page_action ?></li>
                </ol>
            </nav>

            <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><?= $page_action ?></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; ?>
                    <?php if (canEdit()): ?><button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#importModal"><i class="bi bi-upload me-1"></i> استيراد Excel</button><?php endif; ?>
                </div>
            </div>

            <!-- بطاقات الإحصائيات -->
            <?php $statStyles = [
                ['#dbeafe','#bfdbfe','#93c5fd'],
                ['#dcfce7','#bbf7d0','#86efac'],
                ['#fef3c7','#fde68a','#fcd34d'],
                ['#fce7f3','#fbcfe8','#f9a8d4'],
            ]; ?>
            <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; $stats_by_sector->data_seek(0); 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="row g-4">
                <?php if (canEdit()): ?>
                <div class="col-lg-5">
                    <div class="card" 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 text-white" style="background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); border: none; padding: 1rem 1.25rem;">
                            <h5 class="mb-0"><i class="bi bi-plus-circle me-2"></i>إضافة <?= $entity_single ?> جديد</h5>
                        </div>
                        <div class="card-body">
                            <?php if ($success): ?>
                            <div class="alert alert-success d-flex align-items-center">
                                <i class="bi bi-check-circle me-2"></i><?= $success ?>
                            </div>
                            <?php endif; ?>
                            <?php if ($error): ?>
                            <div class="alert alert-danger d-flex align-items-center">
                                <i class="bi bi-exclamation-circle me-2"></i><?= $error ?>
                            </div>
                            <?php endif; ?>
                            <form method="POST" action="?">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <div class="mb-3">
                                    <label class="form-label fw-600"><i class="bi bi-hospital me-1 text-muted"></i>اسم <?= $entity_single ?></label>
                                    <input type="text" name="name" class="form-control" required 
                                        placeholder="مثال: مستشفى اليرموك" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-600"><i class="bi bi-person me-1 text-muted"></i>اسم الشخص المسؤول</label>
                                    <input type="text" name="responsible_person" class="form-control" 
                                        placeholder="اسم المسؤول عن المستشفى" value="<?= htmlspecialchars($_POST['responsible_person'] ?? '') ?>">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-600"><i class="bi bi-geo-alt me-1 text-muted"></i>المحافظة</label>
                                    <select name="governorate_id" class="form-select" required>
                                        <option value="">اختر المحافظة</option>
                                        <?php foreach ($governorates_list as $g): ?>
                                        <option value="<?= $g['id'] ?>" <?= (($_POST['governorate_id'] ?? '') == $g['id']) ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($g['name_ar']) ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-600"><i class="bi bi-telephone me-1 text-muted"></i>رقم الهاتف</label>
                                    <input type="tel" name="phone" class="form-control" pattern="07[0-9]{9}" 
                                        placeholder="07xxxxxxxxx" maxlength="11" required
                                        value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>">
                                    <small class="text-muted">يبدأ بـ 07 ويتكون من 11 رقم</small>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-600"><i class="bi bi-building me-1 text-muted"></i>القطاع</label>
                                    <select name="sector" class="form-select" required>
                                        <option value="">-- اختر القطاع --</option>
                                        <?php foreach ($sectors_for_page as $sec): ?>
                                        <option value="<?= htmlspecialchars($sec['name']) ?>" <?= (($_POST['sector'] ?? '') == $sec['name']) ? 'selected' : '' ?>><?= htmlspecialchars($sec['name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <button type="submit" class="btn btn-primary w-100"><i class="bi bi-plus-lg me-1"></i> إضافة</button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                <div class="col-lg-<?= canEdit() ? 7 : 12 ?>">
                    <div class="card hosp-list-card">
                        <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-3">
                            <h5 class="mb-0 fw-600"><i class="bi bi-list-ul me-2"></i>قائمة <?= $entity ?></h5>
                            <form method="GET" class="hosp-filter-form 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: 180px;">
                                <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_page as $sec): ?>
                                    <option value="<?= htmlspecialchars($sec['name']) ?>" <?= $filter_sector === $sec['name'] ? 'selected' : '' ?>><?= htmlspecialchars($sec['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="submit" class="btn btn-primary btn-sm px-3"><i class="bi bi-search me-1"></i>بحث</button>
                                <?php if ($search || $filter_gov || $filter_sector): ?>
                                <a href="hospitals.php" class="btn btn-outline-secondary btn-sm px-3">إلغاء</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" id="hospitalsTable">
                                <thead>
                                    <tr><th>#</th><th>الاسم</th><th>المسؤول</th><th>المحافظة</th><th>الهاتف</th><th>القطاع</th><?php if (canEdit() || canDelete()): ?><th>إجراء</th><?php endif; ?></tr>
                                </thead>
                                <tbody>
                                <?php if ($hospitals): while ($h = $hospitals->fetch_assoc()): ?>
                                <tr class="align-middle" data-name="<?= htmlspecialchars($h['name']) ?>" data-gov="<?= htmlspecialchars($h['gov_name']) ?>" data-sector="<?= htmlspecialchars($h['sector']) ?>" data-responsible="<?= htmlspecialchars($h['responsible_person'] ?? '') ?>">
                                    <td><?= $h['id'] ?></td>
                                    <td class="fw-500"><?= htmlspecialchars($h['name']) ?></td>
                                    <td><?= htmlspecialchars($h['responsible_person'] ?? '-') ?></td>
                                    <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
                                        $sectorClass = $h['sector'] === 'اهلي' ? 'bg-success' : ($h['sector'] === 'حكومي' ? 'bg-warning text-dark' : ($h['sector'] === 'مركز جراحي' ? 'bg-info' : 'bg-secondary'));
                                        ?>
                                        <span class="badge <?= $sectorClass ?>"><?= htmlspecialchars($h['sector']) ?></span>
                                    </td>
                                    <?php if (canEdit() || canDelete()): ?><td>
                                        <?php if (canEdit()): ?><button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editModal" 
                                            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'] ?? '') ?>" 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" data-id="<?= $h['id'] ?>" title="حذف"><i class="bi bi-trash"></i></button><?php endif; ?>
                                    </td><?php endif; ?>
                                </tr>
                                <?php endwhile; endif; ?>
                                <?php if (!$hospitals || $hospitals->num_rows === 0): ?>
                                <tr>
                                    <td colspan="<?= (canEdit() || canDelete()) ? 7 : 6 ?>" class="text-center text-muted py-5">
                                        <i class="bi bi-hospital fs-1 d-block mb-2"></i>
                                        <?= ($search || $filter_gov || $filter_sector) ? 'لا توجد نتائج مطابقة للبحث' : 'لا توجد ' . $entity . ' مسجلة' ?>
                                    </td>
                                </tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- إدارة القطاعات -->
            <?php if (canEdit() || canDelete()): ?>
            <div class="card mt-4" style="border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
                <div class="card-header bg-white d-flex justify-content-between align-items-center py-3" data-bs-toggle="collapse" data-bs-target="#sectorsSection" style="cursor:pointer">
                    <h5 class="mb-0 fw-600"><i class="bi bi-tags me-2"></i>إدارة القطاعات</h5>
                    <i class="bi bi-chevron-down"></i>
                </div>
                <div class="collapse" id="sectorsSection">
                    <div class="card-body">
                        <div class="row g-4">
                            <?php if (canEdit()): ?>
                            <div class="col-md-6">
                                <label class="form-label fw-600">إضافة قطاع جديد</label>
                                <div class="input-group mb-2">
                                    <input type="text" id="newSectorName" class="form-control" placeholder="اسم القطاع">
                                    <button type="button" class="btn btn-primary" id="addSectorBtn"><i class="bi bi-plus-lg"></i></button>
                                </div>
                                <div class="d-flex gap-3 small">
                                    <label class="form-check"><input type="checkbox" class="form-check-input" id="newSectorHospitals" checked> يظهر في المستشفيات</label>
                                </div>
                            </div>
                            <?php endif; ?>
                            <div class="col-12">
                                <table class="table table-sm table-hover" id="sectorsTable">
                                    <thead class="table-light"><tr><th>#</th><th>الاسم</th><th>مستشفيات</th><?php if (canEdit() || canDelete()): ?><th>إجراء</th><?php endif; ?></tr></thead>
                                    <tbody id="sectorsTableBody">
                                        <?php foreach ($sectors_list as $sec): ?>
                                        <?php $fh = isset($sec['for_hospitals']) ? (int)$sec['for_hospitals'] : 1; ?>
                                        <tr data-id="<?= $sec['id'] ?>" data-name="<?= htmlspecialchars($sec['name']) ?>" data-use="<?= $sec['use_count'] ?>" data-for-hospitals="<?= $fh ?>">
                                            <td><?= $sec['id'] ?></td>
                                            <td class="fw-500"><?= htmlspecialchars($sec['name']) ?><br><small class="text-muted"><?= $fh ? 'مستشفى' : '—' ?></small></td>
                                            <td><span class="badge bg-primary bg-opacity-25 text-primary"><?= (int)($sec['hospital_count'] ?? 0) ?></span></td>
                                            <?php if (canEdit() || canDelete()): ?><td>
                                                <?php if (canEdit()): ?><button type="button" class="btn btn-sm btn-outline-primary btn-edit-sector" data-id="<?= $sec['id'] ?>" data-name="<?= htmlspecialchars($sec['name']) ?>" data-for-hospitals="<?= $fh ?>" title="تعديل"><i class="bi bi-pencil"></i></button><?php endif; ?>
                                                <button type="button" class="btn btn-sm btn-outline-danger btn-del-sector <?= $sec['use_count'] > 0 ? 'disabled' : '' ?>" data-id="<?= $sec['id'] ?>" title="<?= $sec['use_count'] > 0 ? 'مستخدم ولا يمكن حذفه' : 'حذف' ?>"><i class="bi bi-trash"></i></button>
                                            </td><?php endif; ?>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- نافذة تعديل القطاع -->
    <div class="modal fade" id="editSectorModal" 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_sector_id">
                    <div class="mb-2"><label class="form-label">الاسم</label><input type="text" id="edit_sector_name" class="form-control" required></div>
                    <div class="mb-0">
                        <label class="form-label">يظهر في</label>
                        <div class="d-flex gap-3">
                            <label class="form-check"><input type="checkbox" class="form-check-input" id="edit_sector_hospitals"> المستشفيات</label>
                        </div>
                    </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="saveSectorEdit">حفظ</button></div>
            </div>
        </div>
    </div>
    
    <!-- نافذة التعديل -->
    <div class="modal fade" id="editModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header"><h5 class="modal-title">تعديل <?= $entity_single ?></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>
                    <div class="mb-2"><label class="form-label">اسم الشخص المسؤول</label><input type="text" id="edit_responsible" class="form-control" placeholder="اسم المسؤول عن المستشفى"></div>
                    <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_page as $sec): ?><option value="<?= htmlspecialchars($sec['name']) ?>"><?= htmlspecialchars($sec['name']) ?></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 if (canEdit()): ?>
    <div class="modal fade" id="importModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-upload me-2"></i>استيراد <?= $entity ?> من Excel</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" enctype="multipart/form-data">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="import">
                    <input type="hidden" name="import_type" value="hospital">
                    <div class="modal-body">
                        <p class="text-muted small">الصيغ المدعومة: xlsx, xls, csv. الأعمدة المتوقعة: الاسم، المحافظة، الهاتف، القطاع. يجب أن تتطابق أسماء المحافظات مع النظام (بغداد، البصرة، ...). القطاعات غير الموجودة تُنشأ تلقائياً. رقم الهاتف يجب 07xxxxxxxxx.</p>
                        <div class="mb-3">
                            <label class="form-label">اختر الملف</label>
                            <input type="file" name="import_file" class="form-control" accept=".xlsx,.xls,.csv" required>
                        </div>
                        <p class="small"><a href="export.php?type=hospitals" class="text-primary">حمّل ملف نموذج</a> من التصدير ثم أضف البيانات الجديدة فيه.</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="submit" class="btn btn-success"><i class="bi bi-upload me-1"></i>استيراد</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    document.getElementById('editModal').addEventListener('show.bs.modal', function(e) {
        const btn = e.relatedTarget;
        if (btn?.dataset?.id) {
            document.getElementById('edit_id').value = btn.dataset.id;
            document.getElementById('edit_name').value = btn.dataset.name;
            document.getElementById('edit_phone').value = btn.dataset.phone;
            document.getElementById('edit_sector').value = btn.dataset.sector;
            document.getElementById('edit_governorate').value = btn.dataset.gov;
            const ep = document.getElementById('edit_responsible');
            if (ep) ep.value = btn.dataset.responsible || '';
        }
    });
    document.getElementById('saveEdit').addEventListener('click', function() {
        const 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);
        const ep = document.getElementById('edit_responsible');
        if (ep) fd.append('responsible_person', ep.value);
        if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
        fetch('<?= $api_url ?>', { method: 'POST', body: fd }).then(r => r.json()).then(d => { if (d.success) location.reload(); else alert(d.message || 'فشل'); });
    });
    document.querySelectorAll('.btn-delete').forEach(btn => {
        btn.addEventListener('click', function() {
            if (confirm('حذف <?= $entity_single ?> هذه؟')) {
                const u = '<?= $api_url ?>?action=delete&id=' + this.dataset.id + (window.csrfToken ? '&csrf_token=' + window.csrfToken : '');
                fetch(u).then(r => r.json()).then(d => { if (d.success) location.reload(); else alert(d.message || 'فشل'); });
            }
        });
    });

    // إدارة القطاعات
    document.querySelectorAll('.btn-edit-sector').forEach(btn => {
        btn.addEventListener('click', function() {
            document.getElementById('edit_sector_id').value = this.dataset.id;
            document.getElementById('edit_sector_name').value = this.dataset.name;
            document.getElementById('edit_sector_hospitals').checked = this.dataset.forHospitals === '1';
            new bootstrap.Modal(document.getElementById('editSectorModal')).show();
        });
    });
    document.getElementById('saveSectorEdit')?.addEventListener('click', function() {
        const id = document.getElementById('edit_sector_id').value;
        const name = document.getElementById('edit_sector_name').value.trim();
        if (!name) { alert('أدخل اسم القطاع'); return; }
        const fd = new FormData();
        fd.append('action', 'update');
        fd.append('id', id);
        fd.append('name', name);
        fd.append('for_hospitals', document.getElementById('edit_sector_hospitals').checked ? '1' : '0');
        fd.append('for_clinics', '0');
        if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
        fetch('api/sectors.php', { method: 'POST', body: fd }).then(r => r.json()).then(d => {
            if (d.success) location.reload();
            else alert(d.message || 'فشل');
        });
    });
    document.getElementById('addSectorBtn')?.addEventListener('click', function() {
        const name = document.getElementById('newSectorName').value.trim();
        if (!name) { alert('أدخل اسم القطاع'); return; }
        const fd = new FormData();
        fd.append('action', 'create');
        fd.append('name', name);
        fd.append('for_hospitals', document.getElementById('newSectorHospitals').checked ? '1' : '0');
        fd.append('for_clinics', '0');
        if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
        fetch('api/sectors.php', { method: 'POST', body: fd }).then(r => r.json()).then(d => {
            if (d.success) location.reload();
            else alert(d.message || 'فشل');
        });
    });
    document.getElementById('newSectorName')?.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') document.getElementById('addSectorBtn')?.click();
    });
    document.querySelectorAll('.btn-del-sector').forEach(btn => {
        if (btn.disabled) return;
        btn.addEventListener('click', function() {
            if (confirm('حذف هذا القطاع؟')) {
                const fd = new FormData();
                fd.append('action', 'delete');
                fd.append('id', this.dataset.id);
                if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
                fetch('api/sectors.php', { method: 'POST', body: fd }).then(r => r.json()).then(d => {
                    if (d.success) location.reload();
                    else alert(d.message || 'فشل');
                });
            }
        });
    });
    </script>
    <?php include 'includes/footer.php'; ?>
</body>
</html>
