<?php
// File: employer/employer_delete_task.php

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

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

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

// 2. KEAMANAN: Cek apakah tugas ini BENAR milik Employer yang sedang login?
// (Mencegah employer menghapus tugas milik orang lain)
$check_sql = "SELECT id FROM tasks WHERE id = ? AND creator_id = ?";
$stmt_check = $conn->prepare($check_sql);
$stmt_check->bind_param("ii", $task_id, $employer_id);
$stmt_check->execute();
$result_check = $stmt_check->get_result();

if ($result_check->num_rows === 0) {
    // Jika data tidak ditemukan, berarti tugas itu bukan miliknya atau tidak ada
    echo "<script>
            alert('⛔ AKSES DITOLAK! Anda tidak memiliki izin untuk menghapus tugas ini.'); 
            window.location.href='employer_dashboard.php';
          </script>";
    exit;
}
$stmt_check->close();

// 3. Ambil Info File Attachment (Supaya file fisiknya juga terhapus dari server)
$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();

// 4. Hapus File Fisik (MENGGUNAKAN PATH ABSOLUT AGAR LEBIH STABIL)
if ($attachment) {
    // Dapatkan folder root project secara otomatis
    $project_root = dirname(__DIR__); 
    // Gabungkan menjadi path lengkap: C:\xampp\htdocs\TaskManagement\uploads\tasks\namafile.ext
    $file_path = $project_root . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'tasks' . DIRECTORY_SEPARATOR . $attachment['unique_file_name'];
    
    // Cek apakah file ada, lalu hapus
    if (file_exists($file_path)) {
        unlink($file_path); // Hapus file
    }
}

// 5. Hapus Data Tugas dari Database
// (Biasanya data di tabel task_attachments akan ikut terhapus otomatis jika settingan DB ON DELETE CASCADE aktif)
$sql_delete = "DELETE FROM tasks WHERE id = ?";
$stmt_delete = $conn->prepare($sql_delete);
$stmt_delete->bind_param("i", $task_id);

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

$stmt_delete->close();
?>