<?php
session_start();
include 'layouts/dbconn.php';
include 'includes/menu_config.php';

// Set timezone
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Fetch user details
$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details) {
    header('Location: logout.php');
    exit();
}

$full_name = $user_details['full_name'];
$role_name = $user_details['role_name'];

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    try {
        switch ($_POST['action']) {
            // COUNTRY ACTIONS
            case 'create_country':
                $country_code = strtoupper(trim($_POST['country_code']));
                $country_name = trim($_POST['country_name']);
                $currency_code = strtoupper(trim($_POST['currency_code']));
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                // Check for duplicate
                $check_sql = "SELECT country_id FROM countries WHERE country_code = ?";
                $stmt_check = $conn->prepare($check_sql);
                $stmt_check->bind_param("s", $country_code);
                $stmt_check->execute();
                if ($stmt_check->get_result()->num_rows > 0) {
                    echo json_encode(['success' => false, 'message' => 'Country code already exists']);
                    exit();
                }
                
                $insert_sql = "INSERT INTO countries (country_code, country_name, currency_code, is_active) 
                              VALUES (?, ?, ?, ?)";
                $stmt = $conn->prepare($insert_sql);
                $stmt->bind_param("sssi", $country_code, $country_name, $currency_code, $is_active);
                
                if ($stmt->execute()) {
                    $country_id = $conn->insert_id;
                    
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                               VALUES (?, 'CREATE', 'countries', ?, ?)";
                    $stmt_log = $conn->prepare($log_sql);
                    $log_details = json_encode(['country_code' => $country_code, 'country_name' => $country_name]);
                    $stmt_log->bind_param("iss", $user_id, $country_id, $log_details);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'Country created successfully', 'country_id' => $country_id]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to create country']);
                }
                break;
                
            case 'update_country':
                $country_id = intval($_POST['country_id']);
                $country_code = strtoupper(trim($_POST['country_code']));
                $country_name = trim($_POST['country_name']);
                $currency_code = strtoupper(trim($_POST['currency_code']));
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                // Check for duplicate (excluding current)
                $check_sql = "SELECT country_id FROM countries WHERE country_code = ? AND country_id != ?";
                $stmt_check = $conn->prepare($check_sql);
                $stmt_check->bind_param("si", $country_code, $country_id);
                $stmt_check->execute();
                if ($stmt_check->get_result()->num_rows > 0) {
                    echo json_encode(['success' => false, 'message' => 'Country code already exists']);
                    exit();
                }
                
                $update_sql = "UPDATE countries SET country_code = ?, country_name = ?, currency_code = ?, is_active = ? 
                              WHERE country_id = ?";
                $stmt = $conn->prepare($update_sql);
                $stmt->bind_param("sssii", $country_code, $country_name, $currency_code, $is_active, $country_id);
                
                if ($stmt->execute()) {
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                               VALUES (?, 'UPDATE', 'countries', ?, ?)";
                    $stmt_log = $conn->prepare($log_sql);
                    $log_details = json_encode(['country_code' => $country_code, 'country_name' => $country_name]);
                    $stmt_log->bind_param("iss", $user_id, $country_id, $log_details);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'Country updated successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to update country']);
                }
                break;
                
            case 'delete_country':
                $country_id = intval($_POST['country_id']);
                
                // Check if country is being used
                $check_locations = "SELECT COUNT(*) as count FROM locations WHERE country_id = ?";
                $stmt_check = $conn->prepare($check_locations);
                $stmt_check->bind_param("i", $country_id);
                $stmt_check->execute();
                $usage = $stmt_check->get_result()->fetch_assoc();
                
                if ($usage['count'] > 0) {
                    echo json_encode(['success' => false, 'message' => 'Cannot delete country. It is being used in ' . $usage['count'] . ' location(s)']);
                    exit();
                }
                
                $delete_sql = "DELETE FROM countries WHERE country_id = ?";
                $stmt = $conn->prepare($delete_sql);
                $stmt->bind_param("i", $country_id);
                
                if ($stmt->execute()) {
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values) 
                               VALUES (?, 'DELETE', 'countries', ?, ?)";
                    $stmt_log = $conn->prepare($log_sql);
                    $log_details = json_encode(['country_id' => $country_id]);
                    $stmt_log->bind_param("iss", $user_id, $country_id, $log_details);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'Country deleted successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to delete country']);
                }
                break;
                
            // ZONE ACTIONS
            case 'create_zone':
                $zone_code = strtoupper(trim($_POST['zone_code']));
                $zone_name = trim($_POST['zone_name']);
                $description = trim($_POST['description']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                // Check for duplicate
                $check_sql = "SELECT zone_id FROM zones WHERE zone_code = ?";
                $stmt_check = $conn->prepare($check_sql);
                $stmt_check->bind_param("s", $zone_code);
                $stmt_check->execute();
                if ($stmt_check->get_result()->num_rows > 0) {
                    echo json_encode(['success' => false, 'message' => 'Zone code already exists']);
                    exit();
                }
                
                $insert_sql = "INSERT INTO zones (zone_code, zone_name, description, is_active) 
                              VALUES (?, ?, ?, ?)";
                $stmt = $conn->prepare($insert_sql);
                $stmt->bind_param("sssi", $zone_code, $zone_name, $description, $is_active);
                
                if ($stmt->execute()) {
                    $zone_id = $conn->insert_id;
                    
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                               VALUES (?, 'CREATE', 'zones', ?, ?)";
                    $stmt_log = $conn->prepare($log_sql);
                    $log_details = json_encode(['zone_code' => $zone_code, 'zone_name' => $zone_name]);
                    $stmt_log->bind_param("iss", $user_id, $zone_id, $log_details);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'Zone created successfully', 'zone_id' => $zone_id]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to create zone']);
                }
                break;
                
            case 'update_zone':
                $zone_id = intval($_POST['zone_id']);
                $zone_code = strtoupper(trim($_POST['zone_code']));
                $zone_name = trim($_POST['zone_name']);
                $description = trim($_POST['description']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                // Check for duplicate (excluding current)
                $check_sql = "SELECT zone_id FROM zones WHERE zone_code = ? AND zone_id != ?";
                $stmt_check = $conn->prepare($check_sql);
                $stmt_check->bind_param("si", $zone_code, $zone_id);
                $stmt_check->execute();
                if ($stmt_check->get_result()->num_rows > 0) {
                    echo json_encode(['success' => false, 'message' => 'Zone code already exists']);
                    exit();
                }
                
                $update_sql = "UPDATE zones SET zone_code = ?, zone_name = ?, description = ?, is_active = ? 
                              WHERE zone_id = ?";
                $stmt = $conn->prepare($update_sql);
                $stmt->bind_param("sssii", $zone_code, $zone_name, $description, $is_active, $zone_id);
                
                if ($stmt->execute()) {
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                               VALUES (?, 'UPDATE', 'zones', ?, ?)";
                    $stmt_log = $conn->prepare($log_sql);
                    $log_details = json_encode(['zone_code' => $zone_code, 'zone_name' => $zone_name]);
                    $stmt_log->bind_param("iss", $user_id, $zone_id, $log_details);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'Zone updated successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to update zone']);
                }
                break;
                
            case 'delete_zone':
                $zone_id = intval($_POST['zone_id']);
                
                // Check if zone is being used
                $check_locations = "SELECT COUNT(*) as count FROM locations WHERE zone_id = ?";
                $stmt_check = $conn->prepare($check_locations);
                $stmt_check->bind_param("i", $zone_id);
                $stmt_check->execute();
                $usage = $stmt_check->get_result()->fetch_assoc();
                
                if ($usage['count'] > 0) {
                    echo json_encode(['success' => false, 'message' => 'Cannot delete zone. It is being used in ' . $usage['count'] . ' location(s)']);
                    exit();
                }
                
                $delete_sql = "DELETE FROM zones WHERE zone_id = ?";
                $stmt = $conn->prepare($delete_sql);
                $stmt->bind_param("i", $zone_id);
                
                if ($stmt->execute()) {
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values) 
                               VALUES (?, 'DELETE', 'zones', ?, ?)";
                    $stmt_log = $conn->prepare($log_sql);
                    $log_details = json_encode(['zone_id' => $zone_id]);
                    $stmt_log->bind_param("iss", $user_id, $zone_id, $log_details);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'Zone deleted successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to delete zone']);
                }
                break;
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
    exit();
}

