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

require_once '../config/database.php';
require_once '../includes/app_helpers.php';

$db = (new Database())->getConnection();
ensureAddressAndCallQueueTables($db);

$success_message = '';
$error_message = '';

if (!function_exists('h')) {
    function h($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('cleanText')) {
    function cleanText($value) {
        return trim((string)$value);
    }
}

$states = [
    'Alabama',
    'Arkansas',
    'Florida',
    'Georgia',
    'Illinois',
    'Indiana',
    'Kentucky',
    'Louisiana',
    'Mississippi',
    'Missouri',
    'North Carolina',
    'Oklahoma',
    'South Carolina',
    'Tennessee',
    'Texas',
    'Virginia'
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $action = $_POST['action'] ?? '';

        if ($action === 'add_area') {
            $zip = preg_replace('/\D+/', '', $_POST['zip_code'] ?? '');
            $city = ucwords(strtolower(cleanText($_POST['city'] ?? '')));
            $state = cleanText($_POST['state'] ?? '');
            $region = cleanText($_POST['region'] ?? '');

            if (!preg_match('/^\d{5}$/', $zip)) {
                throw new Exception('Please enter a valid 5-digit ZIP code.');
            }

            if ($city === '' || $state === '' || $region === '') {
                throw new Exception('Region, city, state, and ZIP code are required.');
            }

            $stmt = $db->prepare("
                INSERT INTO service_areas 
                    (zip_code, city, state, region, is_active, created_at, updated_at)
                VALUES 
                    (:zip, :city, :state, :region, 1, NOW(), NOW())
                ON DUPLICATE KEY UPDATE
                    city = VALUES(city),
                    state = VALUES(state),
                    region = VALUES(region),
                    is_active = 1,
                    updated_at = NOW()
            ");

            $stmt->execute([
                ':zip' => $zip,
                ':city' => $city,
                ':state' => $state,
                ':region' => $region
            ]);

            ensureCoverageCityRecord($db, $city, $state, $region);

            $success_message = 'Service area added / updated successfully.';
        }

        if ($action === 'edit_area') {
            $id = (int)($_POST['area_id'] ?? 0);
            $zip = preg_replace('/\D+/', '', $_POST['zip_code'] ?? '');
            $city = ucwords(strtolower(cleanText($_POST['city'] ?? '')));
            $state = cleanText($_POST['state'] ?? '');
            $region = cleanText($_POST['region'] ?? '');
            $active = isset($_POST['is_active']) ? 1 : 0;

            if ($id <= 0) {
                throw new Exception('Invalid service area.');
            }

            if (!preg_match('/^\d{5}$/', $zip)) {
                throw new Exception('Please enter a valid 5-digit ZIP code.');
            }

            if ($city === '' || $state === '' || $region === '') {
                throw new Exception('Region, city, state, and ZIP code are required.');
            }

            $stmt = $db->prepare("
                UPDATE service_areas
                SET 
                    zip_code = :zip, 
                    city = :city, 
                    state = :state, 
                    region = :region, 
                    is_active = :active, 
                    updated_at = NOW()
                WHERE id = :id
            ");

            $stmt->execute([
                ':zip' => $zip,
                ':city' => $city,
                ':state' => $state,
                ':region' => $region,
                ':active' => $active,
                ':id' => $id
            ]);

            ensureCoverageCityRecord($db, $city, $state, $region);

            $success_message = 'Service area updated successfully.';
        }

        if ($action === 'toggle_area') {
            $id = (int)($_POST['area_id'] ?? 0);

            if ($id <= 0) {
                throw new Exception('Invalid service area.');
            }

            $stmt = $db->prepare("
                UPDATE service_areas 
                SET 
                    is_active = IF(is_active = 1, 0, 1), 
                    updated_at = NOW() 
                WHERE id = :id
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            $success_message = 'Service area status updated.';
        }

        if ($action === 'delete_area') {
            $id = (int)($_POST['area_id'] ?? 0);

            if ($id <= 0) {
                throw new Exception('Invalid service area.');
            }

            $stmt = $db->prepare("
                DELETE FROM service_areas 
                WHERE id = :id 
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            $success_message = 'Service area deleted successfully.';
        }
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

$search = cleanText($_GET['search'] ?? '');

$where = '';
$params = [];

if ($search !== '') {
    $where = "
        WHERE 
            zip_code LIKE :search_zip 
            OR city LIKE :search_city 
            OR state LIKE :search_state 
            OR region LIKE :search_region
    ";

    $searchLike = '%' . $search . '%';
    $params = [
        ':search_zip' => $searchLike,
        ':search_city' => $searchLike,
        ':search_state' => $searchLike,
        ':search_region' => $searchLike
    ];
}

$stats = $db->query("
    SELECT 
        COUNT(*) AS total_zips,
        COUNT(DISTINCT city) AS total_cities,
        COUNT(DISTINCT state) AS total_states,
        COUNT(DISTINCT region) AS total_regions,
        SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) AS active_zips
    FROM service_areas
")->fetch(PDO::FETCH_ASSOC) ?: [];

$groupStmt = $db->prepare("
    SELECT 
        region, 
        state, 
        city,
        COUNT(*) AS zip_count,
        GROUP_CONCAT(zip_code ORDER BY zip_code SEPARATOR ', ') AS zip_codes,
        SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) AS active_count
    FROM service_areas
    $where
    GROUP BY region, state, city
    ORDER BY region, state, city
");

$groupStmt->execute($params);
$cityGroups = $groupStmt->fetchAll(PDO::FETCH_ASSOC);

$regions = [];

foreach ($cityGroups as $g) {
    $regionName = trim((string)($g['region'] ?? ''));

    if ($regionName === '') {
        $regionName = 'Unassigned Region';
    }

    if (!isset($regions[$regionName])) {
        $regions[$regionName] = [
            'cities' => [],
            'states' => [],
            'total_cities' => 0,
            'total_zips' => 0,
            'active_cities' => 0
        ];
    }

    $regions[$regionName]['cities'][] = $g;
    $regions[$regionName]['states'][$g['state']] = true;
    $regions[$regionName]['total_cities']++;
    $regions[$regionName]['total_zips'] += (int)($g['zip_count'] ?? 0);

    if ((int)($g['active_count'] ?? 0) > 0) {
        $regions[$regionName]['active_cities']++;
    }
}

$rowStmt = $db->prepare("
    SELECT * 
    FROM service_areas 
    $where 
    ORDER BY region, state, city, zip_code
");

$rowStmt->execute($params);
$allAreas = $rowStmt->fetchAll(PDO::FETCH_ASSOC);
$areas = array_slice($allAreas, 0, 20);
$totalAreaRows = count($allAreas);
$shownAreaRows = count($areas);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Service Areas - Admin</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

    <style>
        :root {
            --bg1: #080240;
            --bg2: #093349;
            --card1: #17295e;
            --card2: #102448;
            --cyan: #17bdd4;
            --blue: #1d9bf0;
            --muted: #aebbd4;
            --soft: #d7e7ff;
            --border: rgba(56, 189, 248, .28);
        }

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            min-height: 100vh;
            background: linear-gradient(135deg, var(--bg1), var(--bg2));
            color: #fff;
            font-family: Montserrat, Arial, sans-serif;
        }

        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 250px;
            min-height: 100vh;
            background: rgba(8, 2, 64, .96);
            border-right: 1px solid rgba(96, 165, 250, .18);
            z-index: 10;
        }

        .sidebar-header {
            padding: 25px 18px;
            text-align: center;
            border-bottom: 1px solid rgba(96, 165, 250, .18);
        }

        .sidebar-header i {
            color: #fff;
        }

        .sidebar-header h4 {
            font-weight: 900;
            font-size: 1.05rem;
        }

        .sidebar-header p {
            color: var(--muted);
            font-size: .8rem;
        }

        .sidebar-menu {
            padding: 18px 0;
        }

        .sidebar-menu a {
            display: block;
            padding: 13px 20px;
            color: #b9dcff;
            text-decoration: none;
            font-weight: 800;
            font-size: 14px;
            border-left: 4px solid transparent;
        }

        .sidebar-menu a:hover,
        .sidebar-menu a.active {
            background: rgba(56, 189, 248, .12);
            color: #fff;
            border-left-color: var(--cyan);
        }

        .sidebar-menu i {
            width: 21px;
            margin-right: 9px;
        }

        .main-content {
            margin-left: 250px;
            padding: 24px;
        }

        .header-card,
        .panel,
        .stat-card {
            background: linear-gradient(135deg, var(--card1), var(--card2));
            border: 1px solid var(--border);
            border-radius: 16px;
            box-shadow: 0 10px 24px rgba(0, 0, 0, .24);
            overflow: hidden;
        }

        .header-card {
            padding: 20px;
            margin-bottom: 18px;
            display: flex;
            justify-content: space-between;
            gap: 16px;
            align-items: center;
        }

        .header-card h2 {
            font-weight: 900;
            margin: 0;
        }

        .header-card p,
        .text-muted {
            color: var(--muted) !important;
        }

        .stat-card {
            padding: 18px;
        }

        .stat-card h3 {
            font-weight: 900;
            margin: 0;
        }

        .panel-head {
            padding: 14px 16px;
            background: linear-gradient(135deg, rgba(29, 155, 240, .18), rgba(23, 189, 212, .08));
            border-bottom: 1px solid rgba(56, 189, 248, .22);
            font-weight: 900;
        }

        .panel-body {
            padding: 16px;
        }

        .form-control,
        .form-select {
            background: rgba(8, 20, 48, .72) !important;
            border: 1px solid rgba(96, 165, 250, .34) !important;
            color: #fff !important;
            border-radius: 10px !important;
            min-height: 42px;
        }

        .form-control::placeholder {
            color: #aebbd4;
        }

        .form-select option {
            background: #102448;
            color: #fff;
        }

        .form-label {
            font-weight: 800;
            color: #fff;
        }

        .btn-main,
        .btn-primary {
            background: linear-gradient(135deg, var(--blue), var(--cyan)) !important;
            border: 0 !important;
            color: #fff !important;
            border-radius: 10px !important;
            font-weight: 900 !important;
        }

        .btn-soft {
            background: rgba(56, 189, 248, .12);
            border: 1px solid rgba(56, 189, 248, .36);
            color: #dff7ff;
            border-radius: 10px;
            font-weight: 900;
        }

        .btn-soft:hover {
            background: rgba(56, 189, 248, .24);
            color: #ffffff;
        }

        .btn-danger-soft {
            background: rgba(244, 63, 94, .14);
            border: 1px solid rgba(244, 63, 94, .38);
            color: #fecaca;
            border-radius: 10px;
            font-weight: 900;
        }

        .btn-danger-soft:hover {
            background: rgba(244, 63, 94, .28);
            color: #ffffff;
        }

        .table {
            color: #fff;
        }

        .table th {
            background: rgba(8, 20, 48, .62) !important;
            color: #fff !important;
            border-color: rgba(96, 165, 250, .22) !important;
            white-space: nowrap;
        }

        .table td {
            background: rgba(8, 20, 48, .18) !important;
            color: #d7e7ff !important;
            border-color: rgba(96, 165, 250, .20) !important;
            vertical-align: middle;
        }

        .zip-badge {
            display: inline-flex;
            margin: 2px;
            padding: 4px 8px;
            border-radius: 999px;
            background: rgba(56, 189, 248, .18);
            border: 1px solid rgba(56, 189, 248, .30);
            font-weight: 800;
            color: #dff7ff;
        }

        .badge {
            border-radius: 999px;
        }

        .modal-content {
            background: linear-gradient(135deg, var(--card1), var(--card2));
            border: 1px solid var(--border);
            color: #fff;
        }

        .modal-header {
            border-bottom: 1px solid rgba(96, 165, 250, .22);
        }

        .modal-footer {
            border-top: 1px solid rgba(96, 165, 250, .22);
        }

        .btn-close {
            filter: brightness(0) invert(1);
        }

        .delete-confirm-overlay {
            position: fixed;
            inset: 0;
            background: rgba(2, 6, 23, 0.74);
            z-index: 5000;
            display: none;
            align-items: center;
            justify-content: center;
            padding: 18px;
        }

        .delete-confirm-modal {
            width: min(460px, 100%);
            background: linear-gradient(135deg, #17295e, #102448);
            border: 1px solid rgba(244, 63, 94, 0.42);
            border-radius: 18px;
            color: #ffffff;
            box-shadow: 0 24px 80px rgba(0, 0, 0, 0.55);
            overflow: hidden;
            animation: popIn 0.22s ease;
        }

        @keyframes popIn {
            from {
                opacity: 0;
                transform: translateY(-10px) scale(.98);
            }

            to {
                opacity: 1;
                transform: none;
            }
        }

        .delete-confirm-header {
            padding: 16px;
            background: rgba(244, 63, 94, 0.13);
            border-bottom: 1px solid rgba(244, 63, 94, 0.28);
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .delete-confirm-icon {
            width: 42px;
            height: 42px;
            border-radius: 14px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: rgba(244, 63, 94, 0.22);
            color: #fecaca;
            border: 1px solid rgba(244, 63, 94, 0.34);
            flex-shrink: 0;
        }

        .delete-confirm-header h4 {
            margin: 0;
            color: #ffffff !important;
            font-weight: 900;
        }

        .delete-confirm-header small {
            color: #fecaca;
            font-weight: 700;
        }

        .delete-confirm-body {
            padding: 18px;
            color: #d7e7ff;
        }

        .delete-confirm-warning {
            background: rgba(250, 204, 21, 0.12);
            border: 1px solid rgba(250, 204, 21, 0.30);
            color: #fde68a;
            border-radius: 12px;
            padding: 10px 12px;
            font-weight: 700;
            margin-top: 12px;
        }

        .delete-confirm-footer {
            padding: 14px 18px;
            border-top: 1px solid rgba(96, 165, 250, 0.22);
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            flex-wrap: wrap;
        }

        .btn-cancel-delete {
            background: rgba(148, 163, 184, 0.16) !important;
            border: 1px solid rgba(148, 163, 184, 0.34) !important;
            color: #e2e8f0 !important;
            border-radius: 10px !important;
            font-weight: 900 !important;
        }

        .btn-confirm-delete {
            background: linear-gradient(135deg, #dc2626, #f43f5e) !important;
            border: 0 !important;
            color: #ffffff !important;
            border-radius: 10px !important;
            font-weight: 900 !important;
        }

        .region-card {
            height: 100%;
            background: rgba(8, 20, 48, .32);
            border: 1px solid rgba(56, 189, 248, .42);
            border-left: 5px solid var(--cyan);
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 12px 28px rgba(0, 0, 0, .20);
        }

        .region-card-head {
            padding: 14px 15px;
            background: linear-gradient(135deg, rgba(29, 155, 240, .20), rgba(23, 189, 212, .10));
            border-bottom: 1px solid rgba(56, 189, 248, .22);
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 12px;
        }

        .region-card-head h5 {
            margin: 0;
            font-weight: 900;
            color: #ffffff;
        }

        .region-card-head small,
        .region-meta {
            color: var(--muted);
            font-weight: 700;
        }

        .region-card-body {
            padding: 14px;
        }

        .city-mini-row {
            padding: 11px 0;
            border-bottom: 1px solid rgba(96, 165, 250, .16);
        }

        .city-mini-row:last-child {
            border-bottom: 0;
        }

        .city-name {
            font-weight: 900;
            color: #ffffff;
        }

        .modal-city-row {
            background: rgba(8, 20, 48, .28);
            border: 1px solid rgba(96, 165, 250, .20);
            border-radius: 14px;
            padding: 12px;
            margin-bottom: 10px;
        }

        .modal-city-row:last-child {
            margin-bottom: 0;
        }


        .all-records-note {
            color: var(--muted);
            font-weight: 700;
        }

        .search-result-pill {
            display: inline-flex;
            align-items: center;
            gap: 7px;
            padding: 7px 11px;
            border-radius: 999px;
            background: rgba(56, 189, 248, .14);
            border: 1px solid rgba(56, 189, 248, .32);
            color: #dff7ff;
            font-weight: 800;
            font-size: .84rem;
        }

        @media(max-width: 850px) {
            .sidebar {
                position: relative;
                width: 100%;
                min-height: auto;
            }

            .main-content {
                margin-left: 0;
                padding: 14px;
            }

            .header-card {
                display: block;
            }

            .table {
                min-width: 950px;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/ushs-global-theme.css">
    <link rel="stylesheet" href="../assets/admin-sidebar.css">
</head>

<body>
<?php require_once __DIR__ . '/admin_sidebar.php'; render_admin_sidebar(); ?>

    <main class="main-content">
    <div class="header-card">
        <div>
            <h2>
                <i class="fas fa-map-location-dot me-2" style="color:var(--cyan)"></i>
                Service Areas & ZIP Coverage
            </h2>

            <p class="mb-0">
                This page now uses the <strong>service_areas</strong> master table for Region, City, State, and ZIP autofill.
            </p>
        </div>

        <span class="badge bg-info p-2">
            <i class="fas fa-calendar me-1"></i>
            <?= date('F d, Y') ?>
        </span>
    </div>

    <?php if($success_message): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle me-2"></i>
            <?= h($success_message) ?>
        </div>
    <?php endif; ?>

    <?php if($error_message): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle me-2"></i>
            <?= h($error_message) ?>
        </div>
    <?php endif; ?>

    <div class="row mb-4">
        <div class="col-md-3 col-6 mb-3">
            <div class="stat-card">
                <small class="text-muted">Total ZIP Codes</small>
                <h3><?= number_format((int)($stats['total_zips'] ?? 0)) ?></h3>
            </div>
        </div>

        <div class="col-md-3 col-6 mb-3">
            <div class="stat-card">
                <small class="text-muted">Active ZIP Codes</small>
                <h3><?= number_format((int)($stats['active_zips'] ?? 0)) ?></h3>
            </div>
        </div>

        <div class="col-md-3 col-6 mb-3">
            <div class="stat-card">
                <small class="text-muted">Cities</small>
                <h3><?= number_format((int)($stats['total_cities'] ?? 0)) ?></h3>
            </div>
        </div>

        <div class="col-md-3 col-6 mb-3">
            <div class="stat-card">
                <small class="text-muted">Regions</small>
                <h3><?= number_format((int)($stats['total_regions'] ?? 0)) ?></h3>
            </div>
        </div>
    </div>

    <div class="panel mb-4">
        <div class="panel-head">
            <i class="fas fa-plus-circle me-2"></i>
            Add / Update ZIP Coverage
        </div>

        <div class="panel-body">
            <form method="POST" class="row g-3">
                <input type="hidden" name="action" value="add_area">

                <div class="col-md-3">
                    <label class="form-label">Region</label>
                    <input class="form-control" name="region" placeholder="Atlanta" required>
                </div>

                <div class="col-md-3">
                    <label class="form-label">City</label>
                    <input class="form-control" name="city" placeholder="Avondale Estates" required>
                </div>

                <div class="col-md-3">
                    <label class="form-label">State</label>

                    <select class="form-select" name="state" required>
                        <option value="">Select State</option>

                        <?php foreach($states as $state): ?>
                            <option value="<?= h($state) ?>">
                                <?= h($state) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-2">
                    <label class="form-label">ZIP Code</label>
                    <input class="form-control" name="zip_code" maxlength="5" pattern="\d{5}" placeholder="30002" required>
                </div>

                <div class="col-md-1 d-flex align-items-end">
                    <button class="btn btn-main w-100">
                        <i class="fas fa-save"></i>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="panel mb-4">
        <div class="panel-head">
            <i class="fas fa-search me-2"></i>
            Search Coverage
        </div>

        <div class="panel-body">
            <form method="GET" action="cities.php" class="row g-3 align-items-end">
                <div class="col-md-8">
                    <label class="form-label">Search ZIP, City, State, or Region</label>
                    <input 
                        class="form-control" 
                        name="search" 
                        value="<?= h($search) ?>" 
                        placeholder="Example: 30002, Atlanta, Georgia, Dallas..."
                    >
                </div>

                <div class="col-md-2">
                    <button type="submit" class="btn btn-main w-100">
                        <i class="fas fa-search me-1"></i>
                        Search
                    </button>
                </div>

                <div class="col-md-2">
                    <a href="cities.php" class="btn btn-soft w-100">
                        <i class="fas fa-rotate-left me-1"></i>
                        Clear
                    </a>
                </div>

                <?php if($search !== ''): ?>
                    <div class="col-12">
                        <span class="search-result-pill">
                            <i class="fas fa-filter"></i>
                            Showing results for: <?= h($search) ?>
                        </span>
                    </div>
                <?php endif; ?>
            </form>
        </div>
    </div>

    <div class="panel mb-4">
        <div class="panel-head">
            <i class="fas fa-layer-group me-2"></i>
            Coverage by Region
            <span class="badge bg-secondary ms-2">
                <?= count($regions) ?> regions shown
            </span>
            <span class="badge bg-info ms-1">
                <?= count($cityGroups) ?> cities grouped
            </span>
        </div>

        <div class="panel-body">
            <?php if(!$regions): ?>
                <div class="text-center text-muted py-4">
                    No service areas found.
                </div>
            <?php endif; ?>

            <div class="row g-3">
                <?php $regionIndex = 0; ?>
                <?php foreach($regions as $regionName => $regionData): ?>
                    <?php
                        $regionIndex++;
                        $modalId = 'regionCitiesModal' . $regionIndex;
                        $previewCities = array_slice($regionData['cities'], 0, 5);
                        $hiddenCityCount = max(0, (int)$regionData['total_cities'] - count($previewCities));
                        $stateNames = array_keys($regionData['states']);
                    ?>

                    <div class="col-xl-4 col-lg-6">
                        <div class="region-card">
                            <div class="region-card-head">
                                <div>
                                    <h5>
                                        <i class="fas fa-location-dot me-2" style="color:var(--cyan)"></i>
                                        <?= h($regionName) ?>
                                    </h5>
                                    <small>
                                        <?= h(implode(', ', $stateNames)) ?>
                                    </small>
                                </div>

                                <span class="badge bg-info">
                                    <?= (int)$regionData['total_cities'] ?> Cities
                                </span>
                            </div>

                            <div class="region-card-body">
                                <div class="d-flex flex-wrap gap-2 mb-3 region-meta">
                                    <span class="badge bg-primary">
                                        <?= (int)$regionData['total_zips'] ?> ZIPs
                                    </span>

                                    <span class="badge bg-success">
                                        <?= (int)$regionData['active_cities'] ?> Active Cities
                                    </span>
                                </div>

                                <?php foreach($previewCities as $city): ?>
                                    <div class="city-mini-row">
                                        <div class="d-flex justify-content-between gap-2 align-items-start">
                                            <div>
                                                <div class="city-name">
                                                    <?= h($city['city']) ?>
                                                </div>
                                                <small class="text-muted">
                                                    <?= h($city['state']) ?>
                                                </small>
                                            </div>

                                            <span class="badge bg-info">
                                                <?= (int)$city['zip_count'] ?> ZIP<?= ((int)$city['zip_count'] === 1) ? '' : 's' ?>
                                            </span>
                                        </div>

                                        <div class="mt-2">
                                            <?php foreach(explode(',', (string)$city['zip_codes']) as $zip): ?>
                                                <span class="zip-badge">
                                                    <?= h(trim($zip)) ?>
                                                </span>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>

                                <?php if($hiddenCityCount > 0): ?>
                                    <button 
                                        type="button" 
                                        class="btn btn-soft w-100 mt-3"
                                        data-bs-toggle="modal"
                                        data-bs-target="#<?= h($modalId) ?>"
                                    >
                                        <i class="fas fa-eye me-1"></i>
                                        View All <?= (int)$regionData['total_cities'] ?> Cities
                                    </button>
                                <?php else: ?>
                                    <button 
                                        type="button" 
                                        class="btn btn-soft w-100 mt-3"
                                        data-bs-toggle="modal"
                                        data-bs-target="#<?= h($modalId) ?>"
                                    >
                                        <i class="fas fa-eye me-1"></i>
                                        View Details
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <div class="panel">
        <div class="panel-head">
            <i class="fas fa-list me-2"></i>
            Individual ZIP Records
            <span class="badge bg-secondary ms-2">
                Showing <?= (int)$shownAreaRows ?> of <?= (int)$totalAreaRows ?> rows
            </span>
            <?php if($search !== ''): ?>
                <span class="badge bg-info ms-1">Filtered</span>
            <?php endif; ?>
        </div>

        <div class="panel-body">
            <div class="d-flex justify-content-between align-items-center gap-2 flex-wrap mb-3">
                <div class="all-records-note">
                    Showing only the first 20 records to keep the page clean.
                    <?php if($totalAreaRows > 20): ?>
                        Click View All to see the complete filtered list.
                    <?php endif; ?>
                </div>

                <button 
                    type="button" 
                    class="btn btn-soft"
                    data-bs-toggle="modal"
                    data-bs-target="#allZipRecordsModal"
                    <?= $totalAreaRows === 0 ? 'disabled' : '' ?>
                >
                    <i class="fas fa-eye me-1"></i>
                    View All <?= (int)$totalAreaRows ?> Records
                </button>
            </div>

            <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>ZIP</th>
                        <th>City</th>
                        <th>State</th>
                        <th>Region</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach($areas as $a): ?>
                        <tr>
                            <td><?= (int)$a['id'] ?></td>

                            <td>
                                <strong><?= h($a['zip_code']) ?></strong>
                            </td>

                            <td><?= h($a['city']) ?></td>
                            <td><?= h($a['state']) ?></td>
                            <td><?= h($a['region']) ?></td>

                            <td>
                                <?= ((int)$a['is_active'] === 1) 
                                    ? '<span class="badge bg-success">Active</span>' 
                                    : '<span class="badge bg-secondary">Inactive</span>' 
                                ?>
                            </td>

                            <td>
                                <button 
                                    class="btn btn-sm btn-soft" 
                                    onclick='editArea(<?= json_encode($a, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>)'
                                    title="Edit"
                                >
                                    <i class="fas fa-edit"></i>
                                </button>

                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="action" value="toggle_area">
                                    <input type="hidden" name="area_id" value="<?= (int)$a['id'] ?>">

                                    <button class="btn btn-sm btn-soft" title="Toggle">
                                        <i class="fas fa-power-off"></i>
                                    </button>
                                </form>

                                <button 
                                    type="button"
                                    class="btn btn-sm btn-danger-soft"
                                    onclick="openDeleteModal(<?= (int)$a['id'] ?>)"
                                    title="Delete"
                                >
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>

                    <?php if(!$areas): ?>
                        <tr>
                            <td colspan="7" class="text-center text-muted py-4">
                                No individual ZIP records found.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="allZipRecordsModal" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <h5 class="modal-title">
                        <i class="fas fa-list me-2"></i>
                        All Individual ZIP Records
                    </h5>
                    <small class="text-muted">
                        <?= (int)$totalAreaRows ?> total record<?= $totalAreaRows === 1 ? '' : 's' ?><?= $search !== '' ? ' matching your search' : '' ?>
                    </small>
                </div>

                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>ZIP</th>
                                <th>City</th>
                                <th>State</th>
                                <th>Region</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php foreach($allAreas as $a): ?>
                                <tr>
                                    <td><?= (int)$a['id'] ?></td>
                                    <td><strong><?= h($a['zip_code']) ?></strong></td>
                                    <td><?= h($a['city']) ?></td>
                                    <td><?= h($a['state']) ?></td>
                                    <td><?= h($a['region']) ?></td>
                                    <td>
                                        <?= ((int)$a['is_active'] === 1) 
                                            ? '<span class="badge bg-success">Active</span>' 
                                            : '<span class="badge bg-secondary">Inactive</span>' 
                                        ?>
                                    </td>
                                    <td>
                                        <button 
                                            class="btn btn-sm btn-soft" 
                                            onclick='editArea(<?= json_encode($a, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>)'
                                            title="Edit"
                                        >
                                            <i class="fas fa-edit"></i>
                                        </button>

                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="action" value="toggle_area">
                                            <input type="hidden" name="area_id" value="<?= (int)$a['id'] ?>">
                                            <button class="btn btn-sm btn-soft" title="Toggle">
                                                <i class="fas fa-power-off"></i>
                                            </button>
                                        </form>

                                        <button 
                                            type="button"
                                            class="btn btn-sm btn-danger-soft"
                                            onclick="openDeleteModal(<?= (int)$a['id'] ?>)"
                                            title="Delete"
                                        >
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>

                            <?php if(!$allAreas): ?>
                                <tr>
                                    <td colspan="7" class="text-center text-muted py-4">
                                        No individual ZIP records found.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>

<?php $regionModalIndex = 0; ?>
<?php foreach($regions as $regionName => $regionData): ?>
    <?php
        $regionModalIndex++;
        $modalId = 'regionCitiesModal' . $regionModalIndex;
        $stateNames = array_keys($regionData['states']);
    ?>

    <div class="modal fade" id="<?= h($modalId) ?>" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <div>
                        <h5 class="modal-title">
                            <i class="fas fa-map-location-dot me-2"></i>
                            <?= h($regionName) ?> Cities
                        </h5>
                        <small class="text-muted">
                            <?= h(implode(', ', $stateNames)) ?> • <?= (int)$regionData['total_cities'] ?> cities • <?= (int)$regionData['total_zips'] ?> ZIP codes
                        </small>
                    </div>

                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body">
                    <?php foreach($regionData['cities'] as $city): ?>
                        <div class="modal-city-row">
                            <div class="d-flex justify-content-between align-items-start gap-2 flex-wrap">
                                <div>
                                    <div class="city-name">
                                        <?= h($city['city']) ?>
                                    </div>
                                    <small class="text-muted">
                                        <?= h($city['state']) ?>
                                    </small>
                                </div>

                                <div class="d-flex gap-2 flex-wrap">
                                    <span class="badge bg-info">
                                        <?= (int)$city['zip_count'] ?> ZIP<?= ((int)$city['zip_count'] === 1) ? '' : 's' ?>
                                    </span>

                                    <?= ((int)$city['active_count'] > 0) 
                                        ? '<span class="badge bg-success">Active</span>' 
                                        : '<span class="badge bg-secondary">Inactive</span>' 
                                    ?>
                                </div>
                            </div>

                            <div class="mt-2">
                                <?php foreach(explode(',', (string)$city['zip_codes']) as $zip): ?>
                                    <span class="zip-badge">
                                        <?= h(trim($zip)) ?>
                                    </span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        Close
                    </button>
                </div>
            </div>
        </div>
    </div>
<?php endforeach; ?>

<div class="modal fade" id="editAreaModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="edit_area">
                <input type="hidden" name="area_id" id="edit_area_id">

                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-edit me-2"></i>
                        Edit ZIP Coverage
                    </h5>

                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Region</label>
                        <input class="form-control" name="region" id="edit_region" required>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">City</label>
                        <input class="form-control" name="city" id="edit_city" required>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">State</label>

                        <select class="form-select" name="state" id="edit_state" required>
                            <?php foreach($states as $state): ?>
                                <option value="<?= h($state) ?>">
                                    <?= h($state) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">ZIP Code</label>
                        <input class="form-control" name="zip_code" id="edit_zip" maxlength="5" pattern="\d{5}" required>
                    </div>

                    <div class="col-12">
                        <label class="form-check">
                            <input class="form-check-input" type="checkbox" name="is_active" id="edit_active" value="1">
                            <span class="form-check-label">Active</span>
                        </label>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        Cancel
                    </button>

                    <button class="btn btn-main">
                        <i class="fas fa-save me-1"></i>
                        Save Changes
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="delete-confirm-overlay" id="deleteConfirmOverlay">
    <div class="delete-confirm-modal">
        <div class="delete-confirm-header">
            <div class="delete-confirm-icon">
                <i class="fas fa-trash"></i>
            </div>

            <div>
                <h4>Delete ZIP Coverage?</h4>
                <small>This action cannot be undone.</small>
            </div>
        </div>

        <div class="delete-confirm-body">
            <p class="mb-1">
                Are you sure you want to delete this ZIP coverage record?
            </p>

            <p class="mb-0">
                This will remove this ZIP from the service coverage and ZIP auto-fill source.
            </p>

            <div class="delete-confirm-warning">
                <i class="fas fa-triangle-exclamation me-1"></i>
                Only delete wrong, duplicate, or outdated ZIP records.
            </div>
        </div>

        <div class="delete-confirm-footer">
            <button type="button" class="btn btn-cancel-delete" onclick="closeDeleteModal()">
                Cancel
            </button>

            <form method="POST" id="deleteAreaForm" class="m-0">
                <input type="hidden" name="action" value="delete_area">
                <input type="hidden" name="area_id" id="delete_area_id">

                <button type="submit" class="btn btn-confirm-delete">
                    <i class="fas fa-trash me-1"></i>
                    Delete ZIP
                </button>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
function editArea(a) {
    document.getElementById('edit_area_id').value = a.id || '';
    document.getElementById('edit_region').value = a.region || '';
    document.getElementById('edit_city').value = a.city || '';
    document.getElementById('edit_state').value = a.state || '';
    document.getElementById('edit_zip').value = a.zip_code || '';
    document.getElementById('edit_active').checked = Number(a.is_active) === 1;

    new bootstrap.Modal(document.getElementById('editAreaModal')).show();
}

function openDeleteModal(id) {
    document.getElementById('delete_area_id').value = id || '';
    document.getElementById('deleteConfirmOverlay').style.display = 'flex';
}

function closeDeleteModal() {
    document.getElementById('delete_area_id').value = '';
    document.getElementById('deleteConfirmOverlay').style.display = 'none';
}
</script>
</body>
</html>