<?php
// File: superadmin/superadmin_delete_project.php

include 'auth_check.php';
require_role(['superadmin']); 
require_once('../db.php'); 

// 1. Cek ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: superadmin_create_project.php");
    exit;
}

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

// 2. Cek apakah project ada (Opsional, untuk validasi)
$check = mysqli_query($conn, "SELECT project_id FROM projects WHERE project_id = $project_id");
if (mysqli_num_rows($check) == 0) {
    echo "<script>alert('Project tidak ditemukan!'); window.location.href='superadmin_create_project.php';</script>";
    exit;
}

// 3. HAPUS PROJECT
// Catatan: Pastikan di database Anda Foreign Key 'tasks' dan 'employer_projects' 
// sudah di-set ON DELETE CASCADE. Jika belum, data terkait akan error/tertinggal.
// Jika ragu, kita hapus manual data terkaitnya dulu (opsional, tapi lebih aman).

// Hapus keterikatan dengan employer & member dulu (jika tidak cascade)
mysqli_query($conn, "DELETE FROM employer_projects WHERE project_id = $project_id");
mysqli_query($conn, "DELETE FROM member_projects WHERE project_id = $project_id");

// Hapus tugas-tugas di dalam project ini
// (Opsional: Kalau mau file attachment ikut terhapus, butuh logic loop unlink seperti delete_task.php)
mysqli_query($conn, "DELETE FROM tasks WHERE project_id = $project_id");

// Akhirnya hapus project
$query = "DELETE FROM projects WHERE project_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $project_id);

if ($stmt->execute()) {
    echo "<script>
            alert('✅ Project dan semua data terkait berhasil dihapus!');
            window.location.href = 'superadmin_create_project.php';
          </script>";
} else {
    echo "<script>
            alert('❌ Gagal menghapus project: " . $stmt->error . "');
            window.location.href = 'superadmin_create_project.php';
          </script>";
}

$stmt->close();
?>