// Fetch countries with location count
$sql_countries = "SELECT c.*, 
                  (SELECT COUNT(*) FROM locations WHERE country_id = c.country_id) as location_count
                  FROM countries c
                  ORDER BY c.is_active DESC, c.country_name";
$result_countries = $conn->query($sql_countries);

// Fetch zones with location count
$sql_zones = "SELECT z.*, 
              (SELECT COUNT(*) FROM locations WHERE zone_id = z.zone_id) as location_count
              FROM zones z
              ORDER BY z.is_active DESC, z.zone_name";
$result_zones = $conn->query($sql_zones);

// Get statistics
$country_stats = [
    'total' => 0,
    'active' => 0
];

$stats_sql = "SELECT 
              COUNT(*) as total,
              SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active
              FROM countries";
$stats_result = $conn->query($stats_sql);
if ($stats_result) {
    $country_stats = $stats_result->fetch_assoc();
}

$zone_stats = [
    'total' => 0,
    'active' => 0
];

$stats_sql = "SELECT 
              COUNT(*) as total,
              SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active
              FROM zones";
$stats_result = $conn->query($stats_sql);
if ($stats_result) {
    $zone_stats = $stats_result->fetch_assoc();
}

?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Countries & Zones Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .content-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
        }
        
        .content-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }
        
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
        }
        
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            transform: translate(30px, -30px);
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .action-btn {
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.75rem;
            margin: 0.1rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-edit { background: #fff3e0; color: #ef6c00; }
        .btn-delete { background: #ffebee; color: #c62828; }
        
        .action-btn:hover {
            transform: scale(1.05);
        }
        
        .country-flag {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .zone-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(45deg, #4facfe, #00f2fe);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .create-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(40,167,69,0.3);
        }
        
        .create-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(40,167,69,0.4);
            color: white;
        }
        
        .nav-tabs .nav-link {
            border: none;
            border-radius: 8px;
            margin-right: 0.5rem;
            padding: 0.75rem 1.5rem;
            color: #64748b;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        .nav-tabs .nav-link:hover {
            background: #f1f5f9;
            color: #334155;
        }
        
        .nav-tabs .nav-link.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }
        
        @media (max-width: 768px) {
            .stat-card {
                margin-bottom: 1rem;
            }
            
            .stat-value {
                font-size: 1.5rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><i class="ri-global-line me-2"></i>Countries & Zones Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="locations.php">Locations</a></li>
                                        <li class="breadcrumb-item active">Countries & Zones</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Navigation Tabs -->
                    <ul class="nav nav-tabs mb-4" id="mainTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="countries-tab" data-bs-toggle="tab" data-bs-target="#countries" type="button" role="tab">
                                <i class="ri-flag-line me-2"></i>Countries
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="zones-tab" data-bs-toggle="tab" data-bs-target="#zones" type="button" role="tab">
                                <i class="ri-map-2-line me-2"></i>Zones
                            </button>
                        </li>
                    </ul>

                    <div class="tab-content" id="mainTabContent">
                        
                        <!-- COUNTRIES TAB -->
                        <div class="tab-pane fade show active" id="countries" role="tabpanel">
                            
                            <!-- Statistics Cards -->
                            <div class="row mb-4">
                                <div class="col-xl-4 col-md-6">
                                    <div class="stat-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                        <div class="stat-value"><?php echo number_format($country_stats['total']); ?></div>
                                        <div class="stat-label">Total Countries</div>
                                    </div>
                                </div>
                                
                                <div class="col-xl-4 col-md-6">
                                    <div class="stat-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                        <div class="stat-value"><?php echo number_format($country_stats['active']); ?></div>
                                        <div class="stat-label">Active Countries</div>
                                    </div>
                                </div>
                                
                                <div class="col-xl-4 col-md-6">
                                    <div class="stat-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                        <div class="stat-value">
                                            <?php 
                                            $currencies_sql = "SELECT COUNT(DISTINCT currency_code) as count FROM countries WHERE is_active = 1";
                                            $currencies_result = $conn->query($currencies_sql);
                                            echo number_format($currencies_result->fetch_assoc()['count']);
                                            ?>
                                        </div>
                                        <div class="stat-label">Active Currencies</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Actions -->
                            <div class="row">
                                <div class="col-12">
                                    <div class="content-card">
                                        <div class="card-body">
                                            <button class="btn create-btn" onclick="showCreateCountryModal()">
                                                <i class="ri-add-line me-1"></i>Add New Country
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Countries Table -->
                            <div class="row">
                                <div class="col-12">
                                    <div class="content-card">
                                        <div class="card-header bg-transparent border-bottom">
                                            <h5 class="card-title mb-0">
                                                <i class="ri-flag-2-line me-2"></i>All Countries
                                            </h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="table-responsive">
                                                <table class="table table-hover" id="countriesTable">
                                                    <thead>
                                                        <tr>
                                                            <th>Code</th>
                                                            <th>Country Name</th>
                                                            <th>Currency</th>
                                                            <th>Locations</th>
                                                            <th>Status</th>
                                                            <th>Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php 
                                                        $result_countries->data_seek(0);
                                                        while ($country = $result_countries->fetch_assoc()): 
                                                        ?>
                                                        <tr>
                                                            <td>
                                                                <div class="d-flex align-items-center">
                                                                    <div class="country-flag me-2">
                                                                        <?php echo strtoupper(substr($country['country_code'], 0, 2)); ?>
                                                                    </div>
                                                                    <strong><?php echo $country['country_code']; ?></strong>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div class="fw-bold"><?php echo $country['country_name']; ?></div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-primary"><?php echo $country['currency_code']; ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-info"><?php echo number_format($country['location_count']); ?> locations</span>
                                                            </td>
                                                            <td>
                                                                <?php if ($country['is_active']): ?>
                                                                <span class="badge bg-success">Active</span>
                                                                <?php else: ?>
                                                                <span class="badge bg-danger">Inactive</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <div class="btn-group" role="group">
                                                                    <button class="action-btn btn-edit" 
                                                                            onclick='editCountry(<?php echo json_encode($country); ?>)'
                                                                            title="Edit Country">
                                                                        <i class="ri-edit-line"></i>
                                                                    </button>
                                                                    <button class="action-btn btn-delete" 
                                                                            onclick="deleteCountry(<?php echo $country['country_id']; ?>, '<?php echo addslashes($country['country_name']); ?>')"
                                                                            title="Delete Country">
                                                                        <i class="ri-delete-bin-line"></i>
                                                                    </button>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                        <?php endwhile; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- ZONES TAB -->
                        <div class="tab-pane fade" id="zones" role="tabpanel">
                            
                            <!-- Statistics Cards -->
                            <div class="row mb-4">
                                <div class="col-xl-4 col-md-6">
                                    <div class="stat-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                        <div class="stat-value"><?php echo number_format($zone_stats['total']); ?></div>
                                        <div class="stat-label">Total Zones</div>
                                    </div>
                                </div>
                                
                                <div class="col-xl-4 col-md-6">
                                    <div class="stat-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                                        <div class="stat-value"><?php echo number_format($zone_stats['active']); ?></div>
                                        <div class="stat-label">Active Zones</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Actions -->
                            <div class="row">
                                <div class="col-12">
                                    <div class="content-card">
                                        <div class="card-body">
                                            <button class="btn create-btn" onclick="showCreateZoneModal()">
                                                <i class="ri-add-line me-1"></i>Add New Zone
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Zones Table -->
                            <div class="row">
                                <div class="col-12">
                                    <div class="content-card">
                                        <div class="card-header bg-transparent border-bottom">
                                            <h5 class="card-title mb-0">
                                                <i class="ri-map-2-fill me-2"></i>All Zones
                                            </h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="table-responsive">
                                                <table class="table table-hover" id="zonesTable">
                                                    <thead>
                                                        <tr>
                                                            <th>Code</th>
                                                            <th>Zone Name</th>
                                                            <th>Description</th>
                                                            <th>Locations</th>
                                                            <th>Status</th>
                                                            <th>Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php 
                                                        $result_zones->data_seek(0);
                                                        while ($zone = $result_zones->fetch_assoc()): 
                                                        ?>
                                                        <tr>
                                                            <td>
                                                                <div class="d-flex align-items-center">
                                                                    <div class="zone-icon me-2">
                                                                        <?php echo strtoupper(substr($zone['zone_code'], 0, 2)); ?>
                                                                    </div>
                                                                    <strong><?php echo $zone['zone_code']; ?></strong>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div class="fw-bold"><?php echo $zone['zone_name']; ?></div>
                                                            </td>
                                                            <td>
                                                                <small class="text-muted"><?php echo $zone['description'] ?: 'N/A'; ?></small>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-info"><?php echo number_format($zone['location_count']); ?> locations</span>
                                                            </td>
                                                            <td>
                                                                <?php if ($zone['is_active']): ?>
                                                                <span class="badge bg-success">Active</span>
                                                                <?php else: ?>
                                                                <span class="badge bg-danger">Inactive</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <div class="btn-group" role="group">
                                                                    <button class="action-btn btn-edit" 
                                                                            onclick='editZone(<?php echo json_encode($zone); ?>)'
                                                                            title="Edit Zone">
                                                                        <i class="ri-edit-line"></i>
                                                                    </button>
                                                                    <button class="action-btn btn-delete" 
                                                                            onclick="deleteZone(<?php echo $zone['zone_id']; ?>, '<?php echo addslashes($zone['zone_name']); ?>')"
                                                                            title="Delete Zone">
                                                                        <i class="ri-delete-bin-line"></i>
                                                                    </button>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                        <?php endwhile; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Country Modal -->
    <div class="modal fade" id="countryModal" tabindex="-1" aria-labelledby="countryModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="countryModalLabel">
                        <i class="ri-flag-line me-2"></i><span id="countryModalTitle">Add New Country</span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="countryForm" method="POST">
                    <input type="hidden" name="action" id="countryFormAction" value="create_country">
                    <input type="hidden" name="country_id" id="country_id">
                    
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-12">
                                <label for="country_code" class="form-label">Country Code *</label>
                                <input type="text" class="form-control text-uppercase" id="country_code" name="country_code" 
                                       required maxlength="3" placeholder="e.g., KEN, USA, GBR">
                                <div class="form-text">ISO 3166-1 alpha-3 code (3 characters)</div>
                            </div>
                            
                            <div class="col-12">
                                <label for="country_name" class="form-label">Country Name *</label>
                                <input type="text" class="form-control" id="country_name" name="country_name" 
                                       required maxlength="100" placeholder="e.g., Kenya">
                            </div>
                            
                            <div class="col-12">
                                <label for="currency_code" class="form-label">Currency Code *</label>
                                <input type="text" class="form-control text-uppercase" id="currency_code" name="currency_code" 
                                       required maxlength="3" placeholder="e.g., KES, USD, GBP">
                                <div class="form-text">ISO 4217 currency code (3 characters)</div>
                            </div>
                            
                            <div class="col-12">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="country_is_active" name="is_active" value="1" checked>
                                    <label class="form-check-label" for="country_is_active">
                                        <i class="ri-checkbox-circle-line me-1"></i>Active
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="ri-close-line me-1"></i>Cancel
                        </button>
                        <button type="submit" class="btn btn-success">
                            <i class="ri-save-line me-1"></i><span id="countrySubmitBtnText">Create Country</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Zone Modal -->
    <div class="modal fade" id="zoneModal" tabindex="-1" aria-labelledby="zoneModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="zoneModalLabel">
                        <i class="ri-map-2-line me-2"></i><span id="zoneModalTitle">Add New Zone</span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="zoneForm" method="POST">
                    <input type="hidden" name="action" id="zoneFormAction" value="create_zone">
                    <input type="hidden" name="zone_id" id="zone_id">
                    
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-12">
                                <label for="zone_code" class="form-label">Zone Code *</label>
                                <input type="text" class="form-control text-uppercase" id="zone_code" name="zone_code" 
                                       required maxlength="10" placeholder="e.g., DOM, EA, EU">
                                <div class="form-text">Unique 2-10 character code</div>
                            </div>
                            
                            <div class="col-12">
                                <label for="zone_name" class="form-label">Zone Name *</label>
                                <input type="text" class="form-control" id="zone_name" name="zone_name" 
                                       required maxlength="100" placeholder="e.g., Domestic, East Africa">
                            </div>
                            
                            <div class="col-12">
                                <label for="zone_description" class="form-label">Description</label>
                                <textarea class="form-control" id="zone_description" name="description" 
                                          rows="3" placeholder="Optional description of the zone"></textarea>
                            </div>
                            
                            <div class="col-12">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="zone_is_active" name="is_active" value="1" checked>
                                    <label class="form-check-label" for="zone_is_active">
                                        <i class="ri-checkbox-circle-line me-1"></i>Active
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="ri-close-line me-1"></i>Cancel
                        </button>
                        <button type="submit" class="btn btn-success">
                            <i class="ri-save-line me-1"></i><span id="zoneSubmitBtnText">Create Zone</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
$(document).ready(function() {
    // Initialize DataTables
    $('#countriesTable').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[1, 'asc']]
    });
    
    $('#zonesTable').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[1, 'asc']]
    });
});

