<?php
/**
 * API: Get LGAs by State ID
 */

error_reporting(E_ALL);
ini_set('display_headers', 1);
header('Content-Type: application/json');

// Include configuration
require_once __DIR__ . '/../config/config.php';

// Check if user is logged in
if (!isLoggedIn()) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Get state ID from request
$stateId = isset($_GET['state_id']) ? intval($_GET['state_id']) : 0;

if (!$stateId) {
    echo json_encode([]);
    exit;
}

// Get database connection
$pdo = getDBConnection();
if (!$pdo) {
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

try {
    // Prepare and execute query
    $stmt = $pdo->prepare("SELECT id, lga_name FROM lgas WHERE state_id = ? ORDER BY lga_name ASC");
    $stmt->execute([$stateId]);
    $lgas = $stmt->fetchAll();
    
    // Return JSON response
    echo json_encode($lgas);
    
} catch (PDOException $e) {
    error_log("Error fetching LGAs: " . $e->getMessage());
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}