<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$userId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Handle form submissions
if ($_POST) {
    $action = $_POST['action'];
    $customerName = mysqli_real_escape_string($con, $_POST['customerName']);
    $mobile = mysqli_real_escape_string($con, $_POST['mobile']);
    $alternativePhone = mysqli_real_escape_string($con, $_POST['alternativePhone']);
    $area = mysqli_real_escape_string($con, $_POST['area']);
    $address = mysqli_real_escape_string($con, $_POST['address']);
    $gmapLocation = mysqli_real_escape_string($con, $_POST['gmapLocation']);
    $customerType = mysqli_real_escape_string($con, $_POST['customerType']);
    $nearbyCustomer = !empty($_POST['nearbyCustomer']) ? (int)$_POST['nearbyCustomer'] : null;
    
    if ($action == 'create') {
        // Check if mobile number already exists
        $checkQuery = "SELECT ID FROM tblcustomers WHERE Mobile = '$mobile' AND IsActive = 1";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if (mysqli_num_rows($checkResult) > 0) {
            $error = "Mobile number already exists!";
        } else {
            $insertQuery = "INSERT INTO tblcustomers (CustomerName, Mobile, AlternativePhone, Area, Address, GmapLocation, CustomerType, NearbyCustomerId, CreatedBy) 
                           VALUES ('$customerName', '$mobile', '$alternativePhone', '$area', '$address', '$gmapLocation', '$customerType', " . ($nearbyCustomer ? $nearbyCustomer : 'NULL') . ", '$userId')";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "Customer added successfully!";
            } else {
                $error = "Error adding customer: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $customerId = (int)$_POST['customerId'];
        
        // Check if mobile number already exists for other customers
        $checkQuery = "SELECT ID FROM tblcustomers WHERE Mobile = '$mobile' AND ID != $customerId AND IsActive = 1";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if (mysqli_num_rows($checkResult) > 0) {
            $error = "Mobile number already exists for another customer!";
        } else {
            $updateQuery = "UPDATE tblcustomers SET 
                           CustomerName = '$customerName',
                           Mobile = '$mobile',
                           AlternativePhone = '$alternativePhone',
                           Area = '$area',
                           Address = '$address',
                           GmapLocation = '$gmapLocation',
                           CustomerType = '$customerType',
                           NearbyCustomerId = " . ($nearbyCustomer ? $nearbyCustomer : 'NULL') . ",
                           UpdatedBy = '$userId',
                           UpdatedDate = NOW()
                           WHERE ID = $customerId";
            
            if (mysqli_query($con, $updateQuery)) {
                $success = "Customer updated successfully!";
            } else {
                $error = "Error updating customer: " . mysqli_error($con);
            }
        }
    }
}

// Handle delete action
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $customerId = (int)$_GET['delete'];
    $deleteQuery = "UPDATE tblcustomers SET IsActive = 0, UpdatedBy = '$userId', UpdatedDate = NOW() WHERE ID = $customerId";
    
    if (mysqli_query($con, $deleteQuery)) {
        $success = "Customer deleted successfully!";
    } else {
        $error = "Error deleting customer: " . mysqli_error($con);
    }
}

// Get customer for editing
$editCustomer = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $customerId = (int)$_GET['edit'];
    $editQuery = "SELECT * FROM tblcustomers WHERE ID = $customerId AND IsActive = 1";
    $editResult = mysqli_query($con, $editQuery);
    $editCustomer = mysqli_fetch_assoc($editResult);
}

// Fetch all customers with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$recordsPerPage = 10;
$offset = ($page - 1) * $recordsPerPage;

$searchTerm = isset($_GET['search']) ? mysqli_real_escape_string($con, $_GET['search']) : '';
$filterType = isset($_GET['type']) ? mysqli_real_escape_string($con, $_GET['type']) : '';

$whereClause = "WHERE IsActive = 1";
if (!empty($searchTerm)) {
    $whereClause .= " AND (CustomerName LIKE '%$searchTerm%' OR Mobile LIKE '%$searchTerm%' OR AlternativePhone LIKE '%$searchTerm%' OR Area LIKE '%$searchTerm%')";
}
if (!empty($filterType)) {
    $whereClause .= " AND CustomerType = '$filterType'";
}

// Count total records
$countQuery = "SELECT COUNT(*) as total FROM tblcustomers $whereClause";
$countResult = mysqli_query($con, $countQuery);
$totalRecords = mysqli_fetch_assoc($countResult)['total'];
$totalPages = ceil($totalRecords / $recordsPerPage);

// Fetch customers
$customersQuery = "SELECT c.*, u.FullName as CreatedByName, u2.FullName as UpdatedByName 
                   FROM tblcustomers c 
                   LEFT JOIN tblusers u ON c.CreatedBy = u.ID 
                   LEFT JOIN tblusers u2 ON c.UpdatedBy = u2.ID 
                   $whereClause 
                   ORDER BY c.CreatedDate DESC 
                   LIMIT $offset, $recordsPerPage";
$customersResult = mysqli_query($con, $customersQuery);

// Get statistics
$statsQuery = "SELECT 
    COUNT(*) as TotalCustomers,
    COUNT(CASE WHEN CustomerType = 'Retail' THEN 1 END) as RetailCustomers,
    COUNT(CASE WHEN CustomerType = 'Shop' THEN 1 END) as ShopCustomers
    FROM tblcustomers WHERE IsActive = 1";
