<?php
/**
 * Real-Time Appointment Approval with Broadcast
 * Handles approve/decline actions with instant notifications
 */
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'
$staff_id = $_SESSION['user_id'];

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

try {
    // Get appointment details first
    $stmt = $conn->prepare("SELECT user_id, property_id, appointment_date, appointment_time FROM appointments WHERE id = ?");
    $stmt->bind_param('i', $appointment_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $appointment = $result->fetch_assoc();
    $stmt->close();
    
    if (!$appointment) {
        throw new Exception('Appointment not found');
    }
    
    // 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()) {
        throw new Exception('Failed to update appointment');
    }
    
    $stmt->close();
    
    // Store in real-time updates table
    if (!$conn->query("CREATE TABLE IF NOT EXISTS realtime_updates (
        id INT AUTO_INCREMENT PRIMARY KEY,
        update_type VARCHAR(50),
        entity_id INT,
        entity_type VARCHAR(50),
        action VARCHAR(50),
        data JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_type (update_type),
        INDEX idx_created (created_at)
    )")) {
        // Table might already exist
    }
    
    $update_type = 'appointment_' . $action;
    $entity_type = 'appointment';
    $broadcast_data = [
        'id' => $appointment_id,
        'user_id' => $appointment['user_id'],
        'property_id' => $appointment['property_id'],
        'status' => $status,
        'action' => $action,
        'appointment_date' => $appointment['appointment_date'],
        'appointment_time' => $appointment['appointment_time'],
        'updated_at' => date('Y-m-d H:i:s'),
        'updated_by_staff_id' => $staff_id,
        'timestamp' => time()
    ];
    $data_json = json_encode($broadcast_data);
    
    $stmt = $conn->prepare("
        INSERT INTO realtime_updates (update_type, entity_id, entity_type, action, data)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->bind_param('sisss', $update_type, $appointment_id, $entity_type, $action, $data_json);
    $stmt->execute();
    $stmt->close();
    
    // Clean old updates
    $conn->query("DELETE FROM realtime_updates WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 HOUR)");
    
    echo json_encode([
        'success' => true,
        'message' => 'Appointment ' . $action . 'ed successfully',
        'appointment_id' => $appointment_id,
        'status' => $status,
        'action' => $action,
        'timestamp' => time(),
        'realtime' => true
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