// COUNTRY FUNCTIONS
function showCreateCountryModal() {
    $('#countryForm')[0].reset();
    $('#countryFormAction').val('create_country');
    $('#country_id').val('');
    $('#countryModalTitle').text('Add New Country');
    $('#countrySubmitBtnText').text('Create Country');
    $('#country_is_active').prop('checked', true);
    $('#countryModal').modal('show');
}

function editCountry(country) {
    $('#countryFormAction').val('update_country');
    $('#country_id').val(country.country_id);
    $('#country_code').val(country.country_code);
    $('#country_name').val(country.country_name);
    $('#currency_code').val(country.currency_code);
    $('#country_is_active').prop('checked', country.is_active == 1);
    
    $('#countryModalTitle').text('Edit Country');
    $('#countrySubmitBtnText').text('Update Country');
    $('#countryModal').modal('show');
}

$('#countryForm').on('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const action = $('#countryFormAction').val();
    
    Swal.fire({
        title: action === 'create_country' ? 'Creating Country...' : 'Updating Country...',
        text: 'Please wait',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'countries_zones.php',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    title: 'Success!',
                    text: response.message,
                    icon: 'success',
                    timer: 2000,
                    showConfirmButton: false
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire({
                    title: 'Error',
                    text: response.message,
                    icon: 'error'
                });
            }
        },
        error: function(xhr, status, error) {
            console.error('Error:', error);
            Swal.fire({
                title: 'Error',
                text: 'An error occurred. Please try again.',
                icon: 'error'
            });
        }
    });
});

