<?php
// update_area.php: update area details + optional images

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';

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid method');
    }

    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    if ($id <= 0) {
        throw new Exception('Invalid area id');
    }

    $name = trim($_POST['name'] ?? '');
    if ($name === '') {
        throw new Exception('Area name is required');
    }

    $description = trim($_POST['description'] ?? '');
    $basePrice = $_POST['basePrice'] ?? null;
    $minPrice = $_POST['minPrice'] ?? null;
    $maxPrice = $_POST['maxPrice'] ?? null;
    $developmentType = trim($_POST['developmentType'] ?? '');
    $category = trim($_POST['category'] ?? 'Residential');
    $projectStatus = trim($_POST['projectStatus'] ?? 'Ongoing');
    $showOnWebsite = isset($_POST['showOnWebsite']) && $_POST['showOnWebsite'] === '1' ? 1 : 0;
    $configurations = trim($_POST['configurations'] ?? '');

    // Handle file uploads (optional)
    $uploadDir = __DIR__ . '/../../uploads/areas/';
    if (!is_dir($uploadDir)) {
        @mkdir($uploadDir, 0777, true);
    }

    $fieldsToUpdate = [
        'Name' => $name,
        'Description' => $description,
        'BasePricePerPlot' => ($basePrice === '' ? null : $basePrice),
        'MinPrice' => ($minPrice === '' ? null : $minPrice),
        'MaxPrice' => ($maxPrice === '' ? null : $maxPrice),
        'DevelopmentType' => $developmentType,
        'Category' => $category,
        'ProjectStatus' => $projectStatus,
        'ShowOnWebsite' => $showOnWebsite,
        'Configurations' => $configurations,
    ];

    // simple helper
    function handleImageUpload($key, $uploadDir) {
        if (!isset($_FILES[$key]) || $_FILES[$key]['error'] !== UPLOAD_ERR_OK) {
            return null;
        }
        $ext = pathinfo($_FILES[$key]['name'], PATHINFO_EXTENSION);
        $filename = $key . '_' . time() . '_' . mt_rand(1000, 9999) . '.' . $ext;
        $target = $uploadDir . $filename;
        if (!move_uploaded_file($_FILES[$key]['tmp_name'], $target)) {
            return null;
        }
        return $filename;
    }

    $layoutName = handleImageUpload('layoutImage', $uploadDir);
    $frontName  = handleImageUpload('frontImage', $uploadDir);
    $leftName   = handleImageUpload('leftImage', $uploadDir);
    $rightName  = handleImageUpload('rightImage', $uploadDir);
    $sideName   = handleImageUpload('sideImage', $uploadDir);

    if ($layoutName) $fieldsToUpdate['LayoutImagePath'] = $layoutName;
    if ($frontName)  $fieldsToUpdate['FrontImagePath'] = $frontName;
    if ($leftName)   $fieldsToUpdate['LeftImagePath'] = $leftName;
    if ($rightName)  $fieldsToUpdate['RightImagePath'] = $rightName;
    if ($sideName)   $fieldsToUpdate['SideImagePath'] = $sideName;

    // Build dynamic SQL
    $setParts = [];
    $params = [':id' => $id];
    foreach ($fieldsToUpdate as $col => $val) {
        $setParts[] = "$col = :$col";
        $params[":$col"] = $val;
    }

    $sql = "UPDATE Areas SET " . implode(', ', $setParts) . " WHERE Id = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
