<?php
// add_plot.php

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

$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;
}

$areaId    = isset($data['areaId']) ? (int)$data['areaId'] : 0;
$code      = trim($data['code'] ?? '');
$fullPrice = $data['fullPrice'] ?? null;
$status    = trim($data['status'] ?? 'Available');
$buyerName = trim($data['buyerName'] ?? '');
$notes     = trim($data['notes'] ?? '');

if ($areaId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Area is required.']);
    exit;
}

if ($code === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Plot code is required.']);
    exit;
}

if ($fullPrice === null || !is_numeric($fullPrice)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Full price is required.']);
    exit;
}

try {
    // 1) Check for duplicate code in the same area
    $check = $pdo->prepare("
        SELECT COUNT(*) 
        FROM Plots 
        WHERE AreaId = :AreaId AND Code = :Code
    ");
    $check->execute([
        ':AreaId' => $areaId,
        ':Code'   => $code,
    ]);
    $exists = (int)$check->fetchColumn();

    if ($exists > 0) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'A plot with this code already exists in this area.'
        ]);
        exit;
    }

    // 2) Insert new plot
    $stmt = $pdo->prepare("
        INSERT INTO Plots (AreaId, Code, FullPrice, Status, BuyerName, Notes)
        VALUES (:AreaId, :Code, :FullPrice, :Status, :BuyerName, :Notes)
    ");

    $stmt->execute([
        ':AreaId'    => $areaId,
        ':Code'      => $code,
        ':FullPrice' => (float)$fullPrice,
        ':Status'    => $status,
        ':BuyerName' => $buyerName !== '' ? $buyerName : null,
        ':Notes'     => $notes !== '' ? $notes : null,
    ]);

    echo json_encode([
        'success' => true,
        'message' => 'Plot created successfully.',
        'id'      => (int)$pdo->lastInsertId()
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to save plot.',
        'details' => $e->getMessage()
    ]);
}
