<?php
session_start();
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../config/send_email.php'; // Include email function

// Only admin can delete
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../../auth/login.php");
    exit;
}

// Check CSRF token
if (!isset($_GET['token']) || $_GET['token'] !== $_SESSION['csrf_token']) {
    $_SESSION['error'] = "Invalid CSRF token.";
    header("Location: index.php");
    exit;
}

// Check if project ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error'] = "No project specified.";
    header("Location: index.php");
    exit;
}

$project_id = (int)$_GET['id'];

// Check if project exists
$stmt = $pdo->prepare("SELECT * FROM projects WHERE id = ?");
$stmt->execute([$project_id]);
$project = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$project) {
    $_SESSION['error'] = "Project not found.";
    header("Location: index.php");
    exit;
}

// Delete the project
try {
    $del = $pdo->prepare("DELETE FROM projects WHERE id = ?");
    $del->execute([$project_id]);

    // Send email notification to systems
    $username = $_SESSION['username'];
    $subject = "Project Deleted: {$project['name']}";
    $body = "<p>Project <b>{$project['name']}</b> (Code: {$project['code']}) has been deleted by {$username} (Admin).</p>";
    send_email('systems@digivortlimited.com', 'Systems Team', $subject, $body);

    $_SESSION['success'] = "Project '{$project['name']}' has been deleted successfully.";

} catch (PDOException $e) {
    $_SESSION['error'] = "Error deleting project: " . $e->getMessage();
}

header("Location: index.php");
exit;
?>