function deleteCountry(countryId, countryName) {
    Swal.fire({
        title: 'Delete Country',
        text: `Are you sure you want to delete "${countryName}"? This action cannot be undone.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'countries_zones.php',
                method: 'POST',
                data: {
                    action: 'delete_country',
                    country_id: countryId
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Deleted!',
                            text: response.message,
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Cannot Delete',
                            text: response.message,
                            icon: 'error'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        title: 'Error',
                        text: 'An error occurred while deleting the country',
                        icon: 'error'
                    });
                }
            });
        }
    });
}

// ZONE FUNCTIONS
function showCreateZoneModal() {
    $('#zoneForm')[0].reset();
    $('#zoneFormAction').val('create_zone');
    $('#zone_id').val('');
    $('#zoneModalTitle').text('Add New Zone');
    $('#zoneSubmitBtnText').text('Create Zone');
    $('#zone_is_active').prop('checked', true);
    $('#zoneModal').modal('show');
}

function editZone(zone) {
    $('#zoneFormAction').val('update_zone');
    $('#zone_id').val(zone.zone_id);
    $('#zone_code').val(zone.zone_code);
    $('#zone_name').val(zone.zone_name);
    $('#zone_description').val(zone.description || '');
    $('#zone_is_active').prop('checked', zone.is_active == 1);
    
    $('#zoneModalTitle').text('Edit Zone');
    $('#zoneSubmitBtnText').text('Update Zone');
    $('#zoneModal').modal('show');
}

$('#zoneForm').on('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const action = $('#zoneFormAction').val();
    
    Swal.fire({
        title: action === 'create_zone' ? 'Creating Zone...' : 'Updating Zone...',
        text: 'Please wait',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'countries_zones.php',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    title: 'Success!',
                    text: response.message,
                    icon: 'success',
                    timer: 2000,
                    showConfirmButton: false
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire({
                    title: 'Error',
                    text: response.message,
                    icon: 'error'
                });
            }
        },
        error: function(xhr, status, error) {
            console.error('Error:', error);
            Swal.fire({
                title: 'Error',
                text: 'An error occurred. Please try again.',
                icon: 'error'
            });
        }
    });
});

function deleteZone(zoneId, zoneName) {
    Swal.fire({
        title: 'Delete Zone',
        text: `Are you sure you want to delete "${zoneName}"? This action cannot be undone.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'countries_zones.php',
                method: 'POST',
                data: {
                    action: 'delete_zone',
                    zone_id: zoneId
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Deleted!',
                            text: response.message,
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Cannot Delete',
                            text: response.message,
                            icon: 'error'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        title: 'Error',
                        text: 'An error occurred while deleting the zone',
                        icon: 'error'
                    });
                }
            });
        }
    });
}

// Auto-uppercase codes
$('#country_code, #currency_code, #zone_code').on('input', function() {
    this.value = this.value.toUpperCase();
});

// Tab persistence
$('a[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
    localStorage.setItem('activeCountryZoneTab', e.target.getAttribute('id'));
});

// Restore active tab
const activeTab = localStorage.getItem('activeCountryZoneTab');
if (activeTab) {
    $('#' + activeTab).tab('show');
}
</script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>
<?php $conn->close(); ?>