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

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

include 'config.php';

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Get and validate input
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$status = isset($_POST['status']) ? $_POST['status'] : '';

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

if (!in_array($status, ['approved', 'rejected'])) {
    echo json_encode(['success' => false, 'message' => 'Status tidak valid']);
    exit;
}

// Check if the izin exists and is still pending
$check_query = "SELECT p.*, s.nama as siswa_nama, s.nis 
                FROM perizinan p 
                JOIN siswa s ON p.siswa_id = s.id 
                WHERE p.id = ? AND p.status = 'pending'";
$stmt = mysqli_prepare($conn, $check_query);
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$izin_data = mysqli_fetch_assoc($result);

if (!$izin_data) {
    echo json_encode(['success' => false, 'message' => 'Data izin tidak ditemukan atau sudah diproses']);
    exit;
}

// Update the status
$update_query = "UPDATE perizinan SET status = ?, updated_at = NOW() WHERE id = ?";
$stmt = mysqli_prepare($conn, $update_query);
mysqli_stmt_bind_param($stmt, 'si', $status, $id);

if (mysqli_stmt_execute($stmt)) {
    // Set success message in session
    $status_text = $status === 'approved' ? 'disetujui' : 'ditolak';
    $_SESSION['message'] = "Izin siswa " . htmlspecialchars($izin_data['siswa_nama']) . " berhasil " . $status_text;
    $_SESSION['message_type'] = 'success';
    
    echo json_encode(['success' => true, 'message' => 'Status berhasil diupdate']);
} else {
    echo json_encode(['success' => false, 'message' => 'Gagal mengupdate status: ' . mysqli_error($conn)]);
}

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