<?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'];
    $areaName = mysqli_real_escape_string($con, trim($_POST['areaName']));
    $description = mysqli_real_escape_string($con, trim($_POST['description']));
    
    if ($action == 'create') {
        // Check if area already exists
        $checkQuery = "SELECT COUNT(*) as count FROM tblareas WHERE AreaName = '$areaName' AND IsActive = 1";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if (!$checkResult) {
            // Create tblareas table if it doesn't exist
            $createTableQuery = "CREATE TABLE IF NOT EXISTS `tblareas` (
                `ID` int(11) NOT NULL AUTO_INCREMENT,
                `AreaName` varchar(100) NOT NULL COLLATE utf8mb4_general_ci,
                `Description` text COLLATE utf8mb4_general_ci,
                `CreatedBy` int(11) NOT NULL,
                `CreatedDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                `UpdatedBy` int(11) DEFAULT NULL,
                `UpdatedDate` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
                `IsActive` tinyint(1) NOT NULL DEFAULT 1,
                PRIMARY KEY (`ID`),
                UNIQUE KEY `unique_area_name` (`AreaName`),
                KEY `idx_area_name` (`AreaName`),
                KEY `idx_is_active` (`IsActive`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci";
            
            mysqli_query($con, $createTableQuery);
            
            // Try the check query again
            $checkResult = mysqli_query($con, $checkQuery);
        }
        
        $existingCount = mysqli_fetch_assoc($checkResult)['count'];
        
        if ($existingCount > 0) {
            $error = "Area name already exists!";
        } else {
            $insertQuery = "INSERT INTO tblareas (AreaName, Description, CreatedBy) 
                           VALUES ('$areaName', '$description', '$userId')";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "Area added successfully!";
            } else {
                $error = "Error adding area: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $areaId = (int)$_POST['areaId'];
        
        // Check if area name already exists for other areas
        $checkQuery = "SELECT COUNT(*) as count FROM tblareas WHERE AreaName = '$areaName' AND ID != $areaId AND IsActive = 1";
        $checkResult = mysqli_query($con, $checkQuery);
        $existingCount = mysqli_fetch_assoc($checkResult)['count'];
        
        if ($existingCount > 0) {
            $error = "Area name already exists!";
        } else {
            $updateQuery = "UPDATE tblareas SET 
                           AreaName = '$areaName',
                           Description = '$description',
                           UpdatedBy = '$userId',
                           UpdatedDate = NOW()
                           WHERE ID = $areaId";
            
            if (mysqli_query($con, $updateQuery)) {
                $success = "Area updated successfully!";
            } else {
                $error = "Error updating area: " . mysqli_error($con);
            }
        }
    }
}

// Handle delete action
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $areaId = (int)$_GET['delete'];
    
    // Check if area is being used by any customers (with collation fix)
    $customerCheckQuery = "SELECT COUNT(*) as count FROM tblcustomers c 
                          INNER JOIN tblareas a ON c.Area COLLATE utf8mb4_general_ci = a.AreaName COLLATE utf8mb4_general_ci 
                          WHERE a.ID = $areaId AND c.IsActive = 1";
    $customerCheckResult = mysqli_query($con, $customerCheckQuery);
    $customerCount = mysqli_fetch_assoc($customerCheckResult)['count'];
    
    if ($customerCount > 0) {
        $error = "Cannot delete area. It is being used by $customerCount customers.";
    } else {
        $deleteQuery = "UPDATE tblareas SET IsActive = 0, UpdatedBy = '$userId', UpdatedDate = NOW() WHERE ID = $areaId";
        
        if (mysqli_query($con, $deleteQuery)) {
            $success = "Area deleted successfully!";
        } else {
            $error = "Error deleting area: " . mysqli_error($con);
        }
    }
}

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

// Fetch all areas 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']) : '';

// Ensure tblareas table exists
$checkTableQuery = "SHOW TABLES LIKE 'tblareas'";
$tableExists = mysqli_query($con, $checkTableQuery) && mysqli_num_rows(mysqli_query($con, $checkTableQuery)) > 0;

if (!$tableExists) {
    // Create table
    $createTableQuery = "CREATE TABLE IF NOT EXISTS `tblareas` (
        `ID` int(11) NOT NULL AUTO_INCREMENT,
        `AreaName` varchar(100) NOT NULL COLLATE utf8mb4_general_ci,
        `Description` text COLLATE utf8mb4_general_ci,
        `CreatedBy` int(11) NOT NULL,
        `CreatedDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        `UpdatedBy` int(11) DEFAULT NULL,
        `UpdatedDate` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
        `IsActive` tinyint(1) NOT NULL DEFAULT 1,
        PRIMARY KEY (`ID`),
        UNIQUE KEY `unique_area_name` (`AreaName`),
        KEY `idx_area_name` (`AreaName`),
        KEY `idx_is_active` (`IsActive`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci";
    
    mysqli_query($con, $createTableQuery);
}

$whereClause = "WHERE a.IsActive = 1";
if (!empty($searchTerm)) {
    $whereClause .= " AND (a.AreaName LIKE '%$searchTerm%' OR a.Description LIKE '%$searchTerm%')";
}

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

// Fetch areas (with collation fix for customer count)
$areasQuery = "SELECT a.*, u.FullName as CreatedByName, u2.FullName as UpdatedByName,
               (SELECT COUNT(*) FROM tblcustomers WHERE Area COLLATE utf8mb4_general_ci = a.AreaName COLLATE utf8mb4_general_ci AND IsActive = 1) as CustomerCount
               FROM tblareas a 
               LEFT JOIN tblusers u ON a.CreatedBy = u.ID 
               LEFT JOIN tblusers u2 ON a.UpdatedBy = u2.ID 
               $whereClause 
               ORDER BY a.AreaName ASC 
               LIMIT $offset, $recordsPerPage";
$areasResult = mysqli_query($con, $areasQuery);

// Get statistics (with collation fix)
$statsQuery = "SELECT 
    COUNT(*) as TotalAreas,
    (SELECT COUNT(*) FROM tblareas WHERE IsActive = 1 AND CreatedDate >= DATE_SUB(NOW(), INTERVAL 30 DAY)) as NewAreasThisMonth,
    (SELECT COUNT(DISTINCT Area COLLATE utf8mb4_general_ci) FROM tblcustomers WHERE IsActive = 1) as AreasWithCustomers
    FROM tblareas WHERE IsActive = 1";
$statsResult = mysqli_query($con, $statsQuery);
$stats = $statsResult ? mysqli_fetch_assoc($statsResult) : ['TotalAreas' => 0, 'NewAreasThisMonth' => 0, 'AreasWithCustomers' => 0];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Area 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">
    <style>
        .area-card {
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .area-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
        }
        .modal-header { 
            background: linear-gradient(45deg, #4e73df, #36b9cc); 
            color: white; 
        }
        .required { 
            color: red; 
        }
        
        /* Compact design */
        .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; 
        }
        
        /* Area Grid Layout */
        .area-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .area-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;
        }
        
        .area-grid-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .area-header {
            padding: 1rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            position: relative;
        }
        
        .area-icon {
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            font-size: 1.2rem;
            opacity: 0.7;
        }
        
        .area-name {
            font-size: 1.1rem;
            font-weight: 600;
            margin: 0;
            line-height: 1.2;
            padding-right: 2rem;
        }
        
        .area-id {
            font-size: 0.8rem;
            opacity: 0.8;
            margin: 0.25rem 0 0 0;
        }
        
        .area-body {
            padding: 1rem;
        }
        
        .area-info {
            margin-bottom: 0.75rem;
        }
        
        .area-info-item {
            display: flex;
            align-items: flex-start;
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
        }
        
        .area-info-item i {
            width: 16px;
            margin-right: 0.5rem;
            color: #5a5c69;
            margin-top: 0.1rem;
        }
        
        .area-description {
            color: #6c757d;
            font-style: italic;
            line-height: 1.4;
        }
        
        .area-customer-count {
            background: #e3f2fd;
            color: #1976d2;
            padding: 0.25rem 0.5rem;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 600;
            display: inline-block;
        }
        
        .area-actions {
            border-top: 1px solid #e3e6f0;
            padding: 0.75rem 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .area-date {
            font-size: 0.8rem;
            color: #858796;
        }
        
        .view-toggle {
            margin-bottom: 1rem;
        }
        
        @media (max-width: 768px) {
            .area-grid {
                grid-template-columns: 1fr;
                gap: 0.75rem;
            }
            .area-header, .area-body, .area-actions {
                padding: 0.75rem;
            }
            .area-info-item {
                font-size: 0.85rem;
            }
            .form-group { 
                margin-bottom: 0.5rem; 
            }
            .modal-body { 
                padding: 1rem; 
            }
        }
        
        /* 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;
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            color: #6c757d;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 1rem;
            color: #dee2e6;
        }
    </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-map-marker-alt text-primary mr-2"></i>
                            Area Management
                        </h1>
                        <div>
                            <a href="customer-areas.php" class="btn btn-success mr-2">
                                <i class="fas fa-eye mr-2"></i>View Customer Areas
                            </a>
                            <button class="btn btn-primary" data-toggle="modal" data-target="#areaModal" onclick="clearForm()">
                                <i class="fas fa-plus mr-2"></i>Add New Area
                            </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">
                                <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 Areas</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['TotalAreas']); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-map-marker-alt 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">
                                <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">
                                                Areas with Customers</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['AreasWithCustomers']); ?>
                                            </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-info shadow h-100 py-2 stats-card">
                                <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">
                                                New Areas This Month</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['NewAreasThisMonth']); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-calendar-plus 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">
                                <div class="col-md-4 mb-2">
                                    <input type="text" class="form-control form-control-sm" name="search" 
                                           placeholder="Search areas..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                                </div>
                                <div class="col-md-5 mb-2">
                                    <div class="btn-group" role="group">
                                        <button type="submit" class="btn btn-primary btn-sm">
                                            <i class="fas fa-search mr-1"></i>Search
                                        </button>
                                        <a href="area-management.php" class="btn btn-secondary btn-sm">
                                            <i class="fas fa-times mr-1"></i>Clear
                                        </a>
                                        <button type="button" class="btn btn-success btn-sm" onclick="exportAreas()">
                                            <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>
                        </div>
                    </div>

                    <!-- Area Grid View -->
                    <div id="gridView">
                        <?php if ($areasResult && mysqli_num_rows($areasResult) > 0): ?>
                        <div class="area-grid">
                            <?php while($area = mysqli_fetch_assoc($areasResult)): ?>
                            <div class="area-grid-item">
                                <div class="area-header">
                                    <div class="area-icon">
                                        <i class="fas fa-map-marker-alt"></i>
                                    </div>
                                    <h6 class="area-name"><?php echo htmlspecialchars($area['AreaName']); ?></h6>
                                    <p class="area-id">ID: <?php echo $area['ID']; ?></p>
                                </div>
                                <div class="area-body">
                                    <div class="area-info">
                                        <?php if (!empty($area['Description'])): ?>
                                        <div class="area-info-item">
                                            <i class="fas fa-info-circle"></i>
                                            <span class="area-description"><?php echo htmlspecialchars($area['Description']); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        <div class="area-info-item">
                                            <i class="fas fa-users"></i>
                                            <span class="area-customer-count">
                                                <?php echo $area['CustomerCount']; ?> 
                                                <?php echo $area['CustomerCount'] == 1 ? 'Customer' : 'Customers'; ?>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="area-actions">
                                    <div class="area-date">
                                        <?php echo date('M j, Y', strtotime($area['CreatedDate'])); ?>
                                    </div>
                                    <div class="btn-group btn-group-sm" role="group">
                                        <a href="customer-areas.php?area=<?php echo urlencode($area['AreaName']); ?>&type=Retail" 
                                           class="btn btn-outline-info btn-sm"
                                           title="View Customers">
                                            <i class="fas fa-users"></i>
                                        </a>
                                        <button class="btn btn-outline-primary" 
                                                onclick="editArea(<?php echo $area['ID']; ?>)"
                                                title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-outline-danger" 
                                                onclick="deleteArea(<?php echo $area['ID']; ?>, '<?php echo htmlspecialchars($area['AreaName']); ?>', <?php echo $area['CustomerCount']; ?>)"
                                                title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <?php endwhile; ?>
                        </div>
                        <?php else: ?>
                        <div class="empty-state">
                            <i class="fas fa-map-marker-alt"></i>
                            <h4>No Areas Found</h4>
                            <p>No areas have been created yet. Click "Add New Area" to get started.</p>
                            <button class="btn btn-primary" data-toggle="modal" data-target="#areaModal" onclick="clearForm()">
                                <i class="fas fa-plus mr-2"></i>Create First Area
                            </button>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Areas 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>Area List
                                <span class="text-muted">(<?php echo $totalRecords; ?> total)</span>
                            </h6>
                        </div>
                        <div class="card-body p-0">
                            <?php if ($areasResult && mysqli_num_rows($areasResult) > 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>Area Name</th>
                                            <th>Description</th>
                                            <th>Customers</th>
                                            <th>Created Date</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        mysqli_data_seek($areasResult, 0);
                                        $counter = $offset + 1;
                                        while($area = mysqli_fetch_assoc($areasResult)): 
                                        ?>
                                        <tr>
                                            <td><?php echo $counter++; ?></td>
                                            <td>
                                                <strong><?php echo htmlspecialchars($area['AreaName']); ?></strong>
                                                <br><small class="text-muted">ID: <?php echo $area['ID']; ?></small>
                                            </td>
                                            <td>
                                                <?php if (!empty($area['Description'])): ?>
                                                    <span class="text-muted"><?php echo htmlspecialchars($area['Description']); ?></span>
                                                <?php else: ?>
                                                    <span class="text-muted font-italic">No description</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <a href="customer-areas.php?area=<?php echo urlencode($area['AreaName']); ?>&type=Retail" 
                                                   class="badge badge-primary px-2 py-1">
                                                    <i class="fas fa-users mr-1"></i>
                                                    <?php echo $area['CustomerCount']; ?> customers
                                                </a>
                                            </td>
                                            <td>
                                                <small><?php echo date('M j, Y', strtotime($area['CreatedDate'])); ?></small>
                                                <br><small class="text-muted">by <?php echo htmlspecialchars($area['CreatedByName']); ?></small>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm" role="group">
                                                    <button class="btn btn-outline-primary" 
                                                            onclick="editArea(<?php echo $area['ID']; ?>)"
                                                            title="Edit">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button class="btn btn-outline-danger" 
                                                            onclick="deleteArea(<?php echo $area['ID']; ?>, '<?php echo htmlspecialchars($area['AreaName']); ?>', <?php echo $area['CustomerCount']; ?>)"
                                                            title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php else: ?>
                            <div class="empty-state">
                                <i class="fas fa-map-marker-alt"></i>
                                <h4>No Areas Found</h4>
                                <p>No areas match your search criteria.</p>
            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                    <nav aria-label="Area 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); ?>">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); ?>"><?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); ?>">Next</a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>

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

    <!-- Area Modal -->
    <div class="modal fade" id="areaModal" tabindex="-1" role="dialog" aria-labelledby="areaModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="areaModalLabel">
                        <i class="fas fa-map-marker-alt 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 method="POST" id="areaForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" id="formAction" value="create">
                        <input type="hidden" name="areaId" id="areaId">
                        
                        <div class="form-group">
                            <label for="areaName">Area Name <span class="required">*</span></label>
                            <input type="text" class="form-control" id="areaName" name="areaName" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="description">Description <small class="text-muted">(Optional)</small></label>
                            <textarea class="form-control" id="description" name="description" rows="3" 
                                      placeholder="Enter area description, landmarks, or additional details..."></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-primary" id="submitBtn">
                            <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="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.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 = 'block';
                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('areaViewPreference', view);
        }
        
        // Load view preference on page load
        document.addEventListener('DOMContentLoaded', function() {
            const savedView = localStorage.getItem('areaViewPreference') || 'grid';
            toggleView(savedView);
        });

        function clearForm() {
            document.getElementById('areaForm').reset();
            document.getElementById('formAction').value = 'create';
            document.getElementById('areaId').value = '';
            document.getElementById('areaModalLabel').innerHTML = '<i class="fas fa-map-marker-alt mr-2"></i>Add New Area';
            document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Save Area';
        }

        function editArea(areaId) {
            // Fetch area data via AJAX
            fetch('api/areas.php?id=' + areaId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('formAction').value = 'update';
                        document.getElementById('areaId').value = data.area.ID;
                        document.getElementById('areaName').value = data.area.AreaName;
                        document.getElementById('description').value = data.area.Description || '';
                        
                        document.getElementById('areaModalLabel').innerHTML = '<i class="fas fa-edit mr-2"></i>Edit Area';
                        document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Update Area';
                        
                        $('#areaModal').modal('show');
                    } else {
                        alert('Error fetching area data: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error fetching area data');
                });
        }

        function deleteArea(areaId, areaName, customerCount) {
            if (customerCount > 0) {
                alert(`Cannot delete "${areaName}". This area has ${customerCount} customers. Please move or delete the customers first.`);
                return;
            }
            
            if (confirm(`Are you sure you want to delete area "${areaName}"? This action cannot be undone.`)) {
                window.location.href = 'area-management.php?delete=' + areaId;
            }
        }

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

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

        // Initialize tooltips
        $(function () {
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>

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