<?php
/**
 * Broker Statistics API
 * Returns: stats for assigned properties, leads, visits
 */

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 {
    // Get assigned properties count
    $stmt = $conn->prepare("
        SELECT COUNT(*) as count
        FROM properties
        WHERE (broker_id = ? OR (? > 0 AND broker_id = ?))
    ");
    $stmt->bind_param('iii', $broker_id, $fallback_broker_id, $fallback_broker_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $assigned_properties = $result->fetch_assoc()['count'] ?? 0;
    $stmt->close();

    // Get active leads count
    $stmt = $conn->prepare("
        SELECT COUNT(*) as count
        FROM inquiries i
        LEFT JOIN properties p ON p.id = i.property_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')
    ");
    $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();
    $active_leads = $result->fetch_assoc()['count'] ?? 0;
    $stmt->close();

    // Get scheduled visits count
    $stmt = $conn->prepare("
        SELECT COUNT(*) as count
        FROM appointments a
        LEFT JOIN properties p ON p.id = a.property_id
        WHERE (
            a.user_id = ?
            OR p.broker_id = ?
            OR (? > 0 AND p.broker_id = ?)
        )
          AND LOWER(COALESCE(a.status, 'pending')) IN ('pending', 'approved', 'scheduled', 'confirmed', 'completed', 'done', 'finished')
    ");
    $stmt->bind_param('iiii', $session_broker_id, $broker_id, $fallback_broker_id, $fallback_broker_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $scheduled_visits = $result->fetch_assoc()['count'] ?? 0;
    $stmt->close();

    $workflowTableExists = $conn->query("SHOW TABLES LIKE 'property_assignment_workflow'");
    if ($workflowTableExists && $workflowTableExists->num_rows > 0) {
        $doneFromWorkflowStmt = $conn->prepare("
            SELECT COUNT(*) AS count
            FROM property_assignment_workflow
            WHERE (broker_id = ? OR (? > 0 AND broker_id = ?))
              AND LOWER(COALESCE(workflow_status, '')) = 'finished_approved'
        ");
        $doneFromWorkflowStmt->bind_param('iii', $broker_id, $fallback_broker_id, $fallback_broker_id);
        $doneFromWorkflowStmt->execute();
        $workflowResult = $doneFromWorkflowStmt->get_result();
        $scheduled_visits += (int)($workflowResult->fetch_assoc()['count'] ?? 0);
        $doneFromWorkflowStmt->close();
    }

    // Get all submitted documents count (+ status breakdown)
    $total_documents = 0;
    $pending_documents = 0;
    $approved_documents = 0;
    $rejected_documents = 0;
    $docsTableExists = $conn->query("SHOW TABLES LIKE 'broker_documents'");
    if ($docsTableExists && $docsTableExists->num_rows > 0) {
        $stmt = $conn->prepare("
            SELECT LOWER(COALESCE(approval_status, 'pending')) AS status_name, COUNT(*) AS count
            FROM broker_documents
            WHERE (broker_id = ? OR (? > 0 AND broker_id = ?))
            GROUP BY LOWER(COALESCE(approval_status, 'pending'))
        ");
        $stmt->bind_param('iii', $session_broker_id, $fallback_broker_id, $fallback_broker_id);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $statusName = (string)($row['status_name'] ?? 'pending');
            $count = (int)($row['count'] ?? 0);
            $total_documents += $count;
            if ($statusName === 'pending') {
                $pending_documents += $count;
            } elseif ($statusName === 'approved') {
                $approved_documents += $count;
            } elseif ($statusName === 'rejected') {
                $rejected_documents += $count;
            }
        }
        $stmt->close();
    }

    echo json_encode([
        'success' => true,
        'stats' => [
            'assigned_properties' => $assigned_properties,
            'active_leads' => $active_leads,
            'scheduled_visits' => $scheduled_visits,
            'total_documents' => $total_documents,
            'pending_documents' => $pending_documents,
            'approved_documents' => $approved_documents,
            'rejected_documents' => $rejected_documents
        ]
    ]);

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