<?php
/**
 * Get Broker's Leads (Inquiries)
 * Returns: Leads/inquiries assigned to or managed by the broker
 */

header('Content-Type: application/json');
require_once '../../config.php';
require_once __DIR__ . '/broker-identity.php';

$session_role = $_SESSION['role'] ?? ($_SESSION['user_role'] ?? '');
if (!isset($_SESSION['user_id']) || $session_role !== 'broker') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$session_broker_id = (int)$_SESSION['user_id'];
$brokerCtx = resolveBrokerContext($conn, $session_broker_id);
$broker_id = (int)$brokerCtx['property_broker_id'];
$fallback_broker_id = $session_broker_id !== $broker_id ? $session_broker_id : 0;

try {
    $stmt = $conn->prepare("
        SELECT 
            i.id, i.customer_id, i.property_id, i.status, i.message, i.created_at,
            c.firstname, c.lastname, c.email, c.phone,
            p.title as property_title, p.city as property_city
        FROM inquiries i
        JOIN customers c ON i.customer_id = c.id
        JOIN properties p ON i.property_id = p.id
        WHERE (
            i.assigned_to = ?
            OR i.broker_id = ?
            OR (? > 0 AND i.broker_id = ?)
            OR p.broker_id = ?
            OR (? > 0 AND p.broker_id = ?)
        )
          AND LOWER(COALESCE(i.status, 'pending')) IN ('pending', 'responded', 'approved', 'declined', 'completed', 'done', 'finished')
        ORDER BY i.created_at DESC 
        LIMIT 50
    ");
    $stmt->bind_param('iiiiiii', $session_broker_id, $broker_id, $fallback_broker_id, $fallback_broker_id, $broker_id, $fallback_broker_id, $fallback_broker_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $leads = [];
    while ($row = $result->fetch_assoc()) {
        $row['customer_name'] = $row['firstname'] . ' ' . $row['lastname'];
        $leads[] = $row;
    }
    $stmt->close();

    echo json_encode([
        'success' => true,
        'leads' => $leads,
        'count' => count($leads)
    ]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
