<?php
// get_local_governments.php
header('Content-Type: application/json');
include('includes/dbconnection.php');

if (!isset($_GET['state_id']) || empty($_GET['state_id'])) {
    echo json_encode(['error' => 'Missing state_id parameter']);
    exit;
}

$state_name = $_GET['state_id'];  // It's now a name, not an ID

try {
    // Fetch the state ID based on the provided state name
    $stmt = $dbh->prepare("SELECT id FROM states WHERE name = ?");
    $stmt->execute([$state_name]);
    $state = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$state) {
        echo json_encode(['error' => 'State not found']);
        exit;
    }

    $state_id = $state['id'];

    // Now fetch the LGAs for this state ID
    $stmt = $dbh->prepare("SELECT name FROM local_governments WHERE state_id = ? ORDER BY name ASC");
    $stmt->execute([$state_id]);
    $lgas = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($lgas);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
