<?php
header('Content-Type: application/json');
include 'db_connect.php';
$conn = getDbConnection();

$query = $_GET['query'] ?? ''; // Get search query from URL

// 1. Explicitly list all columns needed by the Android Customer model
$sql = "SELECT 
            id, 
            name, 
            mobile_number, 
            product_label, 
            category, 
            note, 
            is_sent, 
            sent_date 
        FROM customers";

$params = [];
$types = '';

if (!empty($query)) {
    // 🟢 UPDATED: Search across 5 fields (name, mobile_number, product_label, category, note)
    $sql .= " WHERE name LIKE ? OR mobile_number LIKE ? OR product_label LIKE ? OR category LIKE ? OR note LIKE ?";
    
    $search_param = "%" . $query . "%";
    
    // 5 parameters for the 5 LIKE clauses
    $params = [$search_param, $search_param, $search_param, $search_param, $search_param];
    $types = 'sssss'; // 5 string types
}

// 2. Order the results
$sql .= " ORDER BY id DESC";

$stmt = $conn->prepare($sql);

if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

$customers = [];
while ($row = $result->fetch_assoc()) {
    
    // 3. Map database snake_case keys to Android model camelCase keys for correct deserialization
    $customer_data = [
        'id' => $row['id'],
        'name' => $row['name'],
        'mobileNumber' => $row['mobile_number'], 
        'productLabel' => $row['product_label'], 
        'category' => $row['category'], 
        'note' => $row['note'], 
        'isSent' => (bool)$row['is_sent'], 
        'sentDate' => $row['sent_date']
    ];
    
    $customers[] = $customer_data; 
}

echo json_encode($customers);

$stmt->close();
$conn->close();
?>