<?php
/**
 * ============================================================================
 * API: Location Hierarchy
 * Handles fetching of regions, districts, subcounties, parishes, and villages
 * File: api/locations.php
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json');

$database = new Database();
$db = $database->getConnection();

$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    switch ($action) {
        case 'get_regions':
            getRegions($db);
            break;
            
        case 'get_districts':
            getDistricts($db);
            break;
            
        case 'get_subcounties':
            getSubcounties($db);
            break;
            
        case 'get_parishes':
            getParishes($db);
            break;
            
        case 'get_villages':
            getVillages($db);
            break;
            
        case 'get_location_details':
            getLocationDetails($db);
            break;
            
        default:
            jsonError('Invalid action', 400);
    }
} catch (Exception $e) {
    logError('Location API Error: ' . $e->getMessage());
    jsonError('An error occurred', 500);
}

/**
 * Get all regions
 */
function getRegions($db) {
    try {
        $sql = "SELECT id, region_name, region_code FROM regions ORDER BY region_name";
        $stmt = $db->query($sql);
        $regions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        jsonSuccess('Regions retrieved successfully', $regions);
    } catch (PDOException $e) {
        logError('Get Regions Error: ' . $e->getMessage());
        jsonError('Failed to fetch regions');
    }
}

/**
 * Get districts by region
 */
function getDistricts($db) {
    $regionId = $_GET['region_id'] ?? $_POST['region_id'] ?? null;
    
    try {
        if ($regionId) {
            $sql = "SELECT id, district_name, district_code 
                    FROM districts 
                    WHERE region_id = ? 
                    ORDER BY district_name";
            $stmt = $db->prepare($sql);
            $stmt->execute([$regionId]);
        } else {
            $sql = "SELECT id, district_name, district_code, region_id 
                    FROM districts 
                    ORDER BY district_name";
            $stmt = $db->query($sql);
        }
        
        $districts = $stmt->fetchAll(PDO::FETCH_ASSOC);
        jsonSuccess('Districts retrieved successfully', $districts);
        
    } catch (PDOException $e) {
        logError('Get Districts Error: ' . $e->getMessage());
        jsonError('Failed to fetch districts');
    }
}

/**
 * Get subcounties by district
 */
function getSubcounties($db) {
    $districtId = $_GET['district_id'] ?? $_POST['district_id'] ?? null;
    
    if (!$districtId) {
        jsonError('District ID is required');
    }
    
    try {
        $sql = "SELECT id, subcounty_name, subcounty_code 
                FROM subcounties 
                WHERE district_id = ? 
                ORDER BY subcounty_name";
        $stmt = $db->prepare($sql);
        $stmt->execute([$districtId]);
        $subcounties = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        jsonSuccess('Subcounties retrieved successfully', $subcounties);
        
    } catch (PDOException $e) {
        logError('Get Subcounties Error: ' . $e->getMessage());
        jsonError('Failed to fetch subcounties');
    }
}

/**
 * Get parishes by subcounty
 */
function getParishes($db) {
    $subcountyId = $_GET['subcounty_id'] ?? $_POST['subcounty_id'] ?? null;
    
    if (!$subcountyId) {
        jsonError('Subcounty ID is required');
    }
    
    try {
        $sql = "SELECT id, parish_name, parish_code 
                FROM parishes 
                WHERE subcounty_id = ? 
                ORDER BY parish_name";
        $stmt = $db->prepare($sql);
        $stmt->execute([$subcountyId]);
        $parishes = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        jsonSuccess('Parishes retrieved successfully', $parishes);
        
    } catch (PDOException $e) {
        logError('Get Parishes Error: ' . $e->getMessage());
        jsonError('Failed to fetch parishes');
    }
}

/**
 * Get villages by parish
 */
function getVillages($db) {
    $parishId = $_GET['parish_id'] ?? $_POST['parish_id'] ?? null;
    
    if (!$parishId) {
        jsonError('Parish ID is required');
    }
    
    try {
        $sql = "SELECT id, village_name, village_code 
                FROM villages 
                WHERE parish_id = ? 
                ORDER BY village_name";
        $stmt = $db->prepare($sql);
        $stmt->execute([$parishId]);
        $villages = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        jsonSuccess('Villages retrieved successfully', $villages);
        
    } catch (PDOException $e) {
        logError('Get Villages Error: ' . $e->getMessage());
        jsonError('Failed to fetch villages');
    }
}

/**
 * Get complete location details
 */
function getLocationDetails($db) {
    $villageId = $_GET['village_id'] ?? $_POST['village_id'] ?? null;
    
    if (!$villageId) {
        jsonError('Village ID is required');
    }
    
    try {
        $sql = "SELECT 
                    r.id as region_id, r.region_name,
                    d.id as district_id, d.district_name,
                    s.id as subcounty_id, s.subcounty_name,
                    p.id as parish_id, p.parish_name,
                    v.id as village_id, v.village_name
                FROM villages v
                JOIN parishes p ON v.parish_id = p.id
                JOIN subcounties s ON p.subcounty_id = s.id
                JOIN districts d ON s.district_id = d.id
                JOIN regions r ON d.region_id = r.id
                WHERE v.id = ?";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$villageId]);
        $location = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($location) {
            jsonSuccess('Location details retrieved successfully', $location);
        } else {
            jsonError('Location not found', 404);
        }
        
    } catch (PDOException $e) {
        logError('Get Location Details Error: ' . $e->getMessage());
        jsonError('Failed to fetch location details');
    }
}
?>