<?php
// get_area.php: return a single area by id as JSON

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid area id']);
    exit;
}

try {
    // 1) Load the area row
    $stmt = $pdo->prepare("
        SELECT 
            Id,
            Name,
            Description,
            BasePricePerPlot,
            MinPricePerPlot,
            MaxPricePerPlot,
            DevelopmentType,
            Configurations,
            Category,
            ProjectStatus,
            Slug
        FROM Areas
        WHERE Id = :id
        LIMIT 1
    ");
    $stmt->execute([':id' => $id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        http_response_code(404);
        echo json_encode(['error' => 'Area not found']);
        exit;
    }

    // Normalize base price like get_areas.php
    $rawBase = $row['BasePricePerPlot'] ?? null;
    $basePrice = ($rawBase === null || $rawBase === '') ? null : (float)$rawBase;

    $area = [
        'Id' => (int)$row['Id'],
        'Name' => $row['Name'] ?? '',
        'Description' => $row['Description'] ?? '',
        'BasePricePerPlot' => $basePrice,
        'MinPrice' => $row['MinPricePerPlot'] ?? null,
        'MaxPrice' => $row['MaxPricePerPlot'] ?? null,
        'DevelopmentType' => $row['DevelopmentType'] ?? '',
        'Configurations' => $row['Configurations'] ?? '',
        'Category' => $row['Category'] ?? 'Residential',
        'ProjectStatus' => $row['ProjectStatus'] ?? 'Ongoing',
        'Slug' => $row['Slug'] ?? ''
    ];

    // 2) Load images from AreaImages
    $imgStmt = $pdo->prepare("
        SELECT ViewType, FilePath
        FROM AreaImages
        WHERE AreaId = :areaId
        ORDER BY SortOrder ASC, Id ASC
    ");
    $imgStmt->execute([':areaId' => $id]);
    $images = $imgStmt->fetchAll(PDO::FETCH_ASSOC);

    // Map specific views + extra list
    $baseUrl = '/uploads/areas/'; // adjust if different
    $layout = null;
    $front  = null;
    $left   = null;
    $right  = null;
    $side   = null;
    $extra  = [];

    foreach ($images as $img) {
        $url = $baseUrl . $img['FilePath'];
        switch ($img['ViewType']) {
            case 'Layout':
                if (!$layout) $layout = $url;
                break;
            case 'Front':
                if (!$front) $front = $url;
                break;
            case 'Left':
                if (!$left) $left = $url;
                break;
            case 'Right':
                if (!$right) $right = $url;
                break;
            case 'Side':
                if (!$side) $side = $url;
                break;
            default:
                $extra[] = $url;
                break;
        }
    }

    $area['LayoutImageUrl'] = $layout;
    $area['FrontImageUrl']  = $front;
    $area['LeftImageUrl']   = $left;
    $area['RightImageUrl']  = $right;
    $area['SideImageUrl']   = $side;
    $area['ExtraImages']    = $extra;

    echo json_encode($area);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Failed to load area',
        'details' => $e->getMessage()
    ]);
}
