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

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

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

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

// 2. AMBIL INFO FILE ATTACHMENT DULU (Sebelum hapus task)
// Kita perlu nama file uniknya untuk menghapus file fisik di folder uploads
$sql_file = "SELECT unique_file_name FROM task_attachments WHERE task_id = ?";
$stmt_file = $conn->prepare($sql_file);
$stmt_file->bind_param("i", $task_id);
$stmt_file->execute();
$result_file = $stmt_file->get_result();
$attachment = $result_file->fetch_assoc();
$stmt_file->close();

// 3. HAPUS FILE FISIK DARI FOLDER (Jika ada)
if ($attachment) {
    // Tentukan path file (Mundur satu folder ke root, lalu ke uploads/tasks/)
    $file_path = '../uploads/tasks/' . $attachment['unique_file_name'];
    
    // Cek apakah file ada, lalu hapus
    if (file_exists($file_path)) {
        unlink($file_path); // Fungsi PHP untuk menghapus file
    }
}

// 4. HAPUS DATA TUGAS DARI DATABASE
// Karena ada Foreign Key ON DELETE CASCADE (biasanya), 
// menghapus task otomatis menghapus data di tabel task_attachments juga.
$sql_delete = "DELETE FROM tasks WHERE id = ?";
$stmt_delete = $conn->prepare($sql_delete);
$stmt_delete->bind_param("i", $task_id);

if ($stmt_delete->execute()) {
    // Berhasil Hapus
    echo "<script>
            alert('✅ Tugas dan file lampiran berhasil dihapus!');
            window.location.href = 'superadmin_dashboard.php';
          </script>";
} else {
    // Gagal Hapus
    echo "<script>
            alert('❌ Gagal menghapus tugas: " . $stmt_delete->error . "');
            window.location.href = 'superadmin_dashboard.php';
          </script>";
}

$stmt_delete->close();
?>