<?php

if (!isset($_SESSION['id_user'])) {
    die("Akses ditolak");
}

$id_user_login = (int)$_SESSION['id_user'];

$q_me = mysqli_query($conn, "SELECT nama, role FROM users WHERE id_user = '$id_user_login' LIMIT 1");
$me   = mysqli_fetch_assoc($q_me);
$nama_login = $me['nama'] ?? '';
$role_login = $me['role'] ?? '';
$is_direktur_admin = in_array($role_login, ['direktur', 'admin']);

$id_task = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$q = mysqli_query($conn, "SELECT * FROM urgent_task WHERE id = '$id_task' LIMIT 1");
$task = mysqli_fetch_assoc($q);

if (!$task) {
    die("Urgent task tidak ditemukan.");
}

$is_pembuat = (trim($task['dibuat_oleh']) === trim($nama_login));

if (!$is_pembuat && !$is_direktur_admin) {
    die("Akses ditolak. Anda tidak memiliki izin untuk menghapus urgent task ini.");
}

// Hapus foto bukti penerima (jika ada file di server) sebelum hapus baris
$q_bukti = mysqli_query($conn, "SELECT bukti_foto FROM urgent_penerima WHERE urgent_id = '$id_task' AND bukti_foto IS NOT NULL");
while ($b = mysqli_fetch_assoc($q_bukti)) {
    $path = __DIR__ . '/bukti/' . $b['bukti_foto'];
    if (is_file($path)) {
        @unlink($path);
    }
}

// Hapus foto bukti task utama (kolom urgent_task.bukti_foto) jika ada
if (!empty($task['bukti_foto'])) {
    $path_task = __DIR__ . '/bukti/' . $task['bukti_foto'];
    if (is_file($path_task)) {
        @unlink($path_task);
    }
}

mysqli_query($conn, "DELETE FROM urgent_dikerjakan WHERE urgent_id = '$id_task'");
mysqli_query($conn, "DELETE FROM urgent_foto WHERE urgent_id = '$id_task'");
mysqli_query($conn, "DELETE FROM urgent_penerima WHERE urgent_id = '$id_task'");
mysqli_query($conn, "DELETE FROM urgent_task WHERE id = '$id_task'");

echo "<script>alert('Urgent task berhasil dihapus.'); window.location='urgent_list.php';</script>";
exit;