<?php
// get_dealers.php
require_once 'db_connect.php';
header('Content-Type: application/json');

// Check if it's a GET request
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    
    // SQL to fetch all dealers, ordered by district for better spinner sorting
    $sql = "SELECT * FROM dealers ORDER BY district ASC, name ASC";
    
    $result = $conn->query($sql);
    
    if ($result) {
        $dealers = array();
        
        while ($row = $result->fetch_assoc()) {
            // Ensure data types match your Dealer.java model
            $dealers[] = array(
                "id" => (int)$row['id'],
                "name" => $row['name'],
                "district" => $row['district'],
                "phone" => $row['phone'],
                "address" => $row['address'],
                "website" => $row['website'] // Can be null or empty string
            );
        }
        
        // Return the list directly as expected by Call<List<Dealer>>
        echo json_encode($dealers);
        
    } else {
        // If the query fails, return an empty array to prevent app crashes
        echo json_encode(array());
    }

} else {
    // Handle invalid request methods
    http_response_code(405);
    echo json_encode(array("error" => "Method Not Allowed"));
}

$conn->close();
?>