<?php
/**
 * AJAX Handler - Get Task
 * Retrieves task data with permission check
 */

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']);
$permSummary = $permission->getPermissionSummary();

// Get task ID
$taskId = isset($_GET['id']) ? intval($_GET['id']) : 0;

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

// Get permission filter to ensure user can view this task
$permissionFilter = $permission->getViewFilter();

// Get task data with permission check
$stmt = $conn->prepare("
    SELECT 
        rk.*,
        creator.full_name AS creator_name,
        creator.department AS creator_department,
        assignee.full_name AS assignee_name,
        assignee.department AS assignee_department,
        approver.full_name AS approver_name
    FROM rencana_kerja rk
    LEFT JOIN users creator ON rk.created_by = creator.id
    LEFT JOIN users assignee ON rk.assigned_to = assignee.id
    LEFT JOIN users approver ON rk.approval_by = approver.id
    WHERE rk.id = ? 
    AND rk.is_deleted = 0
    $permissionFilter
");

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

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Tugas tidak ditemukan atau Anda tidak memiliki akses']);
    exit;
}

$task = $result->fetch_assoc();
$stmt->close();

echo json_encode([
    'success' => true,
    'task' => $task
]);

$conn->close();