<?php
// add_area.php: insert a new area and optional images from JSON body

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: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    echo json_encode(['status' => 'ok']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

// Read JSON payload
$raw  = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid JSON payload']);
    exit;
}

/**
 * Helpers to safely get scalar values
 */
function safe_string($data, $key, $default = '')
{
    if (!array_key_exists($key, $data) || is_array($data[$key])) {
        return $default;
    }
    return trim((string)$data[$key]);
}

function safe_scalar($data, $key, $default = null)
{
    if (!array_key_exists($key, $data) || is_array($data[$key])) {
        return $default;
    }
    return $data[$key];
}

// Basic fields (safe)
$name            = safe_string($data, 'name', '');
$description     = safe_string($data, 'description', '');
$basePrice       = safe_scalar($data, 'basePrice', null);
$minPrice        = safe_scalar($data, 'minPrice', null);
$maxPrice        = safe_scalar($data, 'maxPrice', null);
$developmentType = safe_string($data, 'developmentType', '');
$configurations  = safe_string($data, 'configurations', '');
$category        = safe_scalar($data, 'category', 'Residential');
$projectStatus   = safe_scalar($data, 'projectStatus', 'Ongoing');
$showOnWebsite   = safe_scalar($data, 'showOnWebsite', '1'); // reserved for future

// Image paths (these should be URLs or relative paths, provided by your upload logic)
$layoutImage = safe_string($data, 'layoutImage', '');
$frontImage  = safe_string($data, 'frontImage', '');
$leftImage   = safe_string($data, 'leftImage', '');
$rightImage  = safe_string($data, 'rightImage', '');
$sideImage   = safe_string($data, 'sideImage', '');

// Extra images must be an array of strings
$extraImagesRaw = $data['extraImages'] ?? [];
$extraImages    = [];
if (is_array($extraImagesRaw)) {
    foreach ($extraImagesRaw as $img) {
        if (!is_array($img)) {
            $img = trim((string)$img);
            if ($img !== '') {
                $extraImages[] = $img;
            }
        }
    }
}

// Basic validation
if ($name === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Area name is required.']);
    exit;
}

// Accept numeric including 0; still reject empty / non-numeric
if ($basePrice === null || $basePrice === '' || !is_numeric($basePrice)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Base price is required.']);
    exit;
}

// Normalize numbers
$basePriceNum = (float)$basePrice;
$minPriceNum  = ($minPrice !== null && $minPrice !== '' && is_numeric($minPrice)) ? (float)$minPrice : null;
$maxPriceNum  = ($maxPrice !== null && $maxPrice !== '' && is_numeric($maxPrice)) ? (float)$maxPrice : null;

try {
    $pdo->beginTransaction();

    // Insert into Areas
    $stmt = $pdo->prepare("
        INSERT INTO Areas (
            Name,
            Description,
            BasePricePerPlot,
            MinPricePerPlot,
            MaxPricePerPlot,
            DevelopmentType,
            Configurations,
            Category,
            ProjectStatus,
            Slug
        ) VALUES (
            :Name,
            :Description,
            :BasePricePerPlot,
            :MinPricePerPlot,
            :MaxPricePerPlot,
            :DevelopmentType,
            :Configurations,
            :Category,
            :ProjectStatus,
            :Slug
        )
    ");

    // Simple slug: lowercase-dash name
    $slug = strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $name), '-'));

    $stmt->execute([
        ':Name'             => $name,
        ':Description'      => $description !== '' ? $description : null,
        // If 0, store NULL in DB
        ':BasePricePerPlot' => ($basePriceNum == 0 ? null : $basePriceNum),
        ':MinPricePerPlot'  => $minPriceNum,
        ':MaxPricePerPlot'  => $maxPriceNum,
        ':DevelopmentType'  => $developmentType !== '' ? $developmentType : null,
        ':Configurations'   => $configurations !== '' ? $configurations : null,
        ':Category'         => $category,
        ':ProjectStatus'    => $projectStatus,
        ':Slug'             => $slug
    ]);

    $areaId = (int)$pdo->lastInsertId();

    // Helper to insert one AreaImages record
    $imgStmt = $pdo->prepare("
        INSERT INTO AreaImages (AreaId, ViewType, Title, FilePath, SortOrder)
        VALUES (:AreaId, :ViewType, :Title, :FilePath, :SortOrder)
    ");

    $order = 1;

    // Layout
    if ($layoutImage !== '') {
        $imgStmt->execute([
            ':AreaId'   => $areaId,
            ':ViewType' => 'Layout',
            ':Title'    => 'Site Layout',
            ':FilePath' => $layoutImage,
            ':SortOrder'=> $order++
        ]);
    }

    // Front
    if ($frontImage !== '') {
        $imgStmt->execute([
            ':AreaId'   => $areaId,
            ':ViewType' => 'Front',
            ':Title'    => 'Front View',
            ':FilePath' => $frontImage,
            ':SortOrder'=> $order++
        ]);
    }

    // Left
    if ($leftImage !== '') {
        $imgStmt->execute([
            ':AreaId'   => $areaId,
            ':ViewType' => 'Left',
            ':Title'    => 'Left View',
            ':FilePath' => $leftImage,
            ':SortOrder'=> $order++
        ]);
    }

    // Right
    if ($rightImage !== '') {
        $imgStmt->execute([
            ':AreaId'   => $areaId,
            ':ViewType' => 'Right',
            ':Title'    => 'Right View',
            ':FilePath' => $rightImage,
            ':SortOrder'=> $order++
        ]);
    }

    // Side / Rear
    if ($sideImage !== '') {
        $imgStmt->execute([
            ':AreaId'   => $areaId,
            ':ViewType' => 'Side',
            ':Title'    => 'Side / Rear View',
            ':FilePath' => $sideImage,
            ':SortOrder'=> $order++
        ]);
    }

    // Extra images (array of file paths)
    foreach ($extraImages as $extraPath) {
        $imgStmt->execute([
            ':AreaId'   => $areaId,
            ':ViewType' => 'Extra',
            ':Title'    => 'Additional View',
            ':FilePath' => $extraPath,
            ':SortOrder'=> $order++
        ]);
    }

    $pdo->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Area created successfully.',
        'id'      => $areaId
    ]);
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to save area.',
        'details' => $e->getMessage()
    ]);
}
