<?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']) {
            case 'create':
                $location_code = strtoupper(trim($_POST['location_code']));
                $location_name = trim($_POST['location_name']);
                $city = trim($_POST['city']);
                $state = trim($_POST['state']);
                $country_id = intval($_POST['country_id']);
                $zone_id = intval($_POST['zone_id']);
                $postal_code = trim($_POST['postal_code']);
                $latitude = !empty($_POST['latitude']) ? floatval($_POST['latitude']) : null;
                $longitude = !empty($_POST['longitude']) ? floatval($_POST['longitude']) : null;
                $is_origin = isset($_POST['is_origin']) ? 1 : 0;
                $is_destination = isset($_POST['is_destination']) ? 1 : 0;
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                // Check for duplicate location code
                $check_sql = "SELECT location_id FROM locations WHERE location_code = ?";
                $stmt_check = $conn->prepare($check_sql);
                $stmt_check->bind_param("s", $location_code);
                $stmt_check->execute();
                if ($stmt_check->get_result()->num_rows > 0) {
                    echo json_encode(['success' => false, 'message' => 'Location code already exists']);
                    exit();
                }
                
                $insert_sql = "INSERT INTO locations (
                                location_code, location_name, city, state, country_id, zone_id, 
                                postal_code, latitude, longitude, is_origin, is_destination, is_active
                              ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                
                $stmt = $conn->prepare($insert_sql);
                $stmt->bind_param("ssssiisddiis", 
                    $location_code, $location_name, $city, $state, $country_id, $zone_id,
                    $postal_code, $latitude, $longitude, $is_origin, $is_destination, $is_active
                );
                
                if ($stmt->execute()) {
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                               VALUES (?, 'CREATE', 'locations', ?, ?)";
                    $stmt_log = $conn->prepare($log_sql);
                    $new_id = $conn->insert_id;
                    $log_details = json_encode(['location_code' => $location_code, 'location_name' => $location_name]);
                    $stmt_log->bind_param("iss", $user_id, $new_id, $log_details);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'Location created successfully', 'location_id' => $new_id]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to create location']);
                }
                break;
                
            case 'update':
                $location_id = intval($_POST['location_id']);
                $location_code = strtoupper(trim($_POST['location_code']));
                $location_name = trim($_POST['location_name']);
                $city = trim($_POST['city']);
                $state = trim($_POST['state']);
                $country_id = intval($_POST['country_id']);
                $zone_id = intval($_POST['zone_id']);
                $postal_code = trim($_POST['postal_code']);
                $latitude = !empty($_POST['latitude']) ? floatval($_POST['latitude']) : null;
                $longitude = !empty($_POST['longitude']) ? floatval($_POST['longitude']) : null;
                $is_origin = isset($_POST['is_origin']) ? 1 : 0;
                $is_destination = isset($_POST['is_destination']) ? 1 : 0;
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                // Check for duplicate location code (excluding current location)
                $check_sql = "SELECT location_id FROM locations WHERE location_code = ? AND location_id != ?";
                $stmt_check = $conn->prepare($check_sql);
                $stmt_check->bind_param("si", $location_code, $location_id);
                $stmt_check->execute();
                if ($stmt_check->get_result()->num_rows > 0) {
                    echo json_encode(['success' => false, 'message' => 'Location code already exists']);
                    exit();
                }
                
                $update_sql = "UPDATE locations SET 
                               location_code = ?, location_name = ?, city = ?, state = ?, 
                               country_id = ?, zone_id = ?, postal_code = ?, latitude = ?, 
                               longitude = ?, is_origin = ?, is_destination = ?, is_active = ?
                               WHERE location_id = ?";
                
                $stmt = $conn->prepare($update_sql);
                $stmt->bind_param("ssssiisddiiii", 
                    $location_code, $location_name, $city, $state, $country_id, $zone_id,
                    $postal_code, $latitude, $longitude, $is_origin, $is_destination, $is_active, $location_id
                );
                
                if ($stmt->execute()) {
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                               VALUES (?, 'UPDATE', 'locations', ?, ?)";
                    $stmt_log = $conn->prepare($log_sql);
                    $log_details = json_encode(['location_code' => $location_code, 'location_name' => $location_name]);
                    $stmt_log->bind_param("iss", $user_id, $location_id, $log_details);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'Location updated successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to update location']);
                }
                break;
                
            case 'delete':
                $location_id = intval($_POST['location_id']);
                
                // Check if location is being used
                $check_shipments = "SELECT COUNT(*) as count FROM shipments 
                                   WHERE origin_location_id = ? OR destination_location_id = ?";
                $stmt_check = $conn->prepare($check_shipments);
                $stmt_check->bind_param("ii", $location_id, $location_id);
                $stmt_check->execute();
                $usage = $stmt_check->get_result()->fetch_assoc();
                
                if ($usage['count'] > 0) {
                    echo json_encode(['success' => false, 'message' => 'Cannot delete location. It is being used in ' . $usage['count'] . ' shipment(s)']);
                    exit();
                }
                
                $delete_sql = "DELETE FROM locations WHERE location_id = ?";
                $stmt = $conn->prepare($delete_sql);
                $stmt->bind_param("i", $location_id);
                
                if ($stmt->execute()) {
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values) 
                               VALUES (?, 'DELETE', 'locations', ?, ?)";
                    $stmt_log = $conn->prepare($log_sql);
                    $log_details = json_encode(['location_id' => $location_id]);
                    $stmt_log->bind_param("iss", $user_id, $location_id, $log_details);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'Location deleted successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to delete location']);
                }
                break;
                
            case 'toggle_status':
                $location_id = intval($_POST['location_id']);
                $is_active = intval($_POST['is_active']);
                
                $update_sql = "UPDATE locations SET is_active = ? WHERE location_id = ?";
                $stmt = $conn->prepare($update_sql);
                $stmt->bind_param("ii", $is_active, $location_id);
                
                if ($stmt->execute()) {
                    echo json_encode(['success' => true, 'message' => 'Location status updated']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to update status']);
                }
                break;
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
    exit();
}

// Fetch all locations with related data
$sql_locations = "SELECT l.*, c.country_name, c.currency_code, z.zone_name, z.zone_code,
                  (SELECT COUNT(*) FROM shipments WHERE origin_location_id = l.location_id) as origin_count,
                  (SELECT COUNT(*) FROM shipments WHERE destination_location_id = l.location_id) as destination_count
                  FROM locations l
                  LEFT JOIN countries c ON l.country_id = c.country_id
                  LEFT JOIN zones z ON l.zone_id = z.zone_id
                  ORDER BY l.is_active DESC, c.country_name, l.location_name";
$result_locations = $conn->query($sql_locations);

// Fetch countries for dropdown
$sql_countries = "SELECT country_id, country_name, country_code FROM countries WHERE is_active = 1 ORDER BY country_name";
$result_countries = $conn->query($sql_countries);

// Fetch zones for dropdown
$sql_zones = "SELECT zone_id, zone_name, zone_code FROM zones WHERE is_active = 1 ORDER BY zone_name";
$result_zones = $conn->query($sql_zones);

// Get statistics
$stats = [
    'total' => 0,
    'active' => 0,
    'origins' => 0,
    'destinations' => 0
];

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

?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Location 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>
        .location-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;
        }
        
        .location-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .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;
        }
        
        .status-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-active { background: #d1e7dd; color: #0a3622; }
        .status-inactive { background: #f8d7da; color: #58151c; }
        
        .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-view { background: #e3f2fd; color: #1976d2; }
        .btn-edit { background: #fff3e0; color: #ef6c00; }
        .btn-delete { background: #ffebee; color: #c62828; }
        
        .action-btn:hover {
            transform: scale(1.05);
        }
        
        .location-icon {
            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;
        }
        
        .create-location-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-location-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(40,167,69,0.4);
            color: white;
        }
        
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }
        
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #cbd5e1;
            transition: 0.4s;
            border-radius: 24px;
        }
        
        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: 0.4s;
            border-radius: 50%;
        }
        
        input:checked + .toggle-slider {
            background-color: #667eea;
        }
        
        input:checked + .toggle-slider:before {
            transform: translateX(26px);
        }
        
        @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-map-pin-line me-2"></i>Location 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="shipments.php">Operations</a></li>
                                        <li class="breadcrumb-item active">Locations</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                <div class="stat-value"><?php echo number_format($stats['total']); ?></div>
                                <div class="stat-label">Total Locations</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                <div class="stat-value"><?php echo number_format($stats['active']); ?></div>
                                <div class="stat-label">Active Locations</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                <div class="stat-value"><?php echo number_format($stats['origins']); ?></div>
                                <div class="stat-label">Origin Points</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                                <div class="stat-value"><?php echo number_format($stats['destinations']); ?></div>
                                <div class="stat-label">Destination Points</div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="row">
                        <div class="col-12">
                            <div class="location-card">
                                <div class="card-body">
                                    <button class="btn create-location-btn" onclick="showCreateLocationModal()">
                                        <i class="ri-add-line me-1"></i>Add New Location
                                    </button>
                                    <button class="btn btn-outline-success ms-2" onclick="exportLocations()">
                                        <i class="ri-download-line me-1"></i>Export
                                    </button>
                                    <button class="btn btn-outline-primary ms-2" onclick="importLocations()">
                                        <i class="ri-upload-line me-1"></i>Import
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Locations Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="location-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-map-pin-2-line me-2"></i>All Locations
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover" id="locationsTable">
                                            <thead>
                                                <tr>
                                                    <th>Code</th>
                                                    <th>Location</th>
                                                    <th>City/State</th>
                                                    <th>Country</th>
                                                    <th>Zone</th>
                                                    <th>Type</th>
                                                    <th>Usage</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($location = $result_locations->fetch_assoc()): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="location-icon me-2">
                                                                <?php echo strtoupper(substr($location['location_code'], 0, 2)); ?>
                                                            </div>
                                                            <strong><?php echo $location['location_code']; ?></strong>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="fw-bold"><?php echo $location['location_name']; ?></div>
                                                        <?php if ($location['postal_code']): ?>
                                                        <small class="text-muted">Postal: <?php echo $location['postal_code']; ?></small>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div><?php echo $location['city']; ?></div>
                                                        <?php if ($location['state']): ?>
                                                        <small class="text-muted"><?php echo $location['state']; ?></small>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-primary"><?php echo $location['country_name']; ?></span>
                                                        <small class="d-block text-muted"><?php echo $location['currency_code']; ?></small>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-info"><?php echo $location['zone_name']; ?></span>
                                                    </td>
                                                    <td>
                                                        <?php if ($location['is_origin']): ?>
                                                        <span class="badge bg-success mb-1">Origin</span><br>
                                                        <?php endif; ?>
                                                        <?php if ($location['is_destination']): ?>
                                                        <span class="badge bg-warning">Destination</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <small class="text-muted">
                                                            Out: <?php echo $location['origin_count']; ?><br>
                                                            In: <?php echo $location['destination_count']; ?>
                                                        </small>
                                                    </td>
                                                    <td>
                                                        <label class="toggle-switch">
                                                            <input type="checkbox" 
                                                                   <?php echo $location['is_active'] ? 'checked' : ''; ?>
                                                                   onchange="toggleLocationStatus(<?php echo $location['location_id']; ?>, this.checked ? 1 : 0)">
                                                            <span class="toggle-slider"></span>
                                                        </label>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group" role="group">
                                                            <button class="action-btn btn-view" 
                                                                    onclick="viewLocation(<?php echo $location['location_id']; ?>)"
                                                                    title="View Details">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-edit" 
                                                                    onclick='editLocation(<?php echo json_encode($location); ?>)'
                                                                    title="Edit Location">
                                                                <i class="ri-edit-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-delete" 
                                                                    onclick="deleteLocation(<?php echo $location['location_id']; ?>, '<?php echo addslashes($location['location_name']); ?>')"
                                                                    title="Delete Location">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <!-- Create/Edit Location Modal -->
    <div class="modal fade" id="locationModal" tabindex="-1" aria-labelledby="locationModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="locationModalLabel">
                        <i class="ri-map-pin-add-line me-2"></i><span id="modalTitle">Add New Location</span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="locationForm" method="POST">
                    <input type="hidden" name="action" id="formAction" value="create">
                    <input type="hidden" name="location_id" id="location_id">
                    
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label for="location_code" class="form-label">Location Code *</label>
                                <input type="text" class="form-control text-uppercase" id="location_code" name="location_code" 
                                       required maxlength="10" placeholder="e.g., NBO, MBA">
                                <div class="form-text">Unique 2-5 character code</div>
                            </div>
                            
                            <div class="col-md-8">
                                <label for="location_name" class="form-label">Location Name *</label>
                                <input type="text" class="form-control" id="location_name" name="location_name" 
                                       required maxlength="100" placeholder="e.g., Nairobi Main Hub">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="city" class="form-label">City *</label>
                                <input type="text" class="form-control" id="city" name="city" 
                                       required maxlength="100" placeholder="e.g., Nairobi">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="state" class="form-label">State/Province</label>
                                <input type="text" class="form-control" id="state" name="state" 
                                       maxlength="100" placeholder="Optional">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="country_id" class="form-label">Country *</label>
                                <select class="form-select" id="country_id" name="country_id" required>
                                    <option value="">Select Country</option>
                                    <?php 
                                    $result_countries->data_seek(0);
                                    while ($country = $result_countries->fetch_assoc()): 
                                    ?>
                                    <option value="<?php echo $country['country_id']; ?>">
                                        <?php echo $country['country_name']; ?> (<?php echo $country['country_code']; ?>)
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="zone_id" class="form-label">Zone *</label>
                                <select class="form-select" id="zone_id" name="zone_id" required>
                                    <option value="">Select Zone</option>
                                    <?php 
                                    $result_zones->data_seek(0);
                                    while ($zone = $result_zones->fetch_assoc()): 
                                    ?>
                                    <option value="<?php echo $zone['zone_id']; ?>">
                                        <?php echo $zone['zone_name']; ?> (<?php echo $zone['zone_code']; ?>)
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="postal_code" class="form-label">Postal Code</label>
                                <input type="text" class="form-control" id="postal_code" name="postal_code" 
                                       maxlength="20" placeholder="Optional">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="latitude" class="form-label">Latitude</label>
                                <input type="number" step="0.000001" class="form-control" id="latitude" name="latitude" 
                                       placeholder="e.g., -1.286389">
                                <div class="form-text">Decimal degrees format</div>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="longitude" class="form-label">Longitude</label>
                                <input type="number" step="0.000001" class="form-control" id="longitude" name="longitude" 
                                       placeholder="e.g., 36.817223">
                                <div class="form-text">Decimal degrees format</div>
                            </div>
                            
                            <div class="col-12">
                                <hr>
                                <h6>Location Settings</h6>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="is_origin" name="is_origin" value="1">
                                    <label class="form-check-label" for="is_origin">
                                        <i class="ri-send-plane-line me-1"></i>Can be Origin
                                    </label>
                                </div>
                                <div class="form-text">Allow shipments from this location</div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="is_destination" name="is_destination" value="1" checked>
                                    <label class="form-check-label" for="is_destination">
                                        <i class="ri-map-pin-user-line me-1"></i>Can be Destination
                                    </label>
                                </div>
                                <div class="form-text">Allow shipments to this location</div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="is_active" name="is_active" value="1" checked>
                                    <label class="form-check-label" for="is_active">
                                        <i class="ri-checkbox-circle-line me-1"></i>Active
                                    </label>
                                </div>
                                <div class="form-text">Location is active and available</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="submitBtnText">Create Location</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Location Modal -->
    <div class="modal fade" id="viewLocationModal" tabindex="-1" aria-labelledby="viewLocationModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewLocationModalLabel">
                        <i class="ri-map-pin-line me-2"></i>Location Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="viewLocationContent">
                    <!-- Content loaded via AJAX -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </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 DataTable
    $('#locationsTable').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[1, 'asc']],
        columnDefs: [
            { targets: [8], orderable: false }
        ]
    });
});

