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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Fetch user details and role
$user_id = $_SESSION['user_id'];
$sql_user_details = "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_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Get dashboard statistics
$sql_stats = "SELECT 
                (SELECT COUNT(*) FROM customers WHERE status = 'ACTIVE') as active_customers,
                (SELECT COUNT(*) FROM customers WHERE status = 'INACTIVE') as inactive_customers,
                (SELECT COUNT(*) FROM customers WHERE status = 'SUSPENDED') as suspended_customers,
                (SELECT COUNT(*) FROM customers WHERE customer_type = 'CORPORATE') as corporate_customers,
                (SELECT COUNT(*) FROM customers WHERE customer_type = 'INDIVIDUAL') as individual_customers,
                (SELECT COUNT(*) FROM customers WHERE is_credit_customer = 1) as credit_customers,
                (SELECT SUM(credit_limit) FROM customers WHERE is_credit_customer = 1) as total_credit_limit,
                (SELECT COUNT(*) FROM customers WHERE DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)) as new_customers_month,
                (SELECT COUNT(DISTINCT sender_customer_id) FROM shipments WHERE DATE(booking_date) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)) as active_shippers_month";

$result_stats = $conn->query($sql_stats);
$stats = $result_stats->fetch_assoc();

// Calculate totals
$total_customers = $stats['active_customers'] + $stats['inactive_customers'] + $stats['suspended_customers'];

