<?php
require_once '../../config.php';
header('Content-Type: application/json');

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

function tableExists(mysqli $db, string $table): bool
{
    $safeTable = $db->real_escape_string($table);
    $result = $db->query("SHOW TABLES LIKE '" . $safeTable . "'");
    return $result && $result->num_rows > 0;
}

try {
    $analytics = [
        'broker_pending_properties' => 0,
        'broker_approval_pending_properties' => 0,
        'broker_finished_properties' => 0
    ];

    if (tableExists($mysqli, 'property_assignment_workflow')) {
        $pendingResult = $mysqli->query("
            SELECT COUNT(*) AS count
            FROM property_assignment_workflow
            WHERE LOWER(COALESCE(workflow_status, '')) IN ('assigned', 'working')
        ");
        if ($pendingResult) {
            $analytics['broker_pending_properties'] = intval($pendingResult->fetch_assoc()['count'] ?? 0);
        }

        $approvalPendingResult = $mysqli->query("
            SELECT COUNT(*) AS count
            FROM property_assignment_workflow
            WHERE LOWER(COALESCE(workflow_status, '')) = 'finished_pending_admin'
        ");
        if ($approvalPendingResult) {
            $analytics['broker_approval_pending_properties'] = intval($approvalPendingResult->fetch_assoc()['count'] ?? 0);
        }

        $finishedResult = $mysqli->query("
            SELECT COUNT(*) AS count
            FROM property_assignment_workflow
            WHERE LOWER(COALESCE(workflow_status, '')) = 'finished_approved'
        ");
        if ($finishedResult) {
            $analytics['broker_finished_properties'] = intval($finishedResult->fetch_assoc()['count'] ?? 0);
        }
    }

    echo json_encode([
        'success' => true,
        'analytics' => $analytics
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to load analytics: ' . $e->getMessage()
    ]);
}
?>
