<?php
session_start();
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['username'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

include 'config.php';

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

if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'ID tidak valid']);
    exit;
}

// Query detail izin
$query = "SELECT p.*, s.nama as siswa_nama, s.nis, s.kelas, 
                 wk.nama_wali as wali_nama
          FROM perizinan p 
          JOIN siswa s ON p.siswa_id = s.id 
          LEFT JOIN wali_kelas wk ON s.kelas = wk.kelas 
          WHERE p.id = ?";

$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$data = mysqli_fetch_assoc($result);

if ($data) {
    // Format dates
    $data['tanggal_izin_formatted'] = date('d/m/Y', strtotime($data['tanggal_izin']));
    $data['created_at_formatted'] = date('d/m/Y H:i:s', strtotime($data['created_at']));
    
    echo json_encode([
        'success' => true,
        'data' => $data
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Data tidak ditemukan'
    ]);
}

mysqli_stmt_close($stmt);
mysqli_close($conn);
?>