function showCreateLocationModal() {
    $('#locationForm')[0].reset();
    $('#formAction').val('create');
    $('#location_id').val('');
    $('#modalTitle').text('Add New Location');
    $('#submitBtnText').text('Create Location');
    $('#is_destination').prop('checked', true);
    $('#is_active').prop('checked', true);
    $('#locationModal').modal('show');
}

function editLocation(location) {
    $('#formAction').val('update');
    $('#location_id').val(location.location_id);
    $('#location_code').val(location.location_code);
    $('#location_name').val(location.location_name);
    $('#city').val(location.city);
    $('#state').val(location.state || '');
    $('#country_id').val(location.country_id);
    $('#zone_id').val(location.zone_id);
    $('#postal_code').val(location.postal_code || '');
    $('#latitude').val(location.latitude || '');
    $('#longitude').val(location.longitude || '');
    $('#is_origin').prop('checked', location.is_origin == 1);
    $('#is_destination').prop('checked', location.is_destination == 1);
    $('#is_active').prop('checked', location.is_active == 1);
    
    $('#modalTitle').text('Edit Location');
    $('#submitBtnText').text('Update Location');
    $('#locationModal').modal('show');
}

$('#locationForm').on('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const action = $('#formAction').val();
    
    // Show loading
    Swal.fire({
        title: action === 'create' ? 'Creating Location...' : 'Updating Location...',
        text: 'Please wait',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'locations.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 viewLocation(locationId) {
    Swal.fire({
        title: 'Loading...',
        text: 'Please wait',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'locations.php',
        method: 'GET',
        data: { view: locationId },
        success: function(data) {
            $('#viewLocationContent').html(data);
            $('#viewLocationModal').modal('show');
            Swal.close();
        },
        error: function() {
            Swal.fire({
                title: 'Error',
                text: 'Failed to load location details',
                icon: 'error'
            });
        }
    });
}

function deleteLocation(locationId, locationName) {
    Swal.fire({
        title: 'Delete Location',
        text: `Are you sure you want to delete "${locationName}"? 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: 'locations.php',
                method: 'POST',
                data: {
                    action: 'delete',
                    location_id: locationId
                },
                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 location',
                        icon: 'error'
                    });
                }
            });
        }
    });
}

function toggleLocationStatus(locationId, isActive) {
    $.ajax({
        url: 'locations.php',
        method: 'POST',
        data: {
            action: 'toggle_status',
            location_id: locationId,
            is_active: isActive
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    title: 'Success',
                    text: response.message,
                    icon: 'success',
                    timer: 1500,
                    showConfirmButton: false
                });
            } else {
                Swal.fire({
                    title: 'Error',
                    text: response.message,
                    icon: 'error'
                });
                location.reload();
            }
        },
        error: function() {
            Swal.fire({
                title: 'Error',
                text: 'Failed to update status',
                icon: 'error'
            });
            location.reload();
        }
    });
}

function exportLocations() {
    Swal.fire({
        title: 'Export Locations',
        html: `
            <div class="mb-3">
                <label class="form-label">Export Format:</label>
                <select class="form-select" id="exportFormat">
                    <option value="excel">Excel (.xlsx)</option>
                    <option value="csv">CSV</option>
                    <option value="pdf">PDF</option>
                </select>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Export',
        preConfirm: () => {
            return document.getElementById('exportFormat').value;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = `exports/locations_export.php?format=${result.value}`;
        }
    });
}

function importLocations() {
    Swal.fire({
        title: 'Import Locations',
        html: `
            <div class="mb-3">
                <label class="form-label">Upload File:</label>
                <input type="file" class="form-control" id="importFile" accept=".xlsx,.csv">
            </div>
            <div class="alert alert-info">
                <small>File should contain: location_code, location_name, city, country, zone</small>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Import',
        preConfirm: () => {
            const file = document.getElementById('importFile').files[0];
            if (!file) {
                Swal.showValidationMessage('Please select a file');
            }
            return file;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const formData = new FormData();
            formData.append('file', result.value);
            
            Swal.fire({
                title: 'Importing...',
                text: 'Please wait',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Simulate import
            setTimeout(() => {
                Swal.fire({
                    title: 'Import Complete',
                    text: 'Locations imported successfully',
                    icon: 'success'
                });
            }, 2000);
        }
    });
}

// Auto-uppercase location code
$('#location_code').on('input', function() {
    this.value = this.value.toUpperCase();
});
</script>

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