<?php
session_start();
require_once '../includes/config.php';

header('Content-Type: application/json');

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

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

// ✅ Validate input
$leaveId = isset($_POST['leave_id']) ? intval($_POST['leave_id']) : 0;
$action = $_POST['action'] ?? '';

if (!$leaveId || !in_array($action, ['approve', 'reject'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit;
}

// ✅ Determine new status
$newStatus = $action === 'approve' ? 'approved' : 'rejected';

// ✅ Prepare and execute update
try {
    $stmt = $pdo->prepare("UPDATE leave_requests SET status = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$newStatus, $leaveId]);

    if ($stmt->rowCount()) {
        echo json_encode([
            'success' => true,
            'id' => $leaveId,
            'status' => $newStatus,
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Leave request not found or already updated.'
        ]);
    }
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
