<?php
/**
 * Real-Time WebSocket Server for Staff Dashboard
 * Handles live updates for inquiries and appointments
 */

// Enable WebSocket support with Ratchet
require_once __DIR__ . '/../../config.php';

// Check if this is a WebSocket upgrade request
$from_url = parse_url("http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}", PHP_URL_PATH);

// For actual WebSocket support, use Ratchet library
// This is a fallback polling-based real-time system for compatibility

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    die(json_encode(['error' => 'Method not allowed']));
}

// Get last check timestamp from client
$lastCheck = isset($_GET['lastCheck']) ? intval($_GET['lastCheck']) : 0;
$type = isset($_GET['type']) ? $_GET['type'] : 'all'; // 'inquiries', 'appointments', 'all'

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'staff') {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Set longer timeout for long-polling
set_time_limit(35);
ini_set('default_socket_timeout', 35);

try {
    $updates = ['inquiries' => [], 'appointments' => [], 'timestamp' => time()];
    
    // Check for new inquiries since last check
    if ($type === 'inquiries' || $type === 'all') {
        $lastCheckTime = date('Y-m-d H:i:s', $lastCheck);
        
        $stmt = $conn->prepare("
            SELECT 
                i.id,
                i.customer_id,
                u.user_name as customer_name,
                u.phone,
                u.email,
                p.title as property_title,
                i.property_id,
                i.message,
                i.response,
                i.status,
                i.created_at,
                i.updated_at,
                UNIX_TIMESTAMP(i.updated_at) as updated_timestamp
            FROM inquiries i
            LEFT JOIN users u ON i.customer_id = u.id
            LEFT JOIN properties p ON i.property_id = p.id
            WHERE i.updated_at > FROM_UNIXTIME(?)
            AND i.status IN ('pending', 'responded', 'approved', 'declined')
            ORDER BY i.updated_at DESC
            LIMIT 50
        ");
        
        $stmt->bind_param('i', $lastCheck);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $updates['inquiries'][] = [
                'id' => intval($row['id']),
                'customer_id' => intval($row['customer_id']),
                'customer_name' => $row['customer_name'],
                'phone' => $row['phone'],
                'email' => $row['email'],
                'property_id' => $row['property_id'] ? intval($row['property_id']) : null,
                'property_title' => $row['property_title'],
                'message' => $row['message'],
                'response' => $row['response'],
                'status' => $row['status'],
                'created_at' => $row['created_at'],
                'updated_at' => $row['updated_at'],
                'type' => 'inquiry'
            ];
        }
        $stmt->close();
    }
    
    // Check for new appointments since last check
    if ($type === 'appointments' || $type === 'all') {
        $stmt = $conn->prepare("
            SELECT 
                a.id,
                a.user_id,
                u.user_name as customer_name,
                u.phone,
                u.email,
                a.property_id,
                p.title as property_title,
                p.city,
                a.appointment_date,
                a.appointment_time,
                a.message,
                a.status,
                a.created_at,
                a.updated_at,
                UNIX_TIMESTAMP(a.updated_at) as updated_timestamp
            FROM appointments a
            LEFT JOIN users u ON a.user_id = u.id
            LEFT JOIN properties p ON a.property_id = p.id
            WHERE a.updated_at > FROM_UNIXTIME(?)
            AND a.status IN ('pending', 'approved', 'declined', 'scheduled', 'completed')
            ORDER BY a.updated_at DESC
            LIMIT 50
        ");
        
        $stmt->bind_param('i', $lastCheck);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $updates['appointments'][] = [
                'id' => intval($row['id']),
                'user_id' => intval($row['user_id']),
                'customer_name' => $row['customer_name'],
                'phone' => $row['phone'],
                'email' => $row['email'],
                'property_id' => $row['property_id'] ? intval($row['property_id']) : null,
                'property_title' => $row['property_title'],
                'city' => $row['city'],
                'appointment_date' => $row['appointment_date'],
                'appointment_time' => $row['appointment_time'],
                'message' => $row['message'],
                'status' => $row['status'],
                'created_at' => $row['created_at'],
                'updated_at' => $row['updated_at'],
                'type' => 'appointment'
            ];
        }
        $stmt->close();
    }
    
    // Return updates with current timestamp for next poll
    echo json_encode([
        'success' => true,
        'updates' => $updates,
        'timestamp' => $updates['timestamp'],
        'hasUpdates' => !empty($updates['inquiries']) || !empty($updates['appointments'])
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
