<?php
/**
 * AJAX Handler - Delete Task
 * Uses permission system for delete authorization
 */

session_start();
require_once __DIR__ . '/../../../DataBase/koneksi.php';
require_once __DIR__ . '/../../../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;
}

// Initialize permission
$permission = new RencanaKerjaPermission($conn, $_SESSION['user_id'], $_SESSION['role']);

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$taskId = isset($input['task_id']) ? intval($input['task_id']) : 0;

// Validation
if (!$taskId) {
    echo json_encode(['success' => false, 'message' => 'Task ID diperlukan']);
    exit;
}

// Check if user can delete this task
if (!$permission->canDelete($taskId)) {
    echo json_encode(['success' => false, 'message' => 'Anda tidak memiliki akses untuk menghapus tugas ini']);
    exit;
}

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

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

if ($stmt->execute()) {
    if ($stmt->affected_rows > 0) {
        echo json_encode([
            'success' => true,
            'message' => 'Tugas berhasil dihapus'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Tugas tidak ditemukan atau sudah dihapus'
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Gagal menghapus tugas: ' . $conn->error
    ]);
}

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