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

header('Content-Type: application/json');

// Validasi session
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    echo json_encode(['success' => false, 'message' => 'Session tidak valid']);
    exit;
}

try {
    // Validasi input
    if (empty($_POST['task_id'])) {
        echo json_encode(['success' => false, 'message' => 'Task ID tidak ditemukan']);
        exit;
    }

    $task_id = intval($_POST['task_id']);

    // Initialize permission
    $permission = new RencanaKerjaPermission($conn, $_SESSION['user_id'], $_SESSION['role']);
    $canDelete = $permission->hasPermission(RencanaKerjaPermission::PERM_DELETE, $task_id);

    if (!$canDelete['allowed']) {
        echo json_encode(['success' => false, 'message' => 'Anda tidak memiliki izin untuk menghapus tugas ini']);
        exit;
    }

    // Soft delete (set is_deleted = 1)
    $stmt = $conn->prepare("
        UPDATE rencana_kerja 
        SET is_deleted = 1,
            deleted_at = NOW()
        WHERE id = ?
    ");

    $stmt->bind_param("i", $task_id);

    if ($stmt->execute()) {
        // Log activity
        $permission->logAction($task_id, 'delete', 'Task deleted');

        echo json_encode([
            'success' => true,
            'message' => 'Tugas berhasil dihapus'
        ]);
    } else {
        throw new Exception('Gagal menghapus data: ' . $stmt->error);
    }

    $stmt->close();

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

$conn->close();
?>