$statsResult = mysqli_query($con, $statsQuery);
$stats = mysqli_fetch_assoc($statsResult);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Customer Management | Mariyappa Nadar Ricemill</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
    <style>
        .customer-card {
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .customer-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
        }
        .customer-type-retail { border-left: 4px solid #1cc88a; }
        .customer-type-shop { border-left: 4px solid #36b9cc; }
        .gmap-link { color: #4e73df; text-decoration: none; }
        .gmap-link:hover { color: #2e59d9; text-decoration: underline; }
        .modal-header { background: linear-gradient(45deg, #4e73df, #36b9cc); color: white; }
        .required { color: red; }
        
        /* Compact design for mobile */
        .form-group { margin-bottom: 0.75rem; }
        .card-body { padding: 1rem; }
        .table td, .table th { padding: 0.5rem; }
        .btn { padding: 0.375rem 0.75rem; }
        .alert { padding: 0.5rem 1rem; margin-bottom: 0.75rem; }
        
        /* Compact Modern Modal Design */
        .modal-content {
            border: none;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }
        
        .modal-header {
            border-bottom: 1px solid #e3e6f0;
            padding: 1.25rem 1.5rem 1rem;
            border-radius: 12px 12px 0 0 !important;
        }
        
        .modal-body {
            padding: 1.5rem;
        }
        
        .modal-footer {
            border-top: 1px solid #e3e6f0;
            padding: 1rem 1.5rem;
            border-radius: 0 0 12px 12px;
        }
        
        /* Compact form styling */
        .compact-form .form-group {
            margin-bottom: 1rem;
        }
        
        .compact-form label {
            font-weight: 600;
            color: #495057;
            font-size: 0.875rem;
            margin-bottom: 0.375rem;
        }
        
        .compact-form .form-control {
            border-radius: 8px;
            border: 1.5px solid #e3e6f0;
            padding: 0.625rem 0.875rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .compact-form .form-control:focus {
            border-color: #4e73df;
            box-shadow: 0 0 0 3px rgba(78, 115, 223, 0.1);
            outline: none;
        }
        
        .compact-form .input-group-text {
            border-radius: 8px;
            border: 1.5px solid #e3e6f0;
            background-color: #f8f9fc;
            border-left: none;
            padding: 0.625rem 0.875rem;
        }
        
        .compact-form .input-group .form-control {
            border-right: none;
            border-radius: 8px 0 0 8px;
        }
        
        .compact-form .input-group-append .btn,
        .compact-form .input-group-append .input-group-text {
            border-radius: 0 8px 8px 0;
        }
        
        /* Modern button styling */
        .btn-modern {
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            padding: 0.625rem 1.25rem;
            border: none;
            transition: all 0.2s ease;
        }
        
        .btn-modern:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        /* Form section headers */
        .form-section-header {
            font-size: 0.9rem;
            font-weight: 700;
            color: #4e73df;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin: 1.5rem 0 0.75rem 0;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #f1f3f4;
            position: relative;
        }
        
        .form-section-header:first-child {
            margin-top: 0;
        }
        
        .form-section-header::before {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 40px;
            height: 2px;
            background-color: #4e73df;
        }
        
        /* Icon styling in forms */
        .form-icon {
            color: #858796;
            margin-right: 0.5rem;
        }
        
        /* Field descriptions */
        .field-description {
            font-size: 0.8rem;
            color: #6c757d;
            margin-top: 0.25rem;
            line-height: 1.3;
        }
        
        /* Required field indicator */
        .required-indicator {
            color: #e74a3b;
            font-weight: 600;
        }
        
        /* Compact select2 styling for modal */
        .modal .select2-container--default .select2-selection--single {
            height: 38px;
            border-radius: 8px;
            border: 1.5px solid #e3e6f0;
            font-size: 0.875rem;
        }
        
        .modal .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 34px;
            padding-left: 0.875rem;
        }
        
        .modal .select2-container--default .select2-selection--single:focus-within {
            border-color: #4e73df;
        }
        
        /* Responsive modal adjustments */
        @media (max-width: 768px) {
            .modal-dialog {
                margin: 0.5rem;
                max-width: calc(100vw - 1rem);
            }
            
            .modal-body {
                padding: 1rem;
                max-height: 70vh;
                overflow-y: auto;
            }
            
            .modal-header,
            .modal-footer {
                padding-left: 1rem;
                padding-right: 1rem;
            }
            
            .compact-form .form-control,
            .compact-form .form-control-plaintext {
                font-size: 16px; /* Prevents zoom on iOS */
            }
            
            .form-section-header {
                font-size: 0.85rem;
                margin: 1rem 0 0.5rem 0;
            }
            
            .compact-form .row {
                margin-left: -0.5rem;
                margin-right: -0.5rem;
            }
            
            .compact-form .row > [class*="col-"] {
                padding-left: 0.5rem;
                padding-right: 0.5rem;
            }
            
            .modal-footer {
                flex-direction: column;
                align-items: stretch;
            }
            
            .modal-footer .btn {
                margin: 0.25rem 0;
                order: 2;
            }
            
            .modal-footer .btn-primary {
                order: 1;
            }
        }
        
        @media (max-width: 480px) {
            .modal-dialog {
                margin: 0.25rem;
                max-width: calc(100vw - 0.5rem);
            }
            
            .modal-body {
                padding: 0.75rem;
                max-height: 75vh;
            }
            
            .modal-header {
                padding: 0.75rem;
            }
            
            .modal-footer {
                padding: 0.75rem;
            }
            
            .form-section-header {
                font-size: 0.8rem;
                margin: 0.75rem 0 0.5rem 0;
            }
            
            .compact-form label {
                font-size: 0.8rem;
            }
            
            .field-description {
                font-size: 0.75rem;
            }
            
            .input-group-text,
            .btn {
                font-size: 0.8rem;
            }
        }
        
        /* Customer Grid Layout */
        .customer-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .customer-grid-item {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            overflow: hidden;
            border: 1px solid #e3e6f0;
        }
        
        .customer-grid-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .customer-header {
            padding: 1rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            position: relative;
        }
        
        .customer-header.retail {
            background: linear-gradient(135deg, #1cc88a 0%, #17a673 100%);
        }
        
        .customer-header.shop {
            background: linear-gradient(135deg, #36b9cc 0%, #2c9faf 100%);
        }
        
        .customer-type-badge {
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            font-size: 0.7rem;
            padding: 0.25rem 0.5rem;
            background: rgba(255,255,255,0.2);
            border-radius: 12px;
        }
        
        .customer-name {
            font-size: 1.1rem;
            font-weight: 600;
            margin: 0;
            line-height: 1.2;
        }
        
        .customer-id {
            font-size: 0.8rem;
            opacity: 0.8;
            margin: 0.25rem 0 0 0;
        }
        
        .customer-body {
            padding: 1rem;
        }
        
        .customer-info {
            margin-bottom: 0.75rem;
        }
        
        .customer-info-item {
            display: flex;
            align-items: center;
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
        }
        
        .customer-info-item i {
            width: 16px;
            margin-right: 0.5rem;
            color: #5a5c69;
        }
        
        .customer-actions {
            border-top: 1px solid #e3e6f0;
            padding: 0.75rem 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .customer-date {
            font-size: 0.8rem;
            color: #858796;
        }
        
        .view-toggle {
            margin-bottom: 1rem;
        }
        
        @media (max-width: 768px) {
            .customer-grid {
                grid-template-columns: 1fr;
                gap: 0.75rem;
            }
            .customer-header, .customer-body, .customer-actions {
                padding: 0.75rem;
            }
            .customer-info-item {
                font-size: 0.85rem;
            }
            .form-group { margin-bottom: 0.5rem; }
            .modal-body { padding: 1rem; }
        }
        
        /* Loading states */
        .location-loading {
            pointer-events: none;
            opacity: 0.6;
        }
        
        .location-loading i {
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Location button enhancements */
        #getCurrentLocation {
            transition: all 0.3s ease;
        }
        
        #getCurrentLocation:hover {
            background-color: #4e73df;
            color: white;
            border-color: #4e73df;
        }
        
        #getCurrentLocation:disabled {
            cursor: not-allowed;
        }
        
        /* Permission modal styling */
        .modal-header.bg-warning {
            background: linear-gradient(45deg, #f6c23e, #f4b619) !important;
        }
        
        .alert-info {
            border-left: 4px solid #36b9cc;
        }
        
        .alert-secondary {
            border-left: 4px solid #858796;
        }
        
        /* Responsive location button text */
        @media (max-width: 576px) {
            #getCurrentLocation span {
                display: none !important;
            }
        }
        
        /* Statistics cards hover effect */
        .stats-card {
            transition: all 0.3s ease;
        }
        
        .stats-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 0.5rem 1.5rem rgba(0, 0, 0, 0.2) !important;
        }
        
        .stats-card:active {
            transform: translateY(-1px);
        }
        
        /* Select2 Custom Styling */
        .select2-container {
            width: 100% !important;
        }
        
        .select2-container--default .select2-selection--single {
            background-color: #fff;
            border: 1px solid #d1d3e2;
            border-radius: 0.35rem;
            height: calc(1.5em + 0.75rem + 2px);
            padding: 6px 12px;
            font-size: 0.875rem;
            line-height: 1.5;
            color: #6e707e;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }
        
        .select2-container--default .select2-selection--single:focus {
            border-color: #bac8f3;
            outline: 0;
            box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
        }
        
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            color: #6e707e;
            line-height: calc(1.5em + 0.75rem);
            padding-left: 0;
            padding-right: 20px;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: calc(1.5em + 0.75rem);
            position: absolute;
            top: 1px;
            right: 1px;
            width: 20px;
        }
        
        .select2-dropdown {
            border: 1px solid #d1d3e2;
            border-radius: 0.35rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
        }
        
        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: #4e73df;
            color: white;
        }
        
        .select2-container--default .select2-results__option--selected {
            background-color: #e3edff;
            color: #4e73df;
        }
        
        .select2-search--dropdown .select2-search__field {
            border: 1px solid #d1d3e2;
            border-radius: 0.35rem;
            padding: 0.375rem 0.75rem;
            font-size: 0.875rem;
        }
        
        .select2-search--dropdown .select2-search__field:focus {
            border-color: #bac8f3;
            outline: 0;
            box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
        }
        
        /* Loading state for Select2 */
        .select2-container--default .select2-results__option.loading-results {
            color: #858796;
            text-align: center;
            padding: 1rem;
        }
        
        /* Custom loading spinner */
        .select2-loading-spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #4e73df;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 8px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Responsive Select2 */
        @media (max-width: 576px) {
            .select2-container--default .select2-selection--single {
                font-size: 0.8rem;
                padding: 4px 8px;
            }
            
            .select2-dropdown {
                font-size: 0.8rem;
            }
        }

        /* Search Suggestions Styling (improved) */
        #searchSuggestions {
            max-height: 320px;
            overflow-y: auto;
            border-radius: 0.5rem;
            box-shadow: 0 10px 25px -5px rgba(0,0,0,0.15), 0 4px 8px -2px rgba(0,0,0,0.08);
            border: 1px solid #e3e6f0;
            background: #ffffff;
            z-index: 2000 !important; /* Above modals inner content */
        }
        .search-suggestions-card .card-body{max-height:320px;overflow-y:auto;}

        .search-suggestion-item {
            padding: 0.6rem 0.85rem;
            border-bottom: 1px solid #eef1f6;
            cursor: pointer;
            transition: background-color 0.15s ease, padding-left 0.15s ease;
            position: relative;
        }

        .search-suggestion-item:hover,
        .search-suggestion-item.active {
            background-color: #f1f5ff;
            padding-left: 1rem;
        }

        .search-suggestion-item:last-child {
            border-bottom: none;
        }

        .suggestion-main {
            font-weight: 600;
            color: #5a5c69;
            margin-bottom: 0.25rem;
        }

        .suggestion-details {
            font-size: 0.85rem;
            color: #858796;
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .suggestion-detail {
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        .suggestion-type-badge {
            font-size: 0.7rem;
            padding: 0.15rem 0.4rem;
            border-radius: 0.25rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .suggestion-type-retail {
            background-color: #d1ecf1;
            color: #0c5460;
        }

        .suggestion-type-shop {
            background-color: #d4edda;
            color: #155724;
        }

        .no-suggestions, .suggestions-loading-state {
            padding: 1rem;
            text-align: center;
            color: #6e707e;
            font-size: 0.85rem;
        }
        .suggestions-loading-state i{animation: spin 1s linear infinite;}

        .search-highlight {
            background-color: #ffe9b3;
            font-weight: 600;
            padding: 0.05rem 0.25rem;
            border-radius: 0.2rem;
        }

        /* Real-time search loading states */
        .search-loading {
            opacity: 0.6;
        }

        .search-input-focused {
            border-color: #4e73df !important;
            box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25) !important;
        }

        /* Search info alert styling */
        #searchInfo .alert {
            margin-bottom: 0;
        }

        /* Search input icon positioning */
        .search-input-container {
            position: relative;
        }

        .search-clear-btn {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #858796;
            cursor: pointer;
            z-index: 10;
            padding: 2px;
        }

        .search-clear-btn:hover {
            color: #5a5c69;
        }

        /* Mobile responsive suggestions */
        @media (max-width: 768px) {
            .suggestion-details {
                gap: 0.5rem;
            }
            
            .search-suggestion-item {
                padding: 0.5rem;
            }
            
            .suggestion-main {
                font-size: 0.9rem;
            }
            
            .suggestion-details {
                font-size: 0.8rem;
            }
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php');?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Page Heading -->
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">
                            <i class="fas fa-users text-primary mr-2"></i>
                            Customer Management
                        </h1>
                        <div>
                            <a href="import-customers.php" class="btn btn-success mr-2">
                                <i class="fas fa-file-import mr-2"></i>Import Customers
                            </a>
                            <button class="btn btn-primary" data-toggle="modal" data-target="#customerModal" onclick="clearForm()">
                                <i class="fas fa-plus mr-2"></i>Add New Customer
                            </button>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-4 col-md-6 mb-4">
                            <div class="card border-left-primary shadow h-100 py-2 stats-card" 
                                 onclick="showCustomerOutstanding()" style="cursor: pointer;" 
                                 title="Click to view customer outstanding amounts">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                                Total Customers</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['TotalCustomers']); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-users fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-4 col-md-6 mb-4">
                            <div class="card border-left-success shadow h-100 py-2 stats-card" 
                                 onclick="showCustomerOutstanding('Retail')" style="cursor: pointer;" 
                                 title="Click to view retail customer outstanding amounts">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                Retail Customers</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['RetailCustomers']); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-user fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-4 col-md-6 mb-4">
                            <div class="card border-left-info shadow h-100 py-2 stats-card" 
                                 onclick="showCustomerOutstanding('Shop')" style="cursor: pointer;" 
                                 title="Click to view shop customer outstanding amounts">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                                Shop Customers</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['ShopCustomers']); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-store fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Search and Filter -->
                    <div class="card shadow mb-3">
                        <div class="card-body py-2">
                            <form method="GET" class="row align-items-end" id="searchForm">
                                <div class="col-md-3 mb-2 position-relative">
                                    <label for="searchInput" class="sr-only">Search Customers</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control form-control-sm" name="search" id="searchInput" 
                                               placeholder="Type to search customers..." value="<?php echo htmlspecialchars($searchTerm); ?>"
                                               autocomplete="off" data-toggle="tooltip" 
                                               title="Search by name, mobile, area, or address">
                                        <div class="input-group-append" id="searchSpinner" style="display: none;">
                                            <span class="input-group-text">
                                                <i class="fas fa-spinner fa-spin text-primary"></i>
                                            </span>
                                        </div>
                                    </div>
                                    <!-- Search Suggestions Dropdown -->
                                    <div id="searchSuggestions" class="position-absolute w-100 mt-1" style="display:none;">
                                        <div class="card shadow-sm search-suggestions-card mb-0">
                                            <div class="card-header py-2 px-3 d-flex justify-content-between align-items-center" style="background:#f8f9fc;">
                                                <small class="text-muted mb-0"><i class="fas fa-search mr-1 text-primary"></i><span id="suggestionsTitle">Suggestions</span></small>
                                                <button type="button" class="close p-0" style="font-size:0.9rem;" onclick="hideSuggestions()">&times;</button>
                                            </div>
                                            <div class="card-body p-0" id="suggestionsList">
                                                <div class="suggestions-loading-state"><i class="fas fa-spinner mr-2"></i> Loading...</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-2 mb-2">
                                    <select class="form-control form-control-sm" name="type" id="filterType">
                                        <option value="">All Types</option>
                                        <option value="Retail" <?php echo $filterType == 'Retail' ? 'selected' : ''; ?>>Retail</option>
                                        <option value="Shop" <?php echo $filterType == 'Shop' ? 'selected' : ''; ?>>Shop</option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <div class="btn-group" role="group">
                                        <button type="submit" class="btn btn-primary btn-sm" id="searchBtn">
                                            <i class="fas fa-search mr-1"></i>Search
                                        </button>
                                        <button type="button" class="btn btn-secondary btn-sm" id="clearSearchBtn">
                                            <i class="fas fa-times mr-1"></i>Clear
                                        </button>
                                        <button type="button" class="btn btn-success btn-sm" onclick="exportCustomers()">
                                            <i class="fas fa-download mr-1"></i>Export
                                        </button>
                                    </div>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <div class="view-toggle">
                                        <div class="btn-group btn-group-sm" role="group">
                                            <button type="button" class="btn btn-outline-primary active" id="gridViewBtn" onclick="toggleView('grid')">
                                                <i class="fas fa-th-large"></i> Grid
                                            </button>
                                            <button type="button" class="btn btn-outline-primary" id="tableViewBtn" onclick="toggleView('table')">
                                                <i class="fas fa-list"></i> Table
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                            
                            <!-- Search Results Info -->
                            <div id="searchInfo" class="row mt-2" style="display: none;">
                                <div class="col-12">
                                    <div class="alert alert-info alert-dismissible fade show py-2">
                                        <i class="fas fa-info-circle mr-2"></i>
                                        <span id="searchInfoText"></span>
                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Customer Grid View -->
                    <div id="gridView" class="customer-grid">
                        <?php 
                        mysqli_data_seek($customersResult, 0);
                        $customerCount = 0;
                        while($customer = mysqli_fetch_assoc($customersResult)): 
                            $customerCount++;
                        ?>
                        <div class="customer-grid-item">
                            <div class="customer-header <?php echo strtolower($customer['CustomerType']); ?>">
                                <div class="customer-type-badge">
                                    <i class="fas <?php echo $customer['CustomerType'] == 'Retail' ? 'fa-user' : 'fa-store'; ?>"></i>
                                    <?php echo $customer['CustomerType']; ?>
                                </div>
                                <h6 class="customer-name"><?php echo htmlspecialchars($customer['CustomerName']); ?></h6>
                                <p class="customer-id">ID: <?php echo $customer['ID']; ?></p>
                            </div>
                            <div class="customer-body">
                                <div class="customer-info">
                                    <div class="customer-info-item">
                                        <i class="fas fa-phone"></i>
                                        <a href="tel:<?php echo $customer['Mobile']; ?>" class="text-primary">
                                            <?php echo $customer['Mobile']; ?>
                                        </a>
                                    </div>
                                    <?php if (!empty($customer['AlternativePhone'])): ?>
                                    <div class="customer-info-item">
                                        <i class="fas fa-phone-alt"></i>
                                        <a href="tel:<?php echo $customer['AlternativePhone']; ?>" class="text-secondary">
                                            <?php echo $customer['AlternativePhone']; ?> <small>(Alt)</small>
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                    <div class="customer-info-item">
                                        <i class="fas fa-map-marker-alt"></i>
                                        <span><?php echo htmlspecialchars($customer['Area']); ?></span>
                                    </div>
                                    <div class="customer-info-item">
                                        <i class="fas fa-home"></i>
                                        <span class="text-truncate" title="<?php echo htmlspecialchars($customer['Address']); ?>">
                                            <?php echo htmlspecialchars(substr($customer['Address'], 0, 40)) . (strlen($customer['Address']) > 40 ? '...' : ''); ?>
                                        </span>
                                    </div>
                                    <?php if (!empty($customer['GmapLocation'])): ?>
                                    <div class="customer-info-item">
                                        <i class="fas fa-globe"></i>
                                        <a href="<?php echo htmlspecialchars($customer['GmapLocation']); ?>" 
                                           target="_blank" class="gmap-link">
                                            View Location
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="customer-actions">
                                <div class="customer-date">
                                    <?php echo date('M j, Y', strtotime($customer['CreatedDate'])); ?>
                                </div>
                                <div class="btn-group btn-group-sm" role="group">
                                    <button class="btn btn-outline-info" 
                                            onclick="viewCustomer(<?php echo $customer['ID']; ?>)"
                                            title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <a href="customer-ledger.php?customer_id=<?php echo $customer['ID']; ?>" 
                                       class="btn btn-outline-success btn-sm"
                                       title="View Ledger">
                                        <i class="fas fa-file-invoice-dollar"></i>
                                    </a>
                                    <button class="btn btn-outline-primary" 
                                            onclick="editCustomer(<?php echo $customer['ID']; ?>)"
                                            title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-outline-danger" 
                                            onclick="deleteCustomer(<?php echo $customer['ID']; ?>, '<?php echo htmlspecialchars($customer['CustomerName']); ?>')"
                                            title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <?php endwhile; ?>
                        
                        <?php if ($customerCount === 0): ?>
                        <div class="col-12">
                            <div class="card shadow-sm">
                                <div class="card-body text-center py-5">
                                    <i class="fas fa-users fa-3x text-muted mb-3"></i>
                                    <h5 class="text-muted">No Customers Found</h5>
                                    <p class="text-muted mb-3">
                                        <?php if (!empty($searchTerm) || !empty($filterType)): ?>
                                            No customers match your search criteria. Try adjusting your search terms or filters.
                                        <?php else: ?>
                                            No customers have been added yet. Click "Add New Customer" to get started.
                                        <?php endif; ?>
                                    </p>
                                    <?php if (!empty($searchTerm) || !empty($filterType)): ?>
                                    <a href="customer-management.php" class="btn btn-outline-primary mr-2">
                                        <i class="fas fa-times mr-1"></i>Clear Filters
                                    </a>
                                    <?php endif; ?>
                                    <button class="btn btn-primary" data-toggle="modal" data-target="#customerModal" onclick="clearForm()">
                                        <i class="fas fa-plus mr-1"></i>Add New Customer
                                    </button>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Customers Table -->
                    <div class="card shadow mb-4" id="tableView" style="display: none;">
                        <div class="card-header py-2">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-list mr-2"></i>Customer List
                                <span class="text-muted">(<?php echo $totalRecords; ?> total)</span>
                            </h6>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped table-sm mb-0" width="100%" cellspacing="0">
                                    <thead class="thead-light">
                                        <tr>
                                            <th>#</th>
                                            <th>Customer Name</th>
                                            <th>Mobile</th>
                                            <th>Alt. Phone</th>
                                            <th>Area</th>
                                            <th>Type</th>
                                            <th>Location</th>
                                            <th>Created Date</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        mysqli_data_seek($customersResult, 0);
                                        $counter = $offset + 1;
                                        while($customer = mysqli_fetch_assoc($customersResult)): 
                                        ?>
                                        <tr>
                                            <td><?php echo $counter++; ?></td>
                                            <td>
                                                <strong><?php echo htmlspecialchars($customer['CustomerName']); ?></strong>
                                                <br><small class="text-muted">ID: <?php echo $customer['ID']; ?></small>
                                            </td>
                                            <td>
                                                <a href="tel:<?php echo $customer['Mobile']; ?>" class="text-primary">
                                                    <i class="fas fa-phone mr-1"></i><?php echo $customer['Mobile']; ?>
                                                </a>
                                            </td>
                                            <td>
                                                <?php if (!empty($customer['AlternativePhone'])): ?>
                                                    <a href="tel:<?php echo $customer['AlternativePhone']; ?>" class="text-secondary">
                                                        <i class="fas fa-phone-alt mr-1"></i><?php echo $customer['AlternativePhone']; ?>
                                                    </a>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($customer['Area']); ?></td>
                                            <td>
                                                <span class="badge badge-<?php echo $customer['CustomerType'] == 'Retail' ? 'success' : 'info'; ?> px-2 py-1">
                                                    <i class="fas <?php echo $customer['CustomerType'] == 'Retail' ? 'fa-user' : 'fa-store'; ?> mr-1"></i>
                                                    <?php echo $customer['CustomerType']; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if (!empty($customer['GmapLocation'])): ?>
                                                <a href="<?php echo htmlspecialchars($customer['GmapLocation']); ?>" 
                                                   target="_blank" class="gmap-link">
                                                    <i class="fas fa-map-marker-alt mr-1"></i>View Map
                                                </a>
                                                <?php else: ?>
                                                <span class="text-muted">No location</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <small><?php echo date('M j, Y', strtotime($customer['CreatedDate'])); ?></small>
                                                <br><small class="text-muted">by <?php echo htmlspecialchars($customer['CreatedByName']); ?></small>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm" role="group">
                                                    <button class="btn btn-outline-info" 
                                                            onclick="viewCustomer(<?php echo $customer['ID']; ?>)"
                                                            title="View Details">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                    <a href="customer-ledger.php?customer_id=<?php echo $customer['ID']; ?>" 
                                                       class="btn btn-outline-success btn-sm"
                                                       title="View Ledger">
                                                        <i class="fas fa-file-invoice-dollar"></i>
                                                    </a>
                                                    <button class="btn btn-outline-primary" 
                                                            onclick="editCustomer(<?php echo $customer['ID']; ?>)"
                                                            title="Edit">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button class="btn btn-outline-danger" 
                                                            onclick="deleteCustomer(<?php echo $customer['ID']; ?>, '<?php echo htmlspecialchars($customer['CustomerName']); ?>')"
                                                            title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                    <nav aria-label="Customer pagination">
                        <ul class="pagination justify-content-center pagination-sm">
                            <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($searchTerm); ?>&type=<?php echo urlencode($filterType); ?>">Previous</a>
                            </li>
                            <?php endif; ?>
                            
                            <?php for ($i = max(1, $page-2); $i <= min($totalPages, $page+2); $i++): ?>
                            <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($searchTerm); ?>&type=<?php echo urlencode($filterType); ?>"><?php echo $i; ?></a>
                            </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $totalPages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($searchTerm); ?>&type=<?php echo urlencode($filterType); ?>">Next</a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>

                </div>
                <!-- /.container-fluid -->
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>

    <!-- Customer Modal -->
    <div class="modal fade" id="customerModal" tabindex="-1" role="dialog" aria-labelledby="customerModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header" style="background:linear-gradient(120deg,#4e73df,#2c9faf);color:#fff;">
                    <div class="d-flex align-items-center">
                        <div class="rounded-circle bg-white d-flex align-items-center justify-content-center mr-2" style="width:34px;height:34px;">
                            <i class="fas fa-user-plus text-primary"></i>
                        </div>
                        <h5 class="modal-title mb-0" id="customerModalLabel">
                            Add New Customer
                        </h5>
                    </div>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close" style="opacity:0.9;">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="POST" id="customerForm" class="compact-form">
                    <div class="modal-body">
                        <input type="hidden" name="action" id="formAction" value="create">
                        <input type="hidden" name="customerId" id="customerId">
                        
                        <!-- Basic Information -->
                        <div class="form-section-header">
                            <i class="fas fa-user form-icon"></i>Basic Information
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customerName">
                                        <i class="fas fa-signature form-icon"></i>Customer Name 
                                        <span class="required-indicator">*</span>
                                    </label>
                                    <input type="text" class="form-control" id="customerName" name="customerName" 
                                           placeholder="Enter customer name" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customerType">
                                        <i class="fas fa-tag form-icon"></i>Customer Type 
                                        <span class="required-indicator">*</span>
                                    </label>
                                    <select class="form-control" id="customerType" name="customerType" required>
                                        <option value="">Select Type</option>
                                        <option value="Retail">🛒 Retail Customer</option>
                                        <option value="Shop">🏪 Shop/Business</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="mobile">
                                        <i class="fas fa-phone form-icon"></i>Mobile Number 
                                        <span class="required-indicator">*</span>
                                    </label>
                                    <input type="tel" class="form-control" id="mobile" name="mobile" 
                                           pattern="[0-9]{10}" maxlength="10" placeholder="10-digit mobile" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="alternativePhone">
                                        <i class="fas fa-phone-alt form-icon"></i>Alternative Phone
                                        <small class="text-muted">(Optional)</small>
                                    </label>
                                    <input type="tel" class="form-control" id="alternativePhone" name="alternativePhone" 
                                           pattern="[0-9]{10}" maxlength="10" placeholder="10-digit alternative">
                                </div>
                            </div>
                        </div>
                        
                        <!-- Location Information -->
                        <div class="form-section-header">
                            <i class="fas fa-map-marker-alt form-icon"></i>Location Details
                        </div>
                        
                        <div class="row">
                            <div class="col-md-8">
                                <div class="form-group">
                                    <label for="area">
                                        <i class="fas fa-location-arrow form-icon"></i>Area 
                                        <span class="required-indicator">*</span>
                                    </label>
                                    <div class="input-group">
                                        <select class="form-control" id="area" name="area" required>
                                            <option value="">Select Area</option>
                                            <?php
                                            // Populate areas from database as fallback
                                            $areasQuery = "SELECT AreaName FROM tblareas WHERE IsActive = 1 ORDER BY AreaName ASC";
                                            $areasResult = mysqli_query($con, $areasQuery);
                                            if ($areasResult) {
                                                while ($areaRow = mysqli_fetch_assoc($areasResult)) {
                                                    echo '<option value="' . htmlspecialchars($areaRow['AreaName']) . '">' . htmlspecialchars($areaRow['AreaName']) . '</option>';
                                                }
                                            }
                                            ?>
                                        </select>
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-primary" id="addNewAreaBtn" 
                                                    title="Add New Area">
                                                <i class="fas fa-plus"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="field-description">
                                        Select existing area or add new one
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="nearbyCustomerCount">
                                        <i class="fas fa-users form-icon"></i>Area Customers
                                    </label>
                                    <div class="form-control-plaintext">
                                        <span id="nearbyCustomerCount" class="badge badge-info">
                                            <i class="fas fa-spinner fa-spin"></i> Loading...
                                        </span>
                                    </div>
                                    <div class="field-description">
                                        Customers in selected area
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="nearbyCustomer">
                                <i class="fas fa-user-friends form-icon"></i>Create Near Existing Customer
                            </label>
                            <div class="input-group">
                                <select class="form-control" id="nearbyCustomer" name="nearbyCustomer">
                                    <option value="">Select nearby customer (optional)</option>
                                </select>
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" id="clearNearbyBtn" 
                                            data-toggle="tooltip" title="Clear Selection">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="field-description">
                                <i class="fas fa-info-circle mr-1"></i>
                                Choose a customer to auto-fill location details and list this customer nearby
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="address">
                                <i class="fas fa-home form-icon"></i>Address 
                                <span class="required-indicator">*</span>
                            </label>
                            <textarea class="form-control" id="address" name="address" rows="2" 
                                      placeholder="Enter complete address with landmarks" required></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="gmapLocation">
                                <i class="fas fa-globe form-icon"></i>Google Maps Location
                                <small class="text-muted">(Optional)</small>
                            </label>
                            <div class="input-group">
                                <input type="url" class="form-control" id="gmapLocation" name="gmapLocation" 
                                       placeholder="https://maps.google.com/?q=...">
                                <div class="input-group-append">
                                    <button type="button" class="btn btn-outline-success" id="getCurrentLocation" 
                                            title="Get Current Location">
                                        <i class="fas fa-crosshairs"></i>
                                        <span class="d-none d-sm-inline ml-1">Auto-detect</span>
                                    </button>
                                </div>
                            </div>
                            <div class="field-description">
                                <i class="fas fa-lightbulb mr-1"></i>
                                Click "Auto-detect" to capture current location or paste Google Maps link
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light btn-modern" data-dismiss="modal">
                            <i class="fas fa-times mr-2"></i>Cancel
                        </button>
                        <button type="submit" class="btn btn-primary btn-modern" id="submitBtn">
                            <i class="fas fa-save mr-2"></i>Save Customer
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Customer Modal -->
    <div class="modal fade" id="viewCustomerModal" tabindex="-1" role="dialog" aria-labelledby="viewCustomerModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title" id="viewCustomerModalLabel">
                        <i class="fas fa-eye mr-2"></i>Customer Details
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="customerDetailsContent">
                    <!-- Customer details will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Customer Outstanding Modal -->
    <div class="modal fade" id="customerOutstandingModal" tabindex="-1" role="dialog" aria-labelledby="customerOutstandingModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="customerOutstandingModalLabel">
                        <i class="fas fa-chart-line mr-2"></i>Customer Outstanding Amounts
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <input type="text" class="form-control form-control-sm" id="outstandingSearch" 
                                   placeholder="Search customers...">
                        </div>
                        <div class="col-md-3">
                            <select class="form-control form-control-sm" id="outstandingFilter">
                                <option value="">All Types</option>
                                <option value="Retail">Retail</option>
                                <option value="Shop">Shop</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <button type="button" class="btn btn-success btn-sm" onclick="exportOutstanding()">
                                <i class="fas fa-download mr-1"></i>Export
                            </button>
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover table-sm" id="outstandingTable">
                            <thead class="thead-dark">
                                <tr>
                                    <th>S.No</th>
                                    <th>Customer Name</th>
                                    <th>Area</th>
                                    <th>Mobile</th>
                                    <th>Type</th>
                                    <th>Outstanding Amount</th>
                                    <th>Last Payment</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="outstandingTableBody">
                                <!-- Data will be loaded via AJAX -->
                            </tbody>
                        </table>
                    </div>
                    
                    <div id="outstandingPagination" class="d-flex justify-content-center">
                        <!-- Pagination will be loaded here -->
                    </div>
                </div>
                <div class="modal-footer">
                    <div class="mr-auto">
                        <span class="text-muted">Total Outstanding: <strong id="totalOutstanding">₹0</strong></span>
                    </div>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Add Area Modal -->
    <div class="modal fade" id="quickAddAreaModal" tabindex="-1" role="dialog" aria-labelledby="quickAddAreaModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title" id="quickAddAreaModalLabel">
                        <i class="fas fa-plus-circle mr-2"></i>Add New Area
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="quickAreaForm">
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="quickAreaName">Area Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="quickAreaName" name="areaName" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="quickAreaDescription">Description <small class="text-muted">(Optional)</small></label>
                            <textarea class="form-control" id="quickAreaDescription" name="description" rows="2" 
                                      placeholder="Enter area description or landmarks..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="fas fa-times mr-1"></i>Cancel
                        </button>
                        <button type="submit" class="btn btn-success" id="quickAreaSubmitBtn">
                            <i class="fas fa-save mr-1"></i>Save Area
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include_once('includes/footer2.php');?>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="js/quick-filters.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <!-- Select2 for enhanced dropdowns -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
        let currentView = 'grid';
        
        function toggleView(view) {
            const gridView = document.getElementById('gridView');
            const tableView = document.getElementById('tableView');
            const gridBtn = document.getElementById('gridViewBtn');
            const tableBtn = document.getElementById('tableViewBtn');
            
            if (view === 'grid') {
                gridView.style.display = 'grid';
                tableView.style.display = 'none';
                gridBtn.classList.add('active');
                tableBtn.classList.remove('active');
                currentView = 'grid';
            } else {
                gridView.style.display = 'none';
                tableView.style.display = 'block';
                tableBtn.classList.add('active');
                gridBtn.classList.remove('active');
                currentView = 'table';
            }
            
            // Store preference in localStorage
            localStorage.setItem('customerViewPreference', view);
        }
        
        // Load view preference on page load
        document.addEventListener('DOMContentLoaded', function() {
            const savedView = localStorage.getItem('customerViewPreference') || 'grid';
            toggleView(savedView);
            
            // Initialize Select2 dropdowns
            initializeSelect2Dropdowns();
            
            // Initialize real-time search
            initializeRealTimeSearch();
            
            // Initialize customer count display
            updateCustomerCount(0);
            
            // Load areas and nearby customers for dropdown with a small delay to ensure page is fully loaded
            setTimeout(function() {
                loadAreas();
                loadNearbyCustomers();
            }, 500);
        });

        // Initialize Select2 on all dropdowns
        function initializeSelect2Dropdowns() {
            // Initialize Area dropdown with search
            $('#area').select2({
                placeholder: 'Select or type to search areas...',
                allowClear: true,
                dropdownParent: $('#customerModal'),
                matcher: customMatcher,
                templateResult: formatAreaOption,
                templateSelection: formatAreaSelection,
                escapeMarkup: function(markup) { return markup; }
            });
            
            // Initialize Customer Type dropdown with search
            $('#customerType').select2({
                placeholder: 'Select customer type...',
                allowClear: false,
                dropdownParent: $('#customerModal'),
                minimumResultsForSearch: Infinity, // Hide search for small lists
                templateResult: formatCustomerTypeOption,
                templateSelection: formatCustomerTypeSelection,
                escapeMarkup: function(markup) { return markup; }
            });
            
            // Initialize Nearby Customer dropdown with search
            $('#nearbyCustomer').select2({
                placeholder: 'Type to search customers...',
                allowClear: true,
                dropdownParent: $('#customerModal'),
                matcher: customMatcher,
                templateResult: formatNearbyCustomerOption,
                templateSelection: formatNearbyCustomerSelection,
                escapeMarkup: function(markup) { return markup; }
            });
        }

        // Custom matcher for better search functionality
        function customMatcher(params, data) {
            // If there are no search terms, return all data
            if ($.trim(params.term) === '') {
                return data;
            }

            // Do not display the item if there is no 'text' property
            if (typeof data.text === 'undefined') {
                return null;
            }

            // Check if the text contains the term (case insensitive)
            const searchTerm = params.term.toLowerCase();
            const text = data.text.toLowerCase();
            
            // Also search in data attributes if available
            const element = data.element;
            let searchableText = text;
            
            if (element) {
                const area = $(element).attr('data-area') || '';
                const mobile = $(element).attr('data-mobile') || '';
                searchableText += ' ' + area.toLowerCase() + ' ' + mobile.toLowerCase();
            }
            
            if (searchableText.indexOf(searchTerm) > -1) {
                return data;
            }

            return null;
        }

        // Format Area dropdown options
        function formatAreaOption(area) {
            if (!area.id) {
                return area.text;
            }
            return $('<span><i class="fas fa-map-marker-alt text-primary mr-2"></i>' + area.text + '</span>');
        }

        function formatAreaSelection(area) {
            return area.text || area.id;
        }

        // Format Customer Type dropdown options
        function formatCustomerTypeOption(type) {
            if (!type.id) {
                return type.text;
            }
            
            const icon = type.id === 'Retail' ? 'fas fa-user' : 'fas fa-store';
            const color = type.id === 'Retail' ? 'text-success' : 'text-info';
            
            return $('<span><i class="' + icon + ' ' + color + ' mr-2"></i>' + type.text + '</span>');
        }

        function formatCustomerTypeSelection(type) {
            return type.text || type.id;
        }

        // Format Nearby Customer dropdown options
        function formatNearbyCustomerOption(customer) {
            if (!customer.id) {
                return customer.text;
            }
            
            const element = customer.element;
            if (element) {
                const area = $(element).attr('data-area') || '';
                const mobile = $(element).attr('data-mobile') || '';
                
                return $(`
                    <div class="d-flex align-items-center">
                        <div class="mr-2">
                            <i class="fas fa-user-circle text-primary"></i>
                        </div>
                        <div class="flex-grow-1">
                            <div class="font-weight-bold">${customer.text.split(' (')[0]}</div>
                            <small class="text-muted">
                                <i class="fas fa-phone mr-1"></i>${mobile}
                                ${area ? `<i class="fas fa-map-marker-alt ml-2 mr-1"></i>${area}` : ''}
                            </small>
                        </div>
                    </div>
                `);
            }
            
            return customer.text;
        }

        function formatNearbyCustomerSelection(customer) {
            if (customer.element) {
                const customerName = customer.text.split(' (')[0];
                return customerName;
            }
            return customer.text || customer.id;
        }

        function clearForm() {
            document.getElementById('customerForm').reset();
            document.getElementById('formAction').value = 'create';
            document.getElementById('customerId').value = '';
            document.getElementById('customerModalLabel').innerHTML = '<i class="fas fa-user-plus mr-2"></i>Add New Customer';
            document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-2"></i>Save Customer';
            
            // Reset Select2 dropdowns
            $('#area').val(null).trigger('change');
            $('#customerType').val(null).trigger('change');
            $('#nearbyCustomer').val(null).trigger('change');
            
            // Reset customer count display
            updateCustomerCount(0);
        }

        // Real-time search functionality
        let searchTimeout;
        let currentSearchQuery = '';
        let searchSuggestionsVisible = false;
        let selectedSuggestionIndex = -1;

        function initializeRealTimeSearch() {
            const searchInput = document.getElementById('searchInput');
            const searchSuggestions = document.getElementById('searchSuggestions');
            const filterType = document.getElementById('filterType');
            const clearSearchBtn = document.getElementById('clearSearchBtn');
            const searchForm = document.getElementById('searchForm');

            // Real-time search on input
            searchInput.addEventListener('input', function(e) {
                const query = e.target.value.trim();
                currentSearchQuery = query;
                
                clearTimeout(searchTimeout);
                
                if (query.length >= 2) {
                    // Show loading state
                    showSearchLoading(true);
                    
                    // Debounce search requests
                    searchTimeout = setTimeout(() => {
                        performRealTimeSearch(query);
                    }, 300);
                } else if (query.length === 0) {
                    hideSuggestions();
                    clearSearchResults();
                } else {
                    hideSuggestions();
                }
            });

            // Handle input focus and blur
            searchInput.addEventListener('focus', function() {
                this.classList.add('search-input-focused');
                if (currentSearchQuery.length >= 2) {
                    showSuggestions();
                }
            });

            searchInput.addEventListener('blur', function() {
                this.classList.remove('search-input-focused');
                // Delay hiding suggestions to allow clicking on them
                setTimeout(() => {
                    hideSuggestions();
                }, 150);
            });

            // Keyboard navigation for suggestions
            searchInput.addEventListener('keydown', function(e) {
                if (!searchSuggestionsVisible) return;
                
                const suggestions = document.querySelectorAll('.search-suggestion-item');
                
                switch(e.key) {
                    case 'ArrowDown':
                        e.preventDefault();
                        selectedSuggestionIndex = Math.min(selectedSuggestionIndex + 1, suggestions.length - 1);
                        updateSelectedSuggestion(suggestions);
                        break;
                        
                    case 'ArrowUp':
                        e.preventDefault();
                        selectedSuggestionIndex = Math.max(selectedSuggestionIndex - 1, -1);
                        updateSelectedSuggestion(suggestions);
                        break;
                        
                    case 'Enter':
                        e.preventDefault();
                        if (selectedSuggestionIndex >= 0 && suggestions[selectedSuggestionIndex]) {
                            selectSuggestion(suggestions[selectedSuggestionIndex]);
                        } else {
                            // Submit form for regular search
                            searchForm.submit();
                        }
                        break;
                        
                    case 'Escape':
                        hideSuggestions();
                        searchInput.blur();
                        break;
                }
            });

            // Filter type change trigger search
            filterType.addEventListener('change', function() {
                if (currentSearchQuery.length >= 2) {
                    performRealTimeSearch(currentSearchQuery);
                }
            });

            // Clear search functionality
            clearSearchBtn.addEventListener('click', function(e) {
                e.preventDefault();
                clearSearch();
            });

            // Handle form submission
            searchForm.addEventListener('submit', function(e) {
                hideSuggestions();
                if (currentSearchQuery.trim()) {
                    showSearchInfo(`Searching for "${currentSearchQuery}"...`);
                }
            });
            
            // Click outside to hide suggestions
            document.addEventListener('click', function(e) {
                if (!e.target.closest('#searchInput') && !e.target.closest('#searchSuggestions')) {
                    hideSuggestions();
                }
            });
        }

        function performRealTimeSearch(query) {
            const filterType = document.getElementById('filterType').value;
            
            // Build query parameters
            const params = new URLSearchParams({
                search: query,
                limit: 8, // Limit suggestions to 8 items
                suggestions: '1'
            });
            
            if (filterType) {
                params.append('type', filterType);
            }

            // Show interim loading state
            const suggestionsList = document.getElementById('suggestionsList');
            suggestionsList.innerHTML = '<div class="suggestions-loading-state"><i class="fas fa-spinner mr-2"></i> Searching...</div>';
            document.getElementById('suggestionsTitle').textContent = 'Searching';

            fetch(`api/get-customers-search.php?${params.toString()}`)
                .then(response => response.json())
                .then(data => {
                    showSearchLoading(false);
                    
                    if (data.success) {
                        displaySearchSuggestions(data.data, query);
                        
                        if (data.data.length > 0) {
                            showSearchInfo(`Found ${data.total} customers matching "${query}"`);
                            document.getElementById('suggestionsTitle').textContent = 'Matches';
                        } else {
                            showSearchInfo(`No customers found matching "${query}"`);
                            document.getElementById('suggestionsTitle').textContent = 'No Results';
                        }
                    } else {
                        console.warn('Search failed:', data.message);
                        displayNoSuggestions();
                        document.getElementById('suggestionsTitle').textContent = 'Error';
                    }
                })
                .catch(error => {
                    console.error('Search error:', error);
                    showSearchLoading(false);
                    displayNoSuggestions();
                    document.getElementById('suggestionsTitle').textContent = 'Error';
                });
        }

        function displaySearchSuggestions(customers, query) {
            const suggestionsList = document.getElementById('suggestionsList');
            
            if (customers.length === 0) {
                displayNoSuggestions();
                return;
            }

            let html = '';
            customers.forEach((customer, index) => {
                const highlightedName = highlightSearchTerm(customer.CustomerName, query);
                const highlightedMobile = highlightSearchTerm(customer.Mobile, query);
                const highlightedArea = highlightSearchTerm(customer.Area, query);
                
                const typeClass = customer.CustomerType.toLowerCase() === 'retail' ? 'suggestion-type-retail' : 'suggestion-type-shop';
                
                html += `
                    <div class="search-suggestion-item" data-customer-id="${customer.ID}" 
                         onclick="selectSuggestionById(${customer.ID}, '${customer.CustomerName}')">
                        <div class="suggestion-main">${highlightedName}</div>
                        <div class="suggestion-details">
                            <div class="suggestion-detail">
                                <i class="fas fa-phone text-primary"></i>
                                <span>${highlightedMobile}</span>
                            </div>
                            <div class="suggestion-detail">
                                <i class="fas fa-map-marker-alt text-secondary"></i>
                                <span>${highlightedArea}</span>
                            </div>
                            <div class="suggestion-detail">
                                <span class="suggestion-type-badge ${typeClass}">${customer.CustomerType}</span>
                            </div>
                        </div>
                    </div>
                `;
            });

            suggestionsList.innerHTML = html;
            showSuggestions();
            selectedSuggestionIndex = -1;
        }

        function displayNoSuggestions() {
            const suggestionsList = document.getElementById('suggestionsList');
            suggestionsList.innerHTML = `
                <div class="no-suggestions">
                    <i class="fas fa-search mr-2"></i>No customers found
                </div>
            `;
            showSuggestions();
        }

        function highlightSearchTerm(text, term) {
            if (!term) return text;
            // Escape regex special chars in term
            const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            try {
                const regex = new RegExp('(' + escaped + ')', 'gi');
                return text.replace(regex, '<span class="search-highlight">$1</span>');
            } catch (e) {
                return text; // Fallback if regex fails
            }
        }

        function showSuggestions() {
            document.getElementById('searchSuggestions').style.display = 'block';
            searchSuggestionsVisible = true;
        }

        window.hideSuggestions = function hideSuggestions() {
            document.getElementById('searchSuggestions').style.display = 'none';
            searchSuggestionsVisible = false;
            selectedSuggestionIndex = -1;
        }

        function updateSelectedSuggestion(suggestions) {
            // Remove active class from all suggestions
            suggestions.forEach((item, index) => {
                if (index === selectedSuggestionIndex) {
                    item.classList.add('active');
                    item.scrollIntoView({ block: 'nearest' });
                } else {
                    item.classList.remove('active');
                }
            });
        }

        function selectSuggestion(suggestionElement) {
            const customerId = suggestionElement.getAttribute('data-customer-id');
            const customerName = suggestionElement.querySelector('.suggestion-main').textContent;
            selectSuggestionById(customerId, customerName);
        }

        function selectSuggestionById(customerId, customerName) {
            // Fill search input with customer name
            document.getElementById('searchInput').value = customerName;
            currentSearchQuery = customerName;
            
            // Hide suggestions
            hideSuggestions();
            
            // Navigate to customer details or trigger search
            window.location.href = `customer-management.php?search=${encodeURIComponent(customerName)}`;
        }

        function showSearchLoading(show) {
            const spinner = document.getElementById('searchSpinner');
            if (show) {
                spinner.style.display = 'flex';
                document.getElementById('searchInput').classList.add('search-loading');
            } else {
                spinner.style.display = 'none';
                document.getElementById('searchInput').classList.remove('search-loading');
            }
        }

        function showSearchInfo(message) {
            const searchInfo = document.getElementById('searchInfo');
            const searchInfoText = document.getElementById('searchInfoText');
            
            searchInfoText.textContent = message;
            searchInfo.style.display = 'block';
            
            // Auto-hide after 3 seconds
            setTimeout(() => {
                searchInfo.style.display = 'none';
            }, 3000);
        }

        function clearSearch() {
            document.getElementById('searchInput').value = '';
            document.getElementById('filterType').value = '';
            currentSearchQuery = '';
            hideSuggestions();
            clearSearchResults();
            
            // Navigate to clean page
            window.location.href = 'customer-management.php';
        }

        function clearSearchResults() {
            document.getElementById('searchInfo').style.display = 'none';
        }

        // Get Current Location functionality
        document.getElementById('getCurrentLocation').addEventListener('click', function() {
            const button = this;
            const icon = button.querySelector('i');
            const input = document.getElementById('gmapLocation');
            
            if (!navigator.geolocation) {
                showLocationError('Geolocation is not supported by this browser. Please enter the location manually.');
                return;
            }
            
            // Check permission status first
            checkLocationPermission().then(permission => {
                if (permission === 'denied') {
                    showLocationPermissionModal();
                    return;
                }
                
                // Show loading state
                button.classList.add('location-loading');
                icon.className = 'fas fa-spinner';
                button.disabled = true;
                
                navigator.geolocation.getCurrentPosition(
                    function(position) {
                        const lat = position.coords.latitude;
                        const lng = position.coords.longitude;
                        const googleMapsUrl = `https://maps.google.com/?q=${lat},${lng}`;
                        
                        input.value = googleMapsUrl;
                        
                        // Get address using reverse geocoding
                        getAddressFromCoordinates(lat, lng);
                        
                        // Reset button state
                        button.classList.remove('location-loading');
                        icon.className = 'fas fa-map-marker-alt';
                        button.disabled = false;
                        
                        // Show success message
                        showLocationSuccess('Current location captured successfully!');
                    },
                    function(error) {
                        // Reset button state
                        button.classList.remove('location-loading');
                        icon.className = 'fas fa-map-marker-alt';
                        button.disabled = false;
                        
                        handleLocationError(error);
                    },
                    {
                        enableHighAccuracy: true,
                        timeout: 15000,
                        maximumAge: 300000
                    }
                );
            });
        });

        // Check location permission status
        async function checkLocationPermission() {
            if ('permissions' in navigator) {
                try {
                    const result = await navigator.permissions.query({ name: 'geolocation' });
                    return result.state;
                } catch (e) {
                    return 'unknown';
                }
            }
            return 'unknown';
        }

        // Handle location errors with detailed messages
        function handleLocationError(error) {
            let title = 'Location Access Error';
            let message = '';
            let showInstructions = false;
            
            switch(error.code) {
                case error.PERMISSION_DENIED:
                    title = 'Location Permission Denied';
                    message = 'You have denied location access. To use this feature, please allow location access in your browser.';
                    showInstructions = true;
                    break;
                case error.POSITION_UNAVAILABLE:
                    title = 'Location Unavailable';
                    message = 'Your location information is currently unavailable. Please check your GPS/location services and try again.';
                    break;
                case error.TIMEOUT:
                    title = 'Location Timeout';
                    message = 'Location request timed out. Please try again or enter the location manually.';
                    break;
                default:
                    title = 'Location Error';
                    message = 'An unknown error occurred while getting your location. Please try again.';
                    break;
            }
            
            if (showInstructions) {
                showLocationPermissionModal();
            } else {
                showLocationError(message, title);
            }
        }

        // Show location permission instructions modal
        function showLocationPermissionModal() {
            const modal = `
                <div class="modal fade" id="locationPermissionModal" tabindex="-1" role="dialog">
                    <div class="modal-dialog modal-lg" role="document">
                        <div class="modal-content">
                            <div class="modal-header bg-warning text-dark">
                                <h5 class="modal-title">
                                    <i class="fas fa-exclamation-triangle mr-2"></i>Location Access Required
                                </h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle mr-2"></i>
                                    To automatically capture your current location, this website needs access to your location.
                                </div>
                                
                                <h6><i class="fas fa-mobile-alt mr-2"></i>For Mobile Devices:</h6>
                                <ol class="mb-3">
                                    <li>Click on the location button again</li>
                                    <li>When prompted, tap <strong>"Allow"</strong> or <strong>"Share Location"</strong></li>
                                    <li>If no prompt appears, check your browser settings</li>
                                </ol>

                                <h6><i class="fas fa-desktop mr-2"></i>For Desktop Browsers:</h6>
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6 class="text-primary">Chrome/Edge:</h6>
                                        <ul class="small">
                                            <li>Click the location icon in the address bar</li>
                                            <li>Select "Always allow" and click "Done"</li>
                                            <li>Refresh the page and try again</li>
                                        </ul>
                                    </div>
                                    <div class="col-md-6">
                                        <h6 class="text-primary">Firefox/Safari:</h6>
                                        <ul class="small">
                                            <li>Click on the shield or lock icon</li>
                                            <li>Find "Location" and set to "Allow"</li>
                                            <li>Refresh the page and try again</li>
                                        </ul>
                                    </div>
                                </div>
                                
                                <div class="alert alert-secondary mt-3">
                                    <i class="fas fa-lightbulb mr-2"></i>
                                    <strong>Alternative:</strong> You can manually enter the Google Maps location link or visit 
                                    <a href="https://maps.google.com" target="_blank">Google Maps</a>, find your location, 
                                    and copy the URL to paste here.
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                <button type="button" class="btn btn-warning" onclick="retryLocationAccess()" data-dismiss="modal">
                                    <i class="fas fa-redo mr-1"></i>Try Again
                                </button>
                                <button type="button" class="btn btn-primary" onclick="openGoogleMaps()" data-dismiss="modal">
                                    <i class="fas fa-external-link-alt mr-1"></i>Open Google Maps
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Remove existing modal if any
            $('#locationPermissionModal').remove();
            
            // Add modal to body and show
            $('body').append(modal);
            $('#locationPermissionModal').modal('show');
        }

        // Retry location access
        function retryLocationAccess() {
            setTimeout(() => {
                document.getElementById('getCurrentLocation').click();
            }, 500);
        }

        // Open Google Maps in new tab
        function openGoogleMaps() {
            window.open('https://maps.google.com', '_blank');
        }

        // Get address from coordinates using reverse geocoding
        function getAddressFromCoordinates(lat, lng) {
            const addressField = document.getElementById('address');
            
            // Use Google Geocoding API (free alternative: Nominatim)
            // For production, you should use your own Google Maps API key
            const geocodingUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&zoom=18&addressdetails=1`;
            
            fetch(geocodingUrl)
                .then(response => response.json())
                .then(data => {
                    if (data && data.display_name) {
                        // Format the address nicely
                        let formattedAddress = '';
                        
                        if (data.address) {
                            const addr = data.address;
                            const addressParts = [];
                            
                            if (addr.house_number) addressParts.push(addr.house_number);
                            if (addr.road) addressParts.push(addr.road);
                            if (addr.neighbourhood) addressParts.push(addr.neighbourhood);
                            if (addr.suburb) addressParts.push(addr.suburb);
                            if (addr.city || addr.town || addr.village) {
                                addressParts.push(addr.city || addr.town || addr.village);
                            }
                            if (addr.state) addressParts.push(addr.state);
                            if (addr.postcode) addressParts.push(addr.postcode);
                            
                            formattedAddress = addressParts.join(', ');
                        }
                        
                        if (!formattedAddress) {
                            formattedAddress = data.display_name;
                        }
                        
                        addressField.value = formattedAddress;
                        
                        // Show success message for address
                        showLocationSuccess('Address filled automatically from your location!');
                    }
                })
                .catch(error => {
                    console.warn('Could not get address from coordinates:', error);
                    // Don't show error to user as this is an enhancement, not critical
                });
        }

        // Show customer outstanding modal
        function showCustomerOutstanding(customerType = '') {
            // Set modal title based on filter
            let title = 'Customer Outstanding Amounts';
            if (customerType === 'Retail') {
                title = 'Retail Customer Outstanding Amounts';
            } else if (customerType === 'Shop') {
                title = 'Shop Customer Outstanding Amounts';
            }
            
            document.getElementById('customerOutstandingModalLabel').innerHTML = 
                `<i class="fas fa-chart-line mr-2"></i>${title}`;
            
            // Set filter dropdown
            document.getElementById('outstandingFilter').value = customerType;
            
            // Load outstanding data
            loadCustomerOutstanding(customerType);
            
            // Show modal
            $('#customerOutstandingModal').modal('show');
        }

        // Load customer outstanding data
        function loadCustomerOutstanding(customerType = '', search = '', page = 1) {
            const tableBody = document.getElementById('outstandingTableBody');
            const totalOutstanding = document.getElementById('totalOutstanding');
            
            // Show loading
            tableBody.innerHTML = `
                <tr>
                    <td colspan="8" class="text-center py-4">
                        <i class="fas fa-spinner fa-spin mr-2"></i>Loading customer outstanding data...
                    </td>
                </tr>
            `;
            
            // Prepare query parameters
            const params = new URLSearchParams();
            if (customerType) params.append('type', customerType);
            if (search) params.append('search', search);
            params.append('page', page);
            
            // Fetch data (you'll need to create this API endpoint)
            fetch(`api/get-customer-outstanding.php?${params.toString()}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayOutstandingData(data.customers, data.total, data.pagination);
                        totalOutstanding.textContent = `₹${data.totalOutstanding.toLocaleString()}`;
                    } else {
                        tableBody.innerHTML = `
                            <tr>
                                <td colspan="8" class="text-center text-danger py-4">
                                    <i class="fas fa-exclamation-triangle mr-2"></i>Error loading data: ${data.message}
                                </td>
                            </tr>
                        `;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="8" class="text-center text-danger py-4">
                                <i class="fas fa-exclamation-triangle mr-2"></i>Error loading customer outstanding data
                            </td>
                        </tr>
                    `;
                });
        }

        // Display outstanding data in table
        function displayOutstandingData(customers, total, pagination) {
            const tableBody = document.getElementById('outstandingTableBody');
            const paginationDiv = document.getElementById('outstandingPagination');
            
            if (customers.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="8" class="text-center text-muted py-4">
                            <i class="fas fa-inbox mr-2"></i>No customer outstanding data found
                        </td>
                    </tr>
                `;
                return;
            }
            
            let html = '';
            customers.forEach((customer, index) => {
                const serialNo = ((pagination.currentPage - 1) * pagination.recordsPerPage) + index + 1;
                const outstanding = customer.outstandingAmount || 0;
                const outstandingClass = outstanding > 0 ? 'text-danger font-weight-bold' : 'text-success';
                
                html += `
                    <tr>
                        <td>${serialNo}</td>
                        <td>
                            <div class="font-weight-bold">${customer.CustomerName}</div>
                            <small class="text-muted">ID: ${customer.ID}</small>
                        </td>
                        <td>${customer.Area}</td>
                        <td>${customer.Mobile}</td>
                        <td>
                            <span class="badge badge-${customer.CustomerType === 'Retail' ? 'success' : 'info'}">
                                ${customer.CustomerType}
                            </span>
                        </td>
                        <td class="${outstandingClass}">₹${outstanding.toLocaleString()}</td>
                        <td>${customer.lastPaymentDate || 'No payments'}</td>
                        <td>
                            <button class="btn btn-info btn-sm" onclick="viewCustomer(${customer.ID})" title="View Customer">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-primary btn-sm ml-1" onclick="window.location.href='customer-payments.php?customer=${customer.ID}'" title="View Payments">
                                <i class="fas fa-rupee-sign"></i>
                            </button>
                        </td>
                    </tr>
                `;
            });
            
            tableBody.innerHTML = html;
            
            // Update pagination
            if (pagination.totalPages > 1) {
                let paginationHtml = '<nav><ul class="pagination pagination-sm">';
                
                // Previous button
                if (pagination.currentPage > 1) {
                    paginationHtml += `
                        <li class="page-item">
                            <a class="page-link" href="#" onclick="loadCustomerOutstanding('${document.getElementById('outstandingFilter').value}', '${document.getElementById('outstandingSearch').value}', ${pagination.currentPage - 1})">
                                Previous
                            </a>
                        </li>
                    `;
                }
                
                // Page numbers
                for (let i = 1; i <= pagination.totalPages; i++) {
                    if (i === pagination.currentPage || 
                        i === 1 || 
                        i === pagination.totalPages || 
                        (i >= pagination.currentPage - 2 && i <= pagination.currentPage + 2)) {
                        
                        paginationHtml += `
                            <li class="page-item ${i === pagination.currentPage ? 'active' : ''}">
                                <a class="page-link" href="#" onclick="loadCustomerOutstanding('${document.getElementById('outstandingFilter').value}', '${document.getElementById('outstandingSearch').value}', ${i})">
                                    ${i}
                                </a>
                            </li>
                        `;
                    } else if (i === pagination.currentPage - 3 || i === pagination.currentPage + 3) {
                        paginationHtml += '<li class="page-item disabled"><span class="page-link">...</span></li>';
                    }
                }
                
                // Next button
                if (pagination.currentPage < pagination.totalPages) {
                    paginationHtml += `
                        <li class="page-item">
                            <a class="page-link" href="#" onclick="loadCustomerOutstanding('${document.getElementById('outstandingFilter').value}', '${document.getElementById('outstandingSearch').value}', ${pagination.currentPage + 1})">
                                Next
                            </a>
                        </li>
                    `;
                }
                
                paginationHtml += '</ul></nav>';
                paginationDiv.innerHTML = paginationHtml;
            } else {
                paginationDiv.innerHTML = '';
            }
        }

        // Export outstanding data
        function exportOutstanding() {
            const customerType = document.getElementById('outstandingFilter').value;
            const search = document.getElementById('outstandingSearch').value;
            
            // Create export URL
            const params = new URLSearchParams();
            if (customerType) params.append('type', customerType);
            if (search) params.append('search', search);
            params.append('export', '1');
            
            // Download file
            window.open(`api/get-customer-outstanding.php?${params.toString()}`, '_blank');
        }

        // Add event listeners for outstanding modal search and filter
        document.addEventListener('DOMContentLoaded', function() {
            // Search functionality
            let searchTimeout;
            document.getElementById('outstandingSearch').addEventListener('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    const customerType = document.getElementById('outstandingFilter').value;
                    const search = this.value;
                    loadCustomerOutstanding(customerType, search, 1);
                }, 500);
            });
            
            // Filter functionality
            document.getElementById('outstandingFilter').addEventListener('change', function() {
                const search = document.getElementById('outstandingSearch').value;
                loadCustomerOutstanding(this.value, search, 1);
            });
        });

        // Show location success message
        function showLocationSuccess(message) {
            const input = document.getElementById('gmapLocation');
            const successMsg = document.createElement('div');
            successMsg.className = 'alert alert-success alert-dismissible fade show mt-2';
            successMsg.innerHTML = `
                <i class="fas fa-check-circle mr-2"></i>${message}
                <button type="button" class="close" data-dismiss="alert">
                    <span>&times;</span>
                </button>
            `;
            input.parentNode.parentNode.appendChild(successMsg);
            
            // Auto-dismiss after 3 seconds
            setTimeout(() => {
                if (successMsg.parentNode) {
                    successMsg.remove();
                }
            }, 3000);
        }

        // Show location error message
        function showLocationError(message, title = 'Location Error') {
            const input = document.getElementById('gmapLocation');
            const errorMsg = document.createElement('div');
            errorMsg.className = 'alert alert-warning alert-dismissible fade show mt-2';
            errorMsg.innerHTML = `
                <i class="fas fa-exclamation-triangle mr-2"></i><strong>${title}:</strong> ${message}
                <button type="button" class="close" data-dismiss="alert">
                    <span>&times;</span>
                </button>
            `;
            input.parentNode.parentNode.appendChild(errorMsg);
            
            // Auto-dismiss after 5 seconds
            setTimeout(() => {
                if (errorMsg.parentNode) {
                    errorMsg.remove();
                }
            }, 5000);
        }

        function editCustomer(customerId) {
            // Fetch customer data via AJAX
            fetch('api/get-customer.php?id=' + customerId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('formAction').value = 'update';
                        document.getElementById('customerId').value = data.customer.ID;
                        document.getElementById('customerName').value = data.customer.CustomerName;
                        document.getElementById('mobile').value = data.customer.Mobile;
                        document.getElementById('alternativePhone').value = data.customer.AlternativePhone || '';
                        
                        // Set area dropdown value with Select2
                        const customerArea = data.customer.Area;
                        
                        // Check if area exists in dropdown
                        if (customerArea && $('#area option[value="' + customerArea + '"]').length === 0) {
                            // If area doesn't exist, add it to dropdown
                            $('#area').append(new Option(customerArea, customerArea));
                        }
                        
                        $('#area').val(customerArea).trigger('change');
                        
                        document.getElementById('address').value = data.customer.Address;
                        document.getElementById('gmapLocation').value = data.customer.GmapLocation || '';
                        $('#customerType').val(data.customer.CustomerType).trigger('change');
                        
                        // Set nearby customer if exists
                        if (data.customer.NearbyCustomerId) {
                            $('#nearbyCustomer').val(data.customer.NearbyCustomerId).trigger('change');
                        } else {
                            $('#nearbyCustomer').val(null).trigger('change');
                        }
                        
                        document.getElementById('customerModalLabel').innerHTML = '<i class="fas fa-edit mr-2"></i>Edit Customer';
                        document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-2"></i>Update Customer';
                        
                        $('#customerModal').modal('show');
                    } else {
                        alert('Error fetching customer data: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error fetching customer data');
                });
        }

        function viewCustomer(customerId) {
            // Fetch customer data via AJAX
            fetch('api/get-customer.php?id=' + customerId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const customer = data.customer;
                        const content = `
                            <div class="row">
                                <div class="col-md-6">
                                    <table class="table table-borderless table-sm">
                                        <tr><td><strong>Customer Name:</strong></td><td>${customer.CustomerName}</td></tr>
                                        <tr><td><strong>Mobile:</strong></td><td><a href="tel:${customer.Mobile}">${customer.Mobile}</a></td></tr>
                                        ${customer.AlternativePhone ? `<tr><td><strong>Alt. Phone:</strong></td><td><a href="tel:${customer.AlternativePhone}">${customer.AlternativePhone}</a></td></tr>` : ''}
                                        <tr><td><strong>Area:</strong></td><td>${customer.Area}</td></tr>
                                        <tr><td><strong>Customer Type:</strong></td><td>
                                            <span class="badge badge-${customer.CustomerType === 'Retail' ? 'success' : 'info'} px-2 py-1">
                                                ${customer.CustomerType}
                                            </span>
                                        </td></tr>
                                    </table>
                                </div>
                                <div class="col-md-6">
                                    <table class="table table-borderless table-sm">
                                        <tr><td><strong>Created Date:</strong></td><td>${new Date(customer.CreatedDate).toLocaleDateString()}</td></tr>
                                        <tr><td><strong>Created By:</strong></td><td>${customer.CreatedByName || 'N/A'}</td></tr>
                                        ${customer.UpdatedDate ? `<tr><td><strong>Last Updated:</strong></td><td>${new Date(customer.UpdatedDate).toLocaleDateString()}</td></tr>` : ''}
                                        ${customer.UpdatedByName ? `<tr><td><strong>Updated By:</strong></td><td>${customer.UpdatedByName}</td></tr>` : ''}
                                    </table>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-12">
                                    <strong>Address:</strong>
                                    <p class="mt-1 p-2 bg-light border rounded">${customer.Address}</p>
                                </div>
                            </div>
                            ${customer.GmapLocation ? `
                            <div class="row">
                                <div class="col-12">
                                    <strong>Location:</strong>
                                    <p class="mt-1">
                                        <a href="${customer.GmapLocation}" target="_blank" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-map-marker-alt mr-1"></i>View on Google Maps
                                        </a>
                                    </p>
                                </div>
                            </div>
                            ` : ''}
                        `;
                        
                        document.getElementById('customerDetailsContent').innerHTML = content;
                        $('#viewCustomerModal').modal('show');
                    } else {
                        alert('Error fetching customer data: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error fetching customer data');
                });
        }

        function deleteCustomer(customerId, customerName) {
            if (confirm(`Are you sure you want to delete customer "${customerName}"? This action cannot be undone.`)) {
                window.location.href = 'customer-management.php?delete=' + customerId;
            }
        }

        function exportCustomers() {
            // Create workbook
            const wb = XLSX.utils.book_new();
            
            // Get table data (use table view data)
            const table = document.querySelector('#tableView .table');
            const ws = XLSX.utils.table_to_sheet(table);
            
            // Set column widths
            ws['!cols'] = [
                { width: 5 },   // #
                { width: 25 },  // Customer Name
                { width: 15 },  // Mobile
                { width: 20 },  // Area
                { width: 12 },  // Type
                { width: 15 },  // Location
                { width: 15 },  // Created Date
                { width: 12 }   // Actions (will be empty in export)
            ];
            
            XLSX.utils.book_append_sheet(wb, ws, 'Customers');
            
            // Save file
            const fileName = 'Customers_Export_' + new Date().toISOString().slice(0, 10) + '.xlsx';
            XLSX.writeFile(wb, fileName);
        }

        // Phone number validation
        document.getElementById('mobile').addEventListener('input', function(e) {
            this.value = this.value.replace(/[^0-9]/g, '');
            if (this.value.length > 10) {
                this.value = this.value.slice(0, 10);
            }
        });

        // Alternative phone number validation
        document.getElementById('alternativePhone').addEventListener('input', function(e) {
            this.value = this.value.replace(/[^0-9]/g, '');
            if (this.value.length > 10) {
                this.value = this.value.slice(0, 10);
            }
        });

        // Auto-dismiss alerts after 5 seconds
        setTimeout(function() {
            $('.alert').fadeOut();
        }, 5000);

        // Clean up any location permission modals when customer modal is closed
        $('#customerModal').on('hidden.bs.modal', function () {
            $('#locationPermissionModal').modal('hide').remove();
        });

        // Initialize tooltips for better UX
        $(function () {
            $('[data-toggle="tooltip"]').tooltip();
        });

        // Nearby customer management functions
        function loadNearbyCustomers() {
            // Show loading state for Select2
            $('#nearbyCustomer').prop('disabled', true).html('<option>Loading customers...</option>').trigger('change');
            updateCustomerCount('loading');
            
            fetch('api/get-customers-search.php?limit=50')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        const nearbySelect = $('#nearbyCustomer');
                        
                        // Store current selection
                        const currentValue = nearbySelect.val();
                        
                        // Clear and rebuild options
                        nearbySelect.empty().append('<option value="">Select nearby customer (optional)</option>');
                        
                        // Add customers with data attributes for Select2
                        data.data.forEach(customer => {
                            const option = new Option(customer.display, customer.ID);
                            $(option).attr('data-area', customer.Area);
                            $(option).attr('data-address', customer.Address);
                            $(option).attr('data-location', customer.GmapLocation || '');
                            $(option).attr('data-mobile', customer.Mobile);
                            nearbySelect.append(option);
                        });
                        
                        // Enable and trigger change for Select2
                        nearbySelect.prop('disabled', false).trigger('change');
                        
                        // Restore selection if it still exists
                        if (currentValue) {
                            nearbySelect.val(currentValue).trigger('change');
                        }
                        
                        updateCustomerCount('all', data.data.length);
                        console.log('Loaded ' + data.data.length + ' customers for nearby selection');
                    } else {
                        console.warn('Failed to load customers for nearby selection:', data.message);
                        handleNearbyCustomersLoadError();
                    }
                })
                .catch(error => {
                    console.error('Error loading customers for nearby selection:', error);
                    handleNearbyCustomersLoadError();
                });
        }

        // Load customers by specific area
        function loadCustomersByArea(area) {
            if (!area || area.trim() === '') {
                resetNearbyCustomers();
                return;
            }
            
            // Show loading state for Select2
            $('#nearbyCustomer').prop('disabled', true).html('<option>Loading area customers...</option>').trigger('change');
            updateCustomerCount('loading');
            
            // Build query parameters for area-specific search
            const params = new URLSearchParams({
                area: area,
                limit: 100  // Higher limit for area-specific search
            });
            
            fetch(`api/get-customers-by-area.php?${params.toString()}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        const nearbySelect = $('#nearbyCustomer');
                        
                        // Clear and rebuild options
                        nearbySelect.empty().append('<option value="">Select nearby customer (optional)</option>');
                        
                        // Add area-specific customers with data attributes for Select2
                        data.data.forEach(customer => {
                            const displayText = `${customer.CustomerName} (${customer.Mobile})`;
                            const option = new Option(displayText, customer.ID);
                            $(option).attr('data-area', customer.Area);
                            $(option).attr('data-address', customer.Address);
                            $(option).attr('data-location', customer.GmapLocation || '');
                            $(option).attr('data-mobile', customer.Mobile);
                            $(option).attr('data-type', customer.CustomerType);
                            nearbySelect.append(option);
                        });
                        
                        // Enable and trigger change for Select2
                        nearbySelect.prop('disabled', false).trigger('change');
                        
                        // Update customer count
                        updateCustomerCount('area', data.data.length, area);
                        
                        if (data.data.length > 0) {
                            showAlert('info', `Found ${data.data.length} customers in "${area}" area`);
                        } else {
                            showAlert('warning', `No existing customers found in "${area}" area`);
                        }
                        
                        console.log(`Loaded ${data.data.length} customers from area: ${area}`);
                    } else {
                        console.warn('Failed to load customers by area:', data.message);
                        handleNearbyCustomersLoadError();
                        updateCustomerCount('error');
                    }
                })
                .catch(error => {
                    console.error('Error loading customers by area:', error);
                    handleNearbyCustomersLoadError();
                    updateCustomerCount('error');
                });
        }

        // Reset nearby customers to show all
        function resetNearbyCustomers() {
            $('#nearbyCustomer').empty().append('<option value="">Select nearby customer (optional)</option>');
            $('#nearbyCustomer').prop('disabled', false).trigger('change');
            updateCustomerCount(0);
        }

        function handleNearbyCustomersLoadError() {
            const nearbySelect = $('#nearbyCustomer');
            nearbySelect.empty().append('<option value="">Select nearby customer (optional)</option>');
            nearbySelect.prop('disabled', false).trigger('change');
            updateCustomerCount('error');
        }

        // Update customer count display
        function updateCustomerCount(type, count = 0, area = '') {
            const countBadge = document.getElementById('nearbyCustomerCount');
            
            switch(type) {
                case 'loading':
                    countBadge.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Loading...';
                    countBadge.className = 'badge badge-secondary';
                    break;
                    
                case 'area':
                    if (count > 0) {
                        countBadge.innerHTML = `<i class="fas fa-users mr-1"></i>${count} customers`;
                        countBadge.className = 'badge badge-success';
                        countBadge.title = `${count} existing customers in ${area} area`;
                    } else {
                        countBadge.innerHTML = '<i class="fas fa-plus-circle mr-1"></i>First customer';
                        countBadge.className = 'badge badge-warning';
                        countBadge.title = `No existing customers in ${area} area - this will be the first`;
                    }
                    break;
                    
                case 'all':
                    countBadge.innerHTML = `<i class="fas fa-globe mr-1"></i>${count} total`;
                    countBadge.className = 'badge badge-info';
                    countBadge.title = `${count} customers across all areas`;
                    break;
                    
                case 'error':
                    countBadge.innerHTML = '<i class="fas fa-exclamation-triangle mr-1"></i>Error';
                    countBadge.className = 'badge badge-danger';
                    countBadge.title = 'Error loading customer data';
                    break;
                    
                default:
                    countBadge.innerHTML = '<i class="fas fa-map-marker-alt mr-1"></i>Select area';
                    countBadge.className = 'badge badge-light';
                    countBadge.title = 'Choose an area to see nearby customers';
            }
        }

        // Helper function to show loading state in Select2 dropdowns
        function showSelect2Loading(selector, message) {
            const $select = $(selector);
            $select.prop('disabled', true)
                   .empty()
                   .append(`<option>${message || 'Loading...'}</option>`)
                   .trigger('change');
        }

        // Helper function to enable Select2 dropdown after loading
        function enableSelect2(selector) {
            $(selector).prop('disabled', false).trigger('change');
        }

        // Enhanced refresh function for dropdowns
        function refreshDropdownData() {
            showAlert('info', 'Refreshing dropdown data...');
            loadAreas();
            loadNearbyCustomers();
        }

        // Handle area selection to filter nearby customers
        $('#area').on('select2:select', function(e) {
            const selectedArea = e.params.data.text;
            if (selectedArea && selectedArea !== '') {
                loadCustomersByArea(selectedArea);
                // Update nearby placeholder dynamically
                const nc = $('#nearbyCustomer');
                nc.data('select2').$container.find('.select2-selection__placeholder').text('Customers in ' + selectedArea + '...');
            }
        });

        $('#area').on('select2:unselect select2:clear', function(e) {
            // Reset nearby customers when area is cleared
            resetNearbyCustomers();
            updateCustomerCount(0);
            const nc = $('#nearbyCustomer');
            if (nc.data('select2')) {
                nc.data('select2').$container.find('.select2-selection__placeholder').text('Type to search customers...');
            }
        });

        // Handle nearby customer selection with Select2
        $('#nearbyCustomer').on('select2:select', function(e) {
            const selectedData = e.params.data;
            const selectedOption = $(selectedData.element);
            
            if (selectedData.id) {
                // Auto-fill address and location from selected customer (but not area since it's already selected)
                const address = selectedOption.attr('data-address');
                const location = selectedOption.attr('data-location');
                
                if (address) {
                    document.getElementById('address').value = address;
                }
                if (location) {
                    document.getElementById('gmapLocation').value = location;
                }
                
                // Show success message
                const customerName = selectedData.text.split(' (')[0];
                showAlert('info', 'Location details filled from nearby customer "' + customerName + '"');
            }
        });

        // Clear nearby customer selection
        document.getElementById('clearNearbyBtn').addEventListener('click', function() {
            $('#nearbyCustomer').val(null).trigger('change');
            
            // Clear the auto-filled fields (optional - let user decide)
            // $('#area').val(null).trigger('change');
            // document.getElementById('address').value = '';
            // document.getElementById('gmapLocation').value = '';
            
            showAlert('info', 'Nearby customer selection cleared');
        });

        // Area management functions
        function loadAreas() {
            // Show loading state for Select2
            $('#area').prop('disabled', true).html('<option>Loading areas...</option>').trigger('change');
            
            fetch('api/areas.php')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    const contentType = response.headers.get('content-type');
                    if (!contentType || !contentType.includes('application/json')) {
                        return response.text().then(text => {
                            throw new Error('Server returned non-JSON response: ' + text.substring(0, 200));
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        const areaSelect = $('#area');
                        
                        // Store current selection
                        const currentValue = areaSelect.val();
                        
                        // Clear and rebuild options
                        areaSelect.empty().append('<option value="">Select Area</option>');
                        
                        // Add areas
                        data.areas.forEach(area => {
                            areaSelect.append(new Option(area.AreaName, area.AreaName));
                        });
                        
                        // Enable and trigger change for Select2
                        areaSelect.prop('disabled', false).trigger('change');
                        
                        // Restore selection if it still exists
                        if (currentValue) {
                            areaSelect.val(currentValue).trigger('change');
                        }
                        
                        console.log('Loaded ' + data.areas.length + ' areas via API');
                    } else {
                        console.warn('Failed to load areas:', data.message);
                        handleAreasLoadError();
                    }
                })
                .catch(error => {
                    console.error('Error loading areas via API:', error);
                    handleAreasLoadError();
                });
        }

        function handleAreasLoadError() {
            const areaSelect = $('#area');
            
            // Check if areas are already populated from server-side
            const existingOptions = areaSelect.find('option').length;
            
            if (existingOptions > 1) {
                console.log('Using server-side populated areas (' + (existingOptions - 1) + ' areas)');
                areaSelect.prop('disabled', false).trigger('change');
            } else {
                // Add some default areas only if no areas are available at all
                areaSelect.empty().append('<option value="">Select Area</option>');
                
                const defaultAreas = ['City Center', 'North Area', 'South Area'];
                defaultAreas.forEach(areaName => {
                    areaSelect.append(new Option(areaName, areaName));
                });
                
                areaSelect.prop('disabled', false).trigger('change');
                console.log('Added default areas due to loading error and no server-side areas');
            }
        }

        // Add new area button handler
        document.getElementById('addNewAreaBtn').addEventListener('click', function() {
            $('#quickAddAreaModal').modal('show');
        });

        // Quick area form submission
        document.getElementById('quickAreaForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const areaData = {
                areaName: formData.get('areaName'),
                description: formData.get('description')
            };
            
            // Show loading state
            const submitBtn = document.getElementById('quickAreaSubmitBtn');
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Saving...';
            
            fetch('api/areas.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(areaData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    return response.text().then(text => {
                        throw new Error('Server returned non-JSON response: ' + text.substring(0, 200));
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // Close modal
                    $('#quickAddAreaModal').modal('hide');
                    
                    // Reset form
                    document.getElementById('quickAreaForm').reset();
                    
                    // Reload areas
                    setTimeout(function() {
                        loadAreas();
                    }, 200);
                    
                    // Select the new area
                    setTimeout(() => {
                        document.getElementById('area').value = areaData.areaName;
                    }, 100);
                    
                    // Show success message
                    showAlert('success', 'Area added successfully!');
                } else {
                    showAlert('danger', 'Error adding area: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('danger', 'Error adding area. Please try again.');
            })
            .finally(() => {
                // Reset button
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        });

        // Show alert helper function
        function showAlert(type, message) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
            alertDiv.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} mr-2"></i>${message}
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            `;
            
            // Insert after page heading
            const pageHeading = document.querySelector('.d-sm-flex.align-items-center');
            pageHeading.parentNode.insertBefore(alertDiv, pageHeading.nextSibling);
            
            // Auto-dismiss after 5 seconds
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }

        // Modal event handlers for Select2
        $('#customerModal').on('shown.bs.modal', function() {
            // Reinitialize Select2 when modal is shown to ensure proper rendering
            $('#area, #customerType, #nearbyCustomer').select2('destroy').select2({
                dropdownParent: $('#customerModal')
            });
            
            // Reapply custom configurations
            $('#area').select2({
                placeholder: 'Select or type to search areas...',
                allowClear: true,
                dropdownParent: $('#customerModal'),
                matcher: customMatcher,
                templateResult: formatAreaOption,
                templateSelection: formatAreaSelection,
                escapeMarkup: function(markup) { return markup; }
            });
            
            $('#customerType').select2({
                placeholder: 'Select customer type...',
                allowClear: false,
                dropdownParent: $('#customerModal'),
                minimumResultsForSearch: Infinity,
                templateResult: formatCustomerTypeOption,
                templateSelection: formatCustomerTypeSelection,
                escapeMarkup: function(markup) { return markup; }
            });
            
            $('#nearbyCustomer').select2({
                placeholder: 'Type to search customers...',
                allowClear: true,
                dropdownParent: $('#customerModal'),
                matcher: customMatcher,
                templateResult: formatNearbyCustomerOption,
                templateSelection: formatNearbyCustomerSelection,
                escapeMarkup: function(markup) { return markup; }
            });
        });

        // Handle modal close to clean up Select2
        $('#customerModal').on('hidden.bs.modal', function() {
            // Clean up any Select2 instances
            $('#area, #customerType, #nearbyCustomer').select2('destroy');
        });
    </script>

    <?php if ($editCustomer): ?>
    <script>
        // Auto-populate form for editing
        $(document).ready(function() {
            editCustomer(<?php echo $editCustomer['ID']; ?>);
        });
    </script>
    <?php endif; ?>
</body>
</html>