// Get countries for filter dropdown
$sql_countries = "SELECT DISTINCT country FROM customers WHERE status != 'SUSPENDED' ORDER BY country";
$result_countries = $conn->query($sql_countries);

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Customer Management - Freight System')); ?>
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.7.0/css/select.bootstrap5.min.css">
    
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    
    <!-- Select2 -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet">
    
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        /* Modern Freight Management Design */
        .page-content {
            padding: 1.5rem;
            background-color: #f8fafc;
        }
        
        /* Header Section */
        .customers-header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            border-radius: 16px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 8px 32px rgba(30, 64, 175, 0.2);
            position: relative;
            overflow: hidden;
        }
        
        .customers-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -20%;
            width: 100%;
            height: 200%;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="25" cy="75" r="0.5" fill="rgba(255,255,255,0.05)"/><circle cx="75" cy="25" r="0.5" fill="rgba(255,255,255,0.05)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
            opacity: 0.1;
            pointer-events: none;
        }
        
        .header-content {
            position: relative;
            z-index: 2;
        }
        
        .header-title {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .header-subtitle {
            font-size: 1.1rem;
            opacity: 0.9;
            margin-bottom: 1.5rem;
        }
        
        .header-actions {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
        }
        
        /* Statistics Cards */
        .stats-container {
            margin-bottom: 2rem;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 1.5rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            border: 1px solid rgba(226, 232, 240, 0.8);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: linear-gradient(90deg, var(--card-color, #3b82f6), var(--card-color-light, #60a5fa));
        }
        
        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
        }
        
        .stat-card.primary { --card-color: #3b82f6; --card-color-light: #60a5fa; }
        .stat-card.success { --card-color: #059669; --card-color-light: #10b981; }
        .stat-card.warning { --card-color: #d97706; --card-color-light: #f59e0b; }
        .stat-card.danger { --card-color: #dc2626; --card-color-light: #ef4444; }
        .stat-card.info { --card-color: #0891b2; --card-color-light: #06b6d4; }
        .stat-card.purple { --card-color: #7c3aed; --card-color-light: #8b5cf6; }
        
        .stat-header {
            display: flex;
            justify-content: between;
            align-items: flex-start;
            margin-bottom: 1rem;
        }
        
        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: white;
            background: var(--card-color, #3b82f6);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        .stat-content {
            flex: 1;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 800;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .stat-label {
            font-size: 0.9rem;
            color: #64748b;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.025em;
        }
        
        .stat-trend {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-top: 0.75rem;
            font-size: 0.85rem;
            font-weight: 500;
        }
        
        .stat-trend.positive { color: #059669; }
        .stat-trend.negative { color: #dc2626; }
        .stat-trend.neutral { color: #64748b; }
        
        /* Filter Section */
        .filter-section {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            border: 1px solid rgba(226, 232, 240, 0.8);
        }
        
        .filter-header {
            display: flex;
            justify-content: between;
            align-items: center;
            margin-bottom: 1.5rem;
        }
        
        .filter-title {
            font-size: 1.125rem;
            font-weight: 700;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .filter-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            align-items: end;
        }
        
        .filter-actions {
            display: flex;
            gap: 0.5rem;
        }
        
        /* Table Section */
        .table-section {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            border: 1px solid rgba(226, 232, 240, 0.8);
            overflow: hidden;
        }
        
        .table-header {
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .table-title {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1e293b;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .table-subtitle {
            color: #64748b;
            margin-top: 0.25rem;
            font-size: 0.9rem;
        }
        
        .table-actions {
            display: flex;
            gap: 0.75rem;
            align-items: center;
            margin-top: 1rem;
        }
        
        /* Button Styles */
        .btn {
            padding: 0.625rem 1.25rem;
            border-radius: 10px;
            border: none;
            font-weight: 600;
            font-size: 0.875rem;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            text-decoration: none;
            position: relative;
            overflow: hidden;
        }
        
        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            transition: left 0.5s ease;
        }
        
        .btn:hover::before {
            left: 100%;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(59, 130, 246, 0.4);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(16, 185, 129, 0.4);
        }
        
        .btn-outline-primary {
            background: transparent;
            color: #1e40af;
            border: 2px solid #1e40af;
        }
        
        .btn-outline-primary:hover {
            background: #1e40af;
            color: white;
            transform: translateY(-2px);
        }
        
        .btn-sm {
            padding: 0.5rem 1rem;
            font-size: 0.8rem;
        }
        
        .btn-xs {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
        }
        
        /* Form Controls */
        .form-control,
        .form-select {
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            padding: 0.625rem 1rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
            background: white;
        }
        
        .form-control:focus,
        .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
            font-size: 0.875rem;
        }
        
        /* DataTables Customization */
        .dataTables_wrapper {
            padding: 1.5rem;
        }
        
        .dataTables_filter input {
            border: 2px solid #e2e8f0 !important;
            border-radius: 10px !important;
            padding: 0.5rem 1rem !important;
            margin-left: 0.5rem !important;
        }
        
        .dataTables_filter input:focus {
            border-color: #3b82f6 !important;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1) !important;
        }
        
        .dataTables_length select {
            border: 2px solid #e2e8f0 !important;
            border-radius: 8px !important;
            padding: 0.25rem 0.5rem !important;
            margin: 0 0.5rem !important;
        }
        
        .table {
            font-size: 0.875rem;
            border-collapse: separate;
            border-spacing: 0;
        }
        
        .table thead th {
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            border: none;
            border-bottom: 2px solid #e2e8f0;
            font-weight: 700;
            color: #374151;
            padding: 1rem 0.75rem;
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.025em;
        }
        
        .table thead th:first-child {
            border-top-left-radius: 12px;
        }
        
        .table thead th:last-child {
            border-top-right-radius: 12px;
        }
        
        .table tbody td {
            padding: 1rem 0.75rem;
            vertical-align: middle;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .table tbody tr {
            transition: all 0.2s ease;
        }
        
        .table tbody tr:hover {
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            transform: scale(1.002);
        }
        
        /* Customer Avatar */
        .customer-avatar {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 1rem;
            color: white;
            margin-right: 0.75rem;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        .avatar-corporate {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        }
        
        .avatar-individual {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
        }
        
        /* Status Badges */
        .status-badge {
            padding: 0.375rem 0.875rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.025em;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .status-active {
            background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
            color: #166534;
            border: 1px solid #86efac;
        }
        
        .status-inactive {
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
            color: #92400e;
            border: 1px solid #fcd34d;
        }
        
        .status-suspended {
            background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
            color: #991b1b;
            border: 1px solid #f87171;
        }
        
        .customer-type-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
            font-size: 0.7rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.025em;
        }
        
        .type-corporate {
            background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
            color: #1e40af;
            border: 1px solid #93c5fd;
        }
        
        .type-individual {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            color: #059669;
            border: 1px solid #86efac;
        }
        
        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 0.25rem;
        }
        
        .btn-action {
            width: 36px;
            height: 36px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .btn-action:hover {
            transform: scale(1.1);
        }
        
        .btn-info { background: linear-gradient(135deg, #0891b2 0%, #06b6d4 100%); color: white; }
        .btn-warning { background: linear-gradient(135deg, #d97706 0%, #f59e0b 100%); color: white; }
        .btn-danger { background: linear-gradient(135deg, #dc2626 0%, #ef4444 100%); color: white; }
        
        /* Credit Info */
        .credit-info {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.8rem;
        }
        
        .credit-amount {
            font-weight: 700;
            color: #059669;
        }
        
        .credit-terms {
            color: #64748b;
        }
        
        /* Export Buttons */
        .dt-buttons {
            margin-bottom: 1rem;
        }
        
        .dt-button {
            background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%) !important;
            color: white !important;
            border: none !important;
            border-radius: 8px !important;
            padding: 0.5rem 1rem !important;
            margin-right: 0.5rem !important;
            font-size: 0.8rem !important;
            font-weight: 600 !important;
            transition: all 0.2s ease !important;
        }
        
        .dt-button:hover {
            transform: translateY(-2px) !important;
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3) !important;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .customers-header {
                padding: 1.5rem;
            }
            
            .header-title {
                font-size: 1.5rem;
                flex-direction: column;
                align-items: flex-start;
                gap: 0.5rem;
            }
            
            .header-actions {
                width: 100%;
                justify-content: center;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .filter-grid {
                grid-template-columns: 1fr;
            }
            
            .table-actions {
                flex-direction: column;
                align-items: stretch;
            }
        }
        
        /* Loading Animation */
        .loading-spinner {
            width: 20px;
            height: 20px;
            border: 2px solid #f3f4f6;
            border-top: 2px solid #3b82f6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Animations */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .animate-fade-in-up {
            animation: fadeInUp 0.5s ease-out;
        }
        
        /* Custom scrollbar for tables */
        .dataTables_scrollBody::-webkit-scrollbar {
            height: 8px;
        }
        
        .dataTables_scrollBody::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 4px;
        }
        
        .dataTables_scrollBody::-webkit-scrollbar-thumb {
            background: #94a3b8;
            border-radius: 4px;
        }
        
        .dataTables_scrollBody::-webkit-scrollbar-thumb:hover {
            background: #64748b;
        }
    </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="customers-header animate-fade-in-up">
                        <div class="header-content">
                            <div class="d-flex justify-content-between align-items-start flex-wrap">
                                <div>
                                    <h1 class="header-title">
                                        <i class="bx bx-group"></i>
                                        Customer Management
                                    </h1>
                                    <p class="header-subtitle">
                                        Manage your freight customers, track shipment history, and maintain customer relationships
                                    </p>
                                </div>
                                <div class="header-actions">
                                    <a href="add_customer.php" class="btn btn-success">
                                        <i class="bx bx-plus"></i>
                                        Add New Customer
                                    </a>
                                    <button type="button" class="btn btn-outline-primary" onclick="bulkImportCustomers()">
                                        <i class="bx bx-upload"></i>
                                        Import Customers
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Statistics Dashboard -->
                    <div class="stats-container animate-fade-in-up">
                        <div class="stats-grid">
                            <div class="stat-card primary">
                                <div class="stat-header d-flex justify-content-between align-items-start">
                                    <div class="stat-content">
                                        <div class="stat-value"><?php echo number_format($total_customers); ?></div>
                                        <div class="stat-label">Total Customers</div>
                                        <div class="stat-trend neutral">
                                            <i class="bx bx-group"></i>
                                            All registered customers
                                        </div>
                                    </div>
                                    <div class="stat-icon">
                                        <i class="bx bx-group"></i>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="stat-card success">
                                <div class="stat-header d-flex justify-content-between align-items-start">
                                    <div class="stat-content">
                                        <div class="stat-value"><?php echo number_format($stats['active_customers']); ?></div>
                                        <div class="stat-label">Active Customers</div>
                                        <div class="stat-trend positive">
                                            <i class="bx bx-trending-up"></i>
                                            <?php echo $total_customers > 0 ? round(($stats['active_customers'] / $total_customers) * 100, 1) : 0; ?>% of total
                                        </div>
                                    </div>
                                    <div class="stat-icon">
                                        <i class="bx bx-check-circle"></i>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="stat-card info">
                                <div class="stat-header d-flex justify-content-between align-items-start">
                                    <div class="stat-content">
                                        <div class="stat-value"><?php echo number_format($stats['corporate_customers']); ?></div>
                                        <div class="stat-label">Corporate Clients</div>
                                        <div class="stat-trend neutral">
                                            <i class="bx bx-buildings"></i>
                                            Business accounts
                                        </div>
                                    </div>
                                    <div class="stat-icon">
                                        <i class="bx bx-buildings"></i>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="stat-card warning">
                                <div class="stat-header d-flex justify-content-between align-items-start">
                                    <div class="stat-content">
                                        <div class="stat-value"><?php echo number_format($stats['credit_customers']); ?></div>
                                        <div class="stat-label">Credit Customers</div>
                                        <div class="stat-trend neutral">
                                            <i class="bx bx-credit-card"></i>
                                            KES <?php echo number_format($stats['total_credit_limit'] ?? 0); ?> limit
                                        </div>
                                    </div>
                                    <div class="stat-icon">
                                        <i class="bx bx-credit-card"></i>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="stat-card purple">
                                <div class="stat-header d-flex justify-content-between align-items-start">
                                    <div class="stat-content">
                                        <div class="stat-value"><?php echo number_format($stats['new_customers_month']); ?></div>
                                        <div class="stat-label">New This Month</div>
                                        <div class="stat-trend <?php echo $stats['new_customers_month'] > 0 ? 'positive' : 'neutral'; ?>">
                                            <i class="bx bx-calendar-plus"></i>
                                            Recent additions
                                        </div>
                                    </div>
                                    <div class="stat-icon">
                                        <i class="bx bx-user-plus"></i>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="stat-card danger">
                                <div class="stat-header d-flex justify-content-between align-items-start">
                                    <div class="stat-content">
                                        <div class="stat-value"><?php echo number_format($stats['active_shippers_month']); ?></div>
                                        <div class="stat-label">Active Shippers</div>
                                        <div class="stat-trend <?php echo $stats['active_shippers_month'] > 0 ? 'positive' : 'neutral'; ?>">
                                            <i class="bx bx-package"></i>
                                            Shipped this month
                                        </div>
                                    </div>
                                    <div class="stat-icon">
                                        <i class="bx bx-package"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Advanced Filters -->
                    <div class="filter-section animate-fade-in-up">
                        <div class="filter-header">
                            <h3 class="filter-title">
                                <i class="bx bx-filter-alt"></i>
                                Advanced Filters
                            </h3>
                            <div class="filter-actions">
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="resetFilters()">
                                    <i class="bx bx-refresh"></i>
                                    Reset
                                </button>
                                <button type="button" class="btn btn-primary btn-sm" onclick="applyFilters()">
                                    <i class="bx bx-search"></i>
                                    Apply Filters
                                </button>
                            </div>
                        </div>
                        
                        <div class="filter-grid">
                            <div class="form-group">
                                <label class="form-label">Customer Type</label>
                                <select class="form-select" id="filterCustomerType">
                                    <option value="">All Types</option>
                                    <option value="CORPORATE">Corporate</option>
                                    <option value="INDIVIDUAL">Individual</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Status</label>
                                <select class="form-select" id="filterStatus">
                                    <option value="">All Status</option>
                                    <option value="ACTIVE">Active</option>
                                    <option value="INACTIVE">Inactive</option>
                                    <option value="SUSPENDED">Suspended</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Credit Customer</label>
                                <select class="form-select" id="filterCredit">
                                    <option value="">All Customers</option>
                                    <option value="1">Credit Customers Only</option>
                                    <option value="0">Cash Customers Only</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Country</label>
                                <select class="form-select" id="filterCountry">
                                    <option value="">All Countries</option>
                                    <?php while($country = $result_countries->fetch_assoc()): ?>
                                        <option value="<?php echo htmlspecialchars($country['country']); ?>">
                                            <?php echo htmlspecialchars($country['country']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Registration Period</label>
                                <select class="form-select" id="filterPeriod">
                                    <option value="">All Time</option>
                                    <option value="today">Today</option>
                                    <option value="week">This Week</option>
                                    <option value="month">This Month</option>
                                    <option value="quarter">This Quarter</option>
                                    <option value="year">This Year</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Customer Data Table -->
                    <div class="table-section animate-fade-in-up">
                        <div class="table-header">
                            <div class="d-flex justify-content-between align-items-start flex-wrap">
                                <div>
                                    <h3 class="table-title">
                                        <i class="bx bx-table"></i>
                                        Customer Directory
                                    </h3>
                                    <p class="table-subtitle">
                                        Complete list of all registered customers with their shipping history and account details
                                    </p>
                                </div>
                            </div>
                            
                            <div class="table-actions">
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="refreshTable()">
                                    <i class="bx bx-refresh"></i>
                                    Refresh
                                </button>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="bulkActions()">
                                    <i class="bx bx-check-square"></i>
                                    Bulk Actions
                                </button>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="exportData()">
                                    <i class="bx bx-download"></i>
                                    Export Data
                                </button>
                                <button type="button" class="btn btn-primary btn-sm" onclick="showQuickStats()">
                                    <i class="bx bx-pie-chart-alt"></i>
                                    Quick Stats
                                </button>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table id="customersTable" class="table table-hover" style="width:100%">
                                <thead>
                                    <tr>
                                        <th width="5%">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="selectAll">
                                            </div>
                                        </th>
                                        <th width="20%">Customer</th>
                                        <th width="10%">Code</th>
                                        <th width="10%">Type</th>
                                        <th width="15%">Contact</th>
                                        <th width="12%">Location</th>
                                        <th width="8%">Status</th>
                                        <th width="10%">Credit Info</th>
                                        <th width="10%">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Data loaded via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <!-- Bulk Action Modal -->
    <div class="modal fade" id="bulkActionModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Bulk Actions</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Select Action</label>
                        <select class="form-select" id="bulkActionType">
                            <option value="">Choose action...</option>
                            <option value="activate">Activate Selected</option>
                            <option value="deactivate">Deactivate Selected</option>
                            <option value="suspend">Suspend Selected</option>
                            <option value="export">Export Selected</option>
                            <option value="delete">Delete Selected</option>
                        </select>
                    </div>
                    <div class="alert alert-info">
                        <i class="bx bx-info-circle"></i>
                        <span id="selectedCount">0</span> customers selected
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="executeBulkAction()">Execute Action</button>
                </div>
            </div>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Required Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <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/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.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>
    <script src="https://cdn.datatables.net/select/1.7.0/js/dataTables.select.min.js"></script>
    <script src="https://cdn.datatables.net/select/1.7.0/js/select.bootstrap5.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    
    <!-- Select2 -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
    let customersTable;
    let selectedCustomers = [];
    
    $(document).ready(function() {
        // Initialize components
        initializeTable();
        initializeSelect2();
        setupEventHandlers();
        
        // Show welcome message on first visit
        showWelcomeMessage();
    });
    
    function initializeTable() {
        customersTable = $('#customersTable').DataTable({
            processing: true,
            serverSide: true,
            responsive: true,
            select: {
                style: 'multi',
                selector: 'td:first-child input[type="checkbox"]'
            },
            ajax: {
                url: 'ajax/customers_data_fresh.php',
                type: 'POST',
                data: function(d) {
                    d.customer_type = $('#filterCustomerType').val();
                    d.status = $('#filterStatus').val();
                    d.credit = $('#filterCredit').val();
                    d.country = $('#filterCountry').val();
                    d.period = $('#filterPeriod').val();
                },
                error: function(xhr, error, thrown) {
                    console.error('DataTables error:', error);
                    showErrorAlert('Failed to load customer data', 'Please refresh the page or contact support if the problem persists.');
                }
            },
            columns: [
                {
                    data: null,
                    orderable: false,
                    searchable: false,
                    className: 'text-center',
                    render: function(data, type, row, meta) {
                        return '<div class="form-check"><input class="form-check-input customer-checkbox" type="checkbox" value="' + row.customer_id + '" data-customer="' + encodeURIComponent(JSON.stringify(row)) + '"></div>';
                    }
                },
                {
                    data: null,
                    name: 'customer_name',
                    render: function(data, type, row) {
                        const avatarClass = row.customer_type === 'CORPORATE' ? 'avatar-corporate' : 'avatar-individual';
                        const initials = row.customer_type === 'CORPORATE' 
                            ? (row.company_name ? row.company_name.substring(0, 2).toUpperCase() : 'CO')
                            : (row.first_name && row.last_name ? row.first_name.charAt(0) + row.last_name.charAt(0) : 'CU');
                        
                        const displayName = row.customer_type === 'CORPORATE' 
                            ? (row.company_name || 'Corporate Customer')
                            : (row.first_name + ' ' + row.last_name);
                        
                        return `
                            <div class="d-flex align-items-center">
                                <div class="customer-avatar ${avatarClass}">${initials}</div>
                                <div>
                                    <div class="fw-bold">${displayName}</div>
                                    <small class="text-muted">ID: ${row.customer_id}</small>
                                </div>
                            </div>
                        `;
                    }
                },
                {
                    data: 'customer_code',
                    name: 'customer_code',
                    render: function(data, type, row) {
                        return `<span class="fw-bold text-primary">${data}</span>`;
                    }
                },
                {
                    data: 'customer_type',
                    name: 'customer_type',
                    render: function(data, type, row) {
                        const badgeClass = data === 'CORPORATE' ? 'type-corporate' : 'type-individual';
                        const icon = data === 'CORPORATE' ? 'bx-buildings' : 'bx-user';
                        return `
                            <span class="customer-type-badge ${badgeClass}">
                                <i class="bx ${icon}"></i>
                                ${data.toLowerCase()}
                            </span>
                        `;
                    }
                },
                {
                    data: null,
                    name: 'contact',
                    orderable: false,
                    render: function(data, type, row) {
                        return `
                            <div class="contact-info">
                                <div class="d-flex align-items-center mb-1">
                                    <i class="bx bx-phone me-1 text-muted"></i>
                                    <small>${row.phone}</small>
                                </div>
                                <div class="d-flex align-items-center">
                                    <i class="bx bx-envelope me-1 text-muted"></i>
                                    <small class="text-truncate" style="max-width: 120px;" title="${row.email}">${row.email}</small>
                                </div>
                            </div>
                        `;
                    }
                },
                {
                    data: null,
                    name: 'location',
                    orderable: false,
                    render: function(data, type, row) {
                        return `
                            <div>
                                <div class="fw-medium">${row.city}</div>
                                <small class="text-muted">${row.country}</small>
                            </div>
                        `;
                    }
                },
                {
                    data: 'status',
                    name: 'status',
                    render: function(data, type, row) {
                        const statusClass = 'status-' + data.toLowerCase();
                        let icon = 'bx-check-circle';
                        
                        if (data === 'INACTIVE') icon = 'bx-pause-circle';
                        else if (data === 'SUSPENDED') icon = 'bx-x-circle';
                        
                        return `
                            <span class="status-badge ${statusClass}">
                                <i class="bx ${icon}"></i>
                                ${data.toLowerCase()}
                            </span>
                        `;
                    }
                },
                {
                    data: null,
                    name: 'credit_info',
                    orderable: false,
                    render: function(data, type, row) {
                        if (row.is_credit_customer == 1) {
                            return `
                                <div class="credit-info">
                                    <div class="credit-amount">KES ${parseFloat(row.credit_limit).toLocaleString()}</div>
                                    <div class="credit-terms">${row.payment_terms} days</div>
                                </div>
                            `;
                        } else {
                            return `
                                <span class="text-muted">
                                    <i class="bx bx-money"></i> Cash
                                </span>
                            `;
                        }
                    }
                },
                {
                    data: null,
                    name: 'actions',
                    orderable: false,
                    searchable: false,
                    className: 'text-center',
                    render: function(data, type, row) {
                        return `
                            <div class="action-buttons">
                                <button type="button" class="btn btn-info btn-action" onclick="viewCustomer(${row.customer_id})" title="View Details">
                                    <i class="bx bx-show"></i>
                                </button>
                                <button type="button" class="btn btn-warning btn-action" onclick="editCustomer(${row.customer_id})" title="Edit Customer">
                                    <i class="bx bx-edit"></i>
                                </button>
                                <button type="button" class="btn btn-primary btn-action" onclick="newShipment(${row.customer_id})" title="New Shipment">
                                    <i class="bx bx-package"></i>
                                </button>
                            </div>
                        `;
                    }
                }
            ],
            order: [[2, 'asc']], // Sort by customer code
            pageLength: 25,
            lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                 '<"row"<"col-sm-12"B>>' +
                 '<"row"<"col-sm-12"tr>>' +
                 '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
            buttons: [
                {
                    extend: 'excel',
                    title: 'Customer Directory - ' + new Date().toLocaleDateString(),
                    className: 'dt-button btn-success',
                    text: '<i class="bx bx-file-excel"></i> Excel'
                },
                {
                    extend: 'pdf',
                    title: 'Customer Directory - ' + new Date().toLocaleDateString(),
                    className: 'dt-button btn-danger',
                    text: '<i class="bx bx-file-pdf"></i> PDF'
                },
                {
                    extend: 'print',
                    title: 'Customer Directory',
                    className: 'dt-button btn-info',
                    text: '<i class="bx bx-printer"></i> Print'
                }
            ],
            language: {
                processing: '<div class="d-flex justify-content-center align-items-center"><div class="loading-spinner me-2"></div> Loading customers...</div>',
                emptyTable: "No customers found in the system",
                zeroRecords: "No customers match your search criteria",
                search: "Search customers:",
                searchPlaceholder: "Search by name, email, phone, code...",
                lengthMenu: "Show _MENU_ customers per page",
                info: "Showing _START_ to _END_ of _TOTAL_ customers",
                infoEmpty: "No customers available",
                infoFiltered: "(filtered from _MAX_ total customers)",
                paginate: {
                    first: "First",
                    last: "Last",
                    next: "Next",
                    previous: "Previous"
                }
            },
            drawCallback: function(settings) {
                // Initialize tooltips
                $('[title]').tooltip();
                
                // Update selection count
                updateSelectionCount();
                
                // Animate new rows
                $('.animate-fade-in-up').removeClass('animate-fade-in-up');
                $('tbody tr').addClass('animate-fade-in-up');
            }
        });
    }
    
    function initializeSelect2() {
        $('#filterCountry').select2({
            theme: 'bootstrap-5',
            placeholder: 'Select country...',
            allowClear: true,
            width: '100%'
        });
    }
    
    function setupEventHandlers() {
        // Master checkbox handler
        $('#selectAll').on('change', function() {
            const isChecked = $(this).is(':checked');
            $('.customer-checkbox').prop('checked', isChecked);
            updateSelectionCount();
        });
        
        // Individual checkbox handler
        $(document).on('change', '.customer-checkbox', function() {
            updateSelectionCount();
            
            // Update master checkbox
            const totalCheckboxes = $('.customer-checkbox').length;
            const checkedCheckboxes = $('.customer-checkbox:checked').length;
            
            $('#selectAll').prop('indeterminate', checkedCheckboxes > 0 && checkedCheckboxes < totalCheckboxes);
            $('#selectAll').prop('checked', checkedCheckboxes === totalCheckboxes && totalCheckboxes > 0);
        });
        
        // Keyboard shortcuts
        $(document).keydown(function(e) {
            if ((e.ctrlKey || e.metaKey)) {
                switch(e.key) {
                    case 'n':
                        e.preventDefault();
                        window.location.href = 'add_customer.php';
                        break;
                    case 'f':
                        e.preventDefault();
                        $('.dataTables_filter input').focus();
                        break;
                    case 'r':
                        e.preventDefault();
                        refreshTable();
                        break;
                }
            }
        });
    }
    
    function updateSelectionCount() {
        const count = $('.customer-checkbox:checked').length;
        selectedCustomers = [];
        
        $('.customer-checkbox:checked').each(function() {
            const customerData = JSON.parse(decodeURIComponent($(this).data('customer')));
            selectedCustomers.push(customerData);
        });
        
        $('#selectedCount').text(count);
        
        // Enable/disable bulk action button
        $('button[onclick="bulkActions()"]').prop('disabled', count === 0);
    }
    
    function applyFilters() {
        customersTable.ajax.reload();
        
        Swal.fire({
            title: 'Filters Applied!',
            text: 'Customer list has been updated with your filter selections.',
            icon: 'success',
            timer: 2000,
            timerProgressBar: true,
            showConfirmButton: false
        });
    }
    
    function resetFilters() {
        $('#filterCustomerType').val('');
        $('#filterStatus').val('');
        $('#filterCredit').val('');
        $('#filterCountry').val(null).trigger('change');
        $('#filterPeriod').val('');
        
        customersTable.ajax.reload();
        
        Swal.fire({
            title: 'Filters Reset!',
            text: 'All filters have been cleared. Showing all customers.',
            icon: 'info',
            timer: 2000,
            timerProgressBar: true,
            showConfirmButton: false
        });
    }
    
    function refreshTable() {
        customersTable.ajax.reload(null, false);
        
        Swal.fire({
            title: 'Data Refreshed!',
            text: 'Customer data has been updated.',
            icon: 'success',
            timer: 1500,
            timerProgressBar: true,
            showConfirmButton: false
        });
    }
    
    function viewCustomer(customerId) {
        // Add loading state
        Swal.fire({
            title: 'Loading Customer Profile...',
            text: 'Please wait while we fetch the customer details.',
            allowOutsideClick: false,
            allowEscapeKey: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        // Simulate loading time for better UX
        setTimeout(() => {
            window.location.href = `view_customer.php?id=${customerId}`;
        }, 800);
    }
    
    function editCustomer(customerId) {
        window.location.href = `edit_customer.php?id=${customerId}`;
    }
    
    function newShipment(customerId) {
        Swal.fire({
            title: 'Create New Shipment',
            text: 'Redirecting to shipment creation with customer pre-selected...',
            icon: 'info',
            timer: 1500,
            timerProgressBar: true,
            showConfirmButton: false,
            didClose: () => {
                window.location.href = `create_shipment.php?customer_id=${customerId}`;
            }
        });
    }
    
    function bulkActions() {
        if (selectedCustomers.length === 0) {
            showErrorAlert('No Selection', 'Please select customers to perform bulk actions.');
            return;
        }
        
        $('#bulkActionModal').modal('show');
    }
    
    function executeBulkAction() {
        const action = $('#bulkActionType').val();
        
        if (!action) {
            showErrorAlert('No Action Selected', 'Please select an action to perform.');
            return;
        }
        
        if (selectedCustomers.length === 0) {
            showErrorAlert('No Selection', 'Please select customers first.');
            return;
        }
        
        const customerIds = selectedCustomers.map(c => c.customer_id);
        
        Swal.fire({
            title: `Confirm Bulk ${action.charAt(0).toUpperCase() + action.slice(1)}`,
            text: `This action will affect ${selectedCustomers.length} selected customers. Continue?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3b82f6',
            cancelButtonColor: '#6b7280',
            confirmButtonText: 'Yes, proceed',
            cancelButtonText: 'Cancel',
            showLoaderOnConfirm: true,
            preConfirm: () => {
                return fetch('ajax/bulk_customer_actions.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: action,
                        customer_ids: customerIds
                    })
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.message || 'Action failed');
                    }
                    return data;
                })
                .catch(error => {
                    Swal.showValidationMessage(`Request failed: ${error.message}`);
                });
            },
            allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {
            if (result.isConfirmed) {
                $('#bulkActionModal').modal('hide');
                
                Swal.fire({
                    title: 'Success!',
                    text: `Bulk ${action} completed successfully.`,
                    icon: 'success',
                    confirmButtonColor: '#3b82f6'
                });
                
                // Refresh table and clear selections
                customersTable.ajax.reload();
                $('#selectAll').prop('checked', false);
                selectedCustomers = [];
            }
        });
    }
    
    function exportData() {
        Swal.fire({
            title: 'Export Customer Data',
            text: 'Choose the format for your customer data export:',
            icon: 'question',
            showCancelButton: true,
            showDenyButton: true,
            confirmButtonText: '<i class="bx bx-file-pdf"></i> PDF Report',
            denyButtonText: '<i class="bx bx-file-excel"></i> Excel Spreadsheet',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#dc2626',
            denyButtonColor: '#059669',
            cancelButtonColor: '#6b7280'
        }).then((result) => {
            if (result.isConfirmed) {
                customersTable.button('.buttons-pdf').trigger();
            } else if (result.isDenied) {
                customersTable.button('.buttons-excel').trigger();
            }
        });
    }
    
    function showQuickStats() {
        // This would show a modal with quick customer statistics
        Swal.fire({
            title: 'Quick Customer Statistics',
            html: `
                <div class="row text-center">
                    <div class="col-4">
                        <h3 class="text-primary"><?php echo $stats['active_customers']; ?></h3>
                        <small>Active</small>
                    </div>
                    <div class="col-4">
                        <h3 class="text-success"><?php echo $stats['corporate_customers']; ?></h3>
                        <small>Corporate</small>
                    </div>
                    <div class="col-4">
                        <h3 class="text-warning"><?php echo $stats['credit_customers']; ?></h3>
                        <small>Credit</small>
                    </div>
                </div>
                <hr>
                <div class="row text-center mt-3">
                    <div class="col-6">
                        <h4 class="text-info">KES <?php echo number_format($stats['total_credit_limit'] ?? 0); ?></h4>
                        <small>Total Credit Limit</small>
                    </div>
                    <div class="col-6">
                        <h4 class="text-purple"><?php echo $stats['new_customers_month']; ?></h4>
                        <small>New This Month</small>
                    </div>
                </div>
            `,
            confirmButtonColor: '#3b82f6',
            confirmButtonText: 'Close'
        });
    }
    
    function bulkImportCustomers() {
        Swal.fire({
            title: 'Import Customers',
            text: 'Choose how you would like to import customer data:',
            icon: 'question',
            showCancelButton: true,
            showDenyButton: true,
            confirmButtonText: '<i class="bx bx-file-csv"></i> CSV File',
            denyButtonText: '<i class="bx bx-file-excel"></i> Excel File',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#059669',
            denyButtonColor: '#0891b2',
            cancelButtonColor: '#6b7280'
        }).then((result) => {
            if (result.isConfirmed || result.isDenied) {
                const fileType = result.isConfirmed ? 'csv' : 'excel';
                window.location.href = `import_customers.php?type=${fileType}`;
            }
        });
    }
    
    function showWelcomeMessage() {
        if (localStorage.getItem('customersPageVisited') !== 'true') {
            setTimeout(() => {
                Swal.fire({
                    title: 'Welcome to Customer Management!',
                    html: `
                        <p>Here you can manage all your freight customers efficiently:</p>
                        <ul class="text-start mt-3">
                            <li><strong>View</strong> comprehensive customer profiles</li>
                            <li><strong>Track</strong> shipping history and performance</li>
                            <li><strong>Manage</strong> credit limits and payment terms</li>
                            <li><strong>Filter</strong> and search customers easily</li>
                            <li><strong>Export</strong> data for reporting</li>
                        </ul>
                        <div class="mt-3">
                            <kbd>Ctrl+N</kbd> New Customer &nbsp;
                            <kbd>Ctrl+F</kbd> Search &nbsp;
                            <kbd>Ctrl+R</kbd> Refresh
                        </div>
                    `,
                    icon: 'info',
                    confirmButtonColor: '#3b82f6',
                    confirmButtonText: 'Got it!',
                    allowOutsideClick: false
                });
                
                localStorage.setItem('customersPageVisited', 'true');
            }, 1000);
        }
    }
    
    function showErrorAlert(title, message) {
        Swal.fire({
            title: title,
            text: message,
            icon: 'error',
            confirmButtonColor: '#dc2626',
            confirmButtonText: 'OK'
        });
    }
    
    // Auto-refresh functionality (every 5 minutes)
    setInterval(function() {
        if (document.visibilityState === 'visible') {
            // Quietly refresh statistics
            fetch('ajax/customer_statistics.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Update stat cards with new data
                        updateStatCards(data.stats);
                    }
                })
                .catch(error => console.log('Auto-refresh failed:', error));
        }
    }, 300000); // 5 minutes
    
    function updateStatCards(stats) {
        // Update statistics cards with fresh data
        const statValues = document.querySelectorAll('.stat-value');
        if (statValues.length >= 6) {
            statValues[0].textContent = stats.total_customers.toLocaleString();
            statValues[1].textContent = stats.active_customers.toLocaleString();
            statValues[2].textContent = stats.corporate_customers.toLocaleString();
            statValues[3].textContent = stats.credit_customers.toLocaleString();
            statValues[4].textContent = stats.new_customers_month.toLocaleString();
            statValues[5].textContent = stats.active_shippers_month.toLocaleString();
        }
    }
    
    // Page visibility change handler
    document.addEventListener('visibilitychange', function() {
        if (document.visibilityState === 'visible') {
            // Refresh data when page becomes visible again
            customersTable.ajax.reload(null, false);
        }
    });
    
    // Initialize tooltips for better UX
    $(function() {
        $('[data-bs-toggle="tooltip"]').tooltip();
    });
    
    // Add loading state to buttons
    function addLoadingState(button, originalText) {
        $(button).prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Loading...');
        
        return function() {
            $(button).prop('disabled', false).html(originalText);
        };
    }
    
    // Enhanced search functionality
    $('.dataTables_filter input').on('keyup', function() {
        if (this.value.length >= 3 || this.value.length === 0) {
            customersTable.search(this.value).draw();
        }
    });
    
    // Context menu for table rows (right-click actions)
    $(document).on('contextmenu', '#customersTable tbody tr', function(e) {
        e.preventDefault();
        
        const rowData = customersTable.row(this).data();
        if (!rowData) return;
        
        const contextMenu = `
            <div class="dropdown-menu show" style="position: fixed; top: ${e.pageY}px; left: ${e.pageX}px; z-index: 9999;">
                <a class="dropdown-item" href="javascript:viewCustomer(${rowData.customer_id})">
                    <i class="bx bx-show me-2"></i>View Details
                </a>
                <a class="dropdown-item" href="javascript:editCustomer(${rowData.customer_id})">
                    <i class="bx bx-edit me-2"></i>Edit Customer
                </a>
                <a class="dropdown-item" href="javascript:newShipment(${rowData.customer_id})">
                    <i class="bx bx-package me-2"></i>New Shipment
                </a>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item" href="reports/customer_report.php?id=${rowData.customer_id}" target="_blank">
                    <i class="bx bx-file-pdf me-2"></i>Generate Report
                </a>
            </div>
        `;
        
        // Remove existing context menu
        $('.dropdown-menu.show').remove();
        
        // Add new context menu
        $('body').append(contextMenu);
        
        // Remove context menu when clicking elsewhere
        $(document).one('click', function() {
            $('.dropdown-menu.show').remove();
        });
    });
    
    // Advanced keyboard shortcuts
    $(document).keydown(function(e) {
        if (e.altKey && e.key === 'a') {
            e.preventDefault();
            bulkActions();
        }
        
        if (e.altKey && e.key === 'e') {
            e.preventDefault();
            exportData();
        }
        
        if (e.key === 'Escape') {
            // Clear search
            $('.dataTables_filter input').val('').trigger('keyup');
            // Clear selections
            $('#selectAll').prop('checked', false).trigger('change');
        }
    });
    </script>
    
    <!-- App JS -->
    <script src="assets/js/app.js"></script>
</body>
</html>