<?php
require_once 'config.php';

// Get search parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$area_filter = isset($_GET['area']) ? (int)$_GET['area'] : 0;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10; // Items per page

// Validate page number
if ($page < 1) {
    $page = 1;
}

// Calculate offset for pagination
$offset = ($page - 1) * $per_page;

// Build the base query with JOIN
$query = "SELECT 
            ci.c_id, 
            ci.client_name, 
            ci.address, 
            ci.mobile_number, 
            ci.area_id,
            a.area_name
          FROM customer_info ci
          LEFT JOIN area a ON ci.area_id = a.id
          WHERE 1=1";

$count_query = "SELECT COUNT(*) as total 
                FROM customer_info ci
                LEFT JOIN area a ON ci.area_id = a.id
                WHERE 1=1";

$params = [];
$count_params = [];

// Add search conditions if search term exists
if (!empty($search)) {
    $query .= " AND (ci.client_name LIKE :search OR ci.address LIKE :search OR ci.mobile_number LIKE :search)";
    $count_query .= " AND (ci.client_name LIKE :search OR ci.address LIKE :search OR ci.mobile_number LIKE :search)";
    $params[':search'] = "%$search%";
    $count_params[':search'] = "%$search%";
}

// Add area filter if selected
if ($area_filter > 0) {
    $query .= " AND ci.area_id = :area_id";
    $count_query .= " AND ci.area_id = :area_id";
    $params[':area_id'] = $area_filter;
    $count_params[':area_id'] = $area_filter;
}

// Add sorting and pagination
$query .= " ORDER BY ci.client_name ASC LIMIT :limit OFFSET :offset";
$params[':limit'] = $per_page;
$params[':offset'] = $offset;

// Get areas for filter dropdown
$areas_stmt = $pdo->query("SELECT id, area_name FROM area ORDER BY area_name");
$areas = $areas_stmt->fetchAll(PDO::FETCH_ASSOC);

// Execute count query first
$stmt = $pdo->prepare($count_query);
foreach ($count_params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->execute();
$total_count = $stmt->fetchColumn();

// Calculate total pages
$total_pages = ceil($total_count / $per_page);

// Execute main query
$stmt = $pdo->prepare($query);
foreach ($params as $key => $value) {
    if ($key === ':limit' || $key === ':offset') {
        $stmt->bindValue($key, $value, PDO::PARAM_INT);
    } else {
        $stmt->bindValue($key, $value);
    }
}
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Search</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .search-form {
            background: #f5f5f5;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        button {
            background: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        button:hover {
            background: #0056b3;
        }
        .clear-btn {
            background: #6c757d;
            margin-left: 10px;
            padding: 10px 20px;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            display: inline-block;
        }
        .clear-btn:hover {
            background: #545b62;
        }
        .results-count {
            margin: 20px 0;
            font-size: 16px;
            color: #666;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #e9ecef;
        }
        .sr-no {
            text-align: center;
            width: 80px;
        }
        .pagination {
            display: flex;
            justify-content: center;
            margin: 20px 0;
        }
        .pagination a, .pagination span {
            padding: 8px 16px;
            margin: 0 4px;
            border: 1px solid #ddd;
            text-decoration: none;
            color: #007bff;
            border-radius: 4px;
        }
        .pagination span.current {
            background-color: #007bff;
            color: white;
            border: 1px solid #007bff;
        }
        .pagination a:hover {
            background-color: #ddd;
        }
        .no-results {
            text-align: center;
            padding: 40px;
            color: #666;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Customer Search</h1>
        
        <!-- Search Form -->
        <form method="GET" action="" class="search-form">
            <div class="form-group">
                <label for="search">Search Customers:</label>
                <input type="text" name="search" id="search" 
                       value="<?php echo htmlspecialchars($search); ?>" 
                       placeholder="Search by name, address, or mobile number">
            </div>
            
            <div class="form-group">
                <label for="area">Filter by Area:</label>
                <select name="area" id="area">
                    <option value="0">All Areas</option>
                    <?php foreach ($areas as $area): ?>
                        <option value="<?php echo $area['id']; ?>" 
                            <?php echo $area_filter == $area['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($area['area_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <button type="submit">Search</button>
            <a href="customers.php" class="clear-btn">Clear Filters</a>
        </form>

        <!-- Results Count -->
        <div class="results-count">
            Found <?php echo $total_count; ?> customer(s)
        </div>

        <!-- Results Table -->
        <?php if (!empty($results)): ?>
            <table>
                <thead>
                    <tr>
                        <th class="sr-no">SL No.</th>
                        <th>Client Name</th>
                        <th>Address</th>
                        <th>Mobile Number</th>
                        <th>Area</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    // Calculate starting serial number based on current page
                    $serial_number = ($page - 1) * $per_page + 1;
                    foreach ($results as $row): ?>
                        <tr>
                            <td class="sr-no"><?php echo $serial_number; ?></td>
                            <td><?php echo htmlspecialchars($row['client_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['address']); ?></td>
                            <td><?php echo htmlspecialchars($row['mobile_number']); ?></td>
                            <td><?php echo htmlspecialchars($row['area_name'] ?? 'N/A'); ?></td>
                        </tr>
                    <?php 
                    $serial_number++;
                    endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="no-results">
                No customers found matching your search criteria.
            </div>
        <?php endif; ?>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="pagination">
                <!-- Previous Page -->
                <?php if ($page > 1): ?>
                    <a href="?search=<?php echo urlencode($search); ?>&area=<?php echo $area_filter; ?>&page=<?php echo $page - 1; ?>">Previous</a>
                <?php endif; ?>

                <!-- Page Numbers -->
                <?php 
                // Show limited page numbers around current page
                $start_page = max(1, $page - 2);
                $end_page = min($total_pages, $start_page + 4);
                $start_page = max(1, $end_page - 4);
                
                for ($i = $start_page; $i <= $end_page; $i++): ?>
                    <?php if ($i == $page): ?>
                        <span class="current"><?php echo $i; ?></span>
                    <?php else: ?>
                        <a href="?search=<?php echo urlencode($search); ?>&area=<?php echo $area_filter; ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                    <?php endif; ?>
                <?php endfor; ?>

                <!-- Next Page -->
                <?php if ($page < $total_pages): ?>
                    <a href="?search=<?php echo urlencode($search); ?>&area=<?php echo $area_filter; ?>&page=<?php echo $page + 1; ?>">Next</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>