<?php
/**
 * Delete Plot
 * LandSales Pro - Remove plot from project
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];
$plotId = intval($_GET['id'] ?? 0);
$confirm = isset($_GET['confirm']);

// Get plot
$plot = db_fetch_one("SELECT * FROM plots WHERE id = ? AND user_id = ?", 'ii', [$plotId, $userId]);

if (!$plot) {
    header('Location: index.php');
    exit;
}

// Cannot delete sold plots
if ($plot['status'] === 'sold') {
    setFlashMessage('Cannot delete a sold plot. Cancel the sale first.', 'error');
    header('Location: view.php?id=' . $plotId);
    exit;
}

if (!$confirm) {
    header('Location: edit.php?id=' . $plotId);
    exit;
}

// Delete plot
$sql = "DELETE FROM plots WHERE id = ? AND user_id = ? AND status != 'sold'";

if (db_execute($sql, 'ii', [$plotId, $userId])) {
    logActivity('plot_deleted', "Deleted plot {$plot['plot_number']}");
    setFlashMessage('Plot "' . $plot['plot_number'] . '" has been deleted.', 'success');
    header('Location: index.php?project=' . $plot['project_id']);
} else {
    setFlashMessage('Failed to delete plot. Please try again.', 'error');
    header('Location: edit.php?id=' . $plotId);
}
exit;
