<?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['status'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

$appointment_id = intval($data['appointment_id']);
$status = $data['status'];

// Only allow these status values
$valid_statuses = ['pending', 'scheduled', 'completed', 'cancelled'];
if (!in_array($status, $valid_statuses)) {
    echo json_encode(['success' => false, 'message' => 'Invalid status']);
    exit;
}

try {
    // Update appointment status
    $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' => 'Visit status updated successfully']);
    } else {
        throw new Exception('Failed to update visit status');
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
