<?php
/**
 * Real-Time Inquiry 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['inquiry_id']) || !isset($data['action'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

$inquiry_id = intval($data['inquiry_id']);
$action = $data['action']; // 'approve' or 'decline'
$staff_id = $_SESSION['user_id'];

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

try {
    // Get inquiry details first
    $stmt = $conn->prepare("SELECT customer_id, property_id FROM inquiries WHERE id = ?");
    $stmt->bind_param('i', $inquiry_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $inquiry = $result->fetch_assoc();
    $stmt->close();
    
    if (!$inquiry) {
        throw new Exception('Inquiry not found');
    }
    
    // Update inquiry with approval status
    $status = $action === 'approve' ? 'approved' : 'declined';
    
    $stmt = $conn->prepare("
        UPDATE inquiries 
        SET status = ?, updated_at = NOW()
        WHERE id = ?
    ");
    
    $stmt->bind_param('si', $status, $inquiry_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update inquiry');
    }
    
    $stmt->close();
    
    // Log the action
    $action_log = "{$action}ed by staff (ID: {$staff_id})";
    
    // Broadcast update to all connected clients
    // Store the update in a real-time queue
    $broadcast_key = "inquiry_{$inquiry_id}_update";
    $broadcast_data = [
        'id' => $inquiry_id,
        'customer_id' => $inquiry['customer_id'],
        'property_id' => $inquiry['property_id'],
        'status' => $status,
        'action' => $action,
        'updated_at' => date('Y-m-d H:i:s'),
        'updated_by_staff_id' => $staff_id,
        'timestamp' => time()
    ];
    
    // Store in a real-time updates table for cross-tab updates
    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, ignore error
    }
    
    $update_type = 'inquiry_' . $action;
    $entity_type = 'inquiry';
    $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, $inquiry_id, $entity_type, $action, $data_json);
    $stmt->execute();
    $stmt->close();
    
    // Clean old updates (older than 1 hour)
    $conn->query("DELETE FROM realtime_updates WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 HOUR)");
    
    echo json_encode([
        'success' => true,
        'message' => 'Inquiry ' . $action . 'ed successfully',
        'inquiry_id' => $inquiry_id,
        'status' => $status,
        'action' => $action,
        'timestamp' => time(),
        'realtime' => true  // Indicates this was processed with real-time notification
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
