<?php
/**
 * Delete Project
 * LandSales Pro - Remove project and all related data
 */
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'];
$projectId = intval($_GET['id'] ?? 0);
$confirm = isset($_GET['confirm']);

// Get project
$project = db_fetch_one("SELECT * FROM projects WHERE id = ? AND user_id = ?", 'ii', [$projectId, $userId]);

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

if (!$confirm) {
    // Redirect back if not confirmed
    header('Location: edit.php?id=' . $projectId);
    exit;
}

// Delete project (cascades to plots, sales, payments due to foreign keys)
$sql = "DELETE FROM projects WHERE id = ? AND user_id = ?";

if (db_execute($sql, 'ii', [$projectId, $userId])) {
    setFlashMessage('Project "' . $project['name'] . '" has been deleted.', 'success');
} else {
    setFlashMessage('Failed to delete project. Please try again.', 'error');
}

header('Location: index.php');
exit;
