<?php
require_once '../../config.php';
header('Content-Type: application/json');

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

// Get JSON input
$data = json_decode(file_get_contents('php://input'), true);

if (!$data || !isset($data['appointment_id']) || !isset($data['action'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

$appointment_id = intval($data['appointment_id']);
$action = $data['action']; // 'approve', 'decline', or 'reschedule'

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

try {
    // Update appointment with approval status
    $status = $action === 'approve' ? 'approved' : ($action === 'decline' ? 'declined' : 'pending');
    
    $stmt = $conn->prepare("
        UPDATE appointments 
        SET status = ?, updated_at = NOW()
        WHERE id = ?
    ");
    
    $stmt->bind_param('si', $status, $appointment_id);
    
    if ($stmt->execute()) {
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'Appointment ' . $action . 'ed successfully']);
    } else {
        throw new Exception('Failed to update appointment');
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
