<?php
session_start();
require_once __DIR__ . '/../../DataBase/koneksi.php';

// Validate session
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: /inventoryACF/index.html?error=session");
    exit;
}

$userRole = strtoupper(trim($_SESSION['role']));
$userId = (int) $_SESSION['user_id'];
$userDept = $_SESSION['department'] ?? null;

// Check if user has permission to delete
$allowedRoles = ['A', 'DH', 'D', 'M', 'ADMIN', 'DIRECTOR', 'DEPT_HEAD', 'MANAGER'];
if (!in_array($userRole, $allowedRoles)) {
    $_SESSION['error_message'] = "⛔ Anda tidak memiliki izin untuk menghapus tugas";
    header("Location: /inventoryACF/dashboard.php");
    exit;
}

// ✅ FIXED: Redirect URL TANPA dashboard.php prefix (langsung ke pages)
$redirectUrl = match($userRole) {
    'A', 'ADMIN' => 'pages/admin/rencana_kerja.php',
    'DH', 'DEPT_HEAD' => 'pages/manager/rencana_kerja.php',
    'D', 'DIRECTOR' => 'pages/director/rencana_kerja.php',
    'M', 'MANAGER' => 'pages/manager/rencana_kerja.php',
    'S', 'STAFF' => 'pages/staff/rencana_kerja.php',
    default => '/inventoryACF/dashboard.php'
};

// Get task ID (support both GET and POST)
$taskId = 0;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $taskId = isset($_POST['id']) ? (int)$_POST['id'] : 0;
} else {
    $taskId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
}

if ($taskId <= 0) {
    $_SESSION['error_message'] = "⚠️ ID tugas tidak valid";
    
    // ✅ Redirect via JavaScript jika dalam iframe
    echo "<!DOCTYPE html>
    <html>
    <head><meta charset='UTF-8'></head>
    <body>
    <script>
    if (parent && parent.document.getElementById('contentFrame')) {
        parent.document.getElementById('contentFrame').src = '{$redirectUrl}';
    } else {
        window.location.href = '/inventoryACF/dashboard.php?load=' + encodeURIComponent('{$redirectUrl}');
    }
    </script>
    </body>
    </html>";
    exit;
}

// Get task information to check permissions
$sqlCheck = "SELECT rk.id, rk.created_by, rk.assigned_to, 
             assignee.department as task_department
             FROM rencana_kerja rk
             LEFT JOIN users assignee ON rk.assigned_to = assignee.id
             WHERE rk.id = ? AND rk.is_deleted = 0";

$stmtCheck = $conn->prepare($sqlCheck);

if (!$stmtCheck) {
    $_SESSION['error_message'] = "❌ Database error: " . $conn->error;
    
    // ✅ Redirect via JavaScript
    echo "<!DOCTYPE html>
    <html>
    <head><meta charset='UTF-8'></head>
    <body>
    <script>
    if (parent && parent.document.getElementById('contentFrame')) {
        parent.document.getElementById('contentFrame').src = '{$redirectUrl}';
    } else {
        window.location.href = '/inventoryACF/dashboard.php?load=' + encodeURIComponent('{$redirectUrl}');
    }
    </script>
    </body>
    </html>";
    exit;
}

$stmtCheck->bind_param("i", $taskId);
$stmtCheck->execute();
$resultCheck = $stmtCheck->get_result();

if ($resultCheck->num_rows === 0) {
    $_SESSION['error_message'] = "❌ Tugas tidak ditemukan atau sudah dihapus";
    $stmtCheck->close();
    
    // ✅ Redirect via JavaScript
    echo "<!DOCTYPE html>
    <html>
    <head><meta charset='UTF-8'></head>
    <body>
    <script>
    if (parent && parent.document.getElementById('contentFrame')) {
        parent.document.getElementById('contentFrame').src = '{$redirectUrl}';
    } else {
        window.location.href = '/inventoryACF/dashboard.php?load=' + encodeURIComponent('{$redirectUrl}');
    }
    </script>
    </body>
    </html>";
    exit;
}

$taskInfo = $resultCheck->fetch_assoc();
$stmtCheck->close();

// Check if user can delete this task
$canDelete = false;

switch ($userRole) {
    case 'A':
    case 'ADMIN':
    case 'D':
    case 'DIRECTOR':
        // Admin and Director can delete anything
        $canDelete = true;
        break;
        
    case 'DH':
    case 'DEPT_HEAD':
        // Department Head can delete tasks in their department
        if ($userDept && $taskInfo['task_department'] === $userDept) {
            $canDelete = true;
        }
        break;
        
    case 'M':
    case 'MANAGER':
        // Manager can delete tasks they created in their department
        if ($userDept && 
            $taskInfo['task_department'] === $userDept && 
            $taskInfo['created_by'] == $userId) {
            $canDelete = true;
        }
        break;
}

if (!$canDelete) {
    $_SESSION['error_message'] = "⛔ Anda tidak memiliki izin untuk menghapus tugas ini";
    
    // ✅ Redirect via JavaScript
    echo "<!DOCTYPE html>
    <html>
    <head><meta charset='UTF-8'></head>
    <body>
    <script>
    if (parent && parent.document.getElementById('contentFrame')) {
        parent.document.getElementById('contentFrame').src = '{$redirectUrl}';
    } else {
        window.location.href = '/inventoryACF/dashboard.php?load=' + encodeURIComponent('{$redirectUrl}');
    }
    </script>
    </body>
    </html>";
    exit;
}

// Perform soft delete
$sql = "UPDATE rencana_kerja 
        SET is_deleted = 1, 
            deleted_at = NOW(), 
            deleted_by = ? 
        WHERE id = ? AND is_deleted = 0";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    $_SESSION['error_message'] = "❌ Error: " . $conn->error;
    
    // ✅ Redirect via JavaScript
    echo "<!DOCTYPE html>
    <html>
    <head><meta charset='UTF-8'></head>
    <body>
    <script>
    if (parent && parent.document.getElementById('contentFrame')) {
        parent.document.getElementById('contentFrame').src = '{$redirectUrl}';
    } else {
        window.location.href = '/inventoryACF/dashboard.php?load=' + encodeURIComponent('{$redirectUrl}');
    }
    </script>
    </body>
    </html>";
    exit;
}

$stmt->bind_param("ii", $userId, $taskId);

if ($stmt->execute() && $stmt->affected_rows > 0) {
    $_SESSION['success_message'] = "✅ Rencana kerja berhasil dihapus";
} else {
    $_SESSION['error_message'] = "❌ Gagal menghapus rencana kerja";
}

$stmt->close();
$conn->close();

// ✅ FINAL FIX: Redirect menggunakan JavaScript untuk handle iframe
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Redirect...</title>
</head>
<body>
    <script>
        // ✅ Detect if we're in an iframe
        if (parent && parent.document.getElementById('contentFrame')) {
            // Redirect iframe only (no dashboard wrapper)
            parent.document.getElementById('contentFrame').src = '<?= $redirectUrl ?>';
        } else {
            // Not in iframe, redirect with dashboard wrapper
            window.location.href = '/inventoryACF/dashboard.php?load=' + encodeURIComponent('<?= $redirectUrl ?>');
        }
    </script>
    <p>Redirecting...</p>
</body>
</html>