<?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($_GET['id'])) {
        echo json_encode(['success' => false, 'message' => 'Task ID tidak ditemukan']);
        exit;
    }

    $task_id = intval($_GET['id']);

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

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

    // Get task data
    $stmt = $conn->prepare("
        SELECT * FROM rencana_kerja 
        WHERE id = ? AND is_deleted = 0
    ");

    $stmt->bind_param("i", $task_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $task = $result->fetch_assoc();
        
        echo json_encode([
            'success' => true,
            'task' => $task
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Tugas tidak ditemukan'
        ]);
    }

    $stmt->close();

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

$conn->close();
?>