<?php
require_once dirname(__DIR__, 2) . '/config/config.php';
require_once dirname(__DIR__, 2) . '/includes/db.php';

if (ob_get_length()) ob_clean(); 
header('Content-Type: application/json');

if (!isset($conn) && isset($db)) { $conn = $db; }

try {
    // Analytics
    $kpi_total = $conn->query("SELECT COUNT(*) as total FROM suppliers")->fetch_assoc()['total'] ?? 0;
    $kpi_comp  = $conn->query("SELECT COUNT(*) as total FROM suppliers WHERE supplier_type = 'Company'")->fetch_assoc()['total'] ?? 0;
    $kpi_indiv = $conn->query("SELECT COUNT(*) as total FROM suppliers WHERE supplier_type = 'Individual'")->fetch_assoc()['total'] ?? 0;
    $kpi_act   = $conn->query("SELECT COUNT(*) as total FROM suppliers WHERE is_active = 1")->fetch_assoc()['total'] ?? 0;

    // Advanced Join to aggregate multiple mapped roles
    $query = "
        SELECT s.id, s.supplier_code, s.supplier_type, s.company_name, s.first_name, s.last_name, s.mobile, s.city, s.is_active,
               GROUP_CONCAT(sc.category_name SEPARATOR '||') as roles
        FROM suppliers s
        LEFT JOIN supplier_category_mapping scm ON s.id = scm.supplier_id
        LEFT JOIN supplier_categories sc ON scm.category_id = sc.id
        GROUP BY s.id
        ORDER BY s.id DESC
    ";
    
    $result = $conn->query($query);
    $records = [];

    while ($row = $result->fetch_assoc()) {
        $displayName = $row['supplier_type'] === 'Company' ? $row['company_name'] : trim("{$row['first_name']} {$row['last_name']}");
        $rolesArr = !empty($row['roles']) ? explode('||', $row['roles']) : [];

        $records[] = [
            'id' => (int)$row['id'],
            'code' => $row['supplier_code'],
            'type' => $row['supplier_type'],
            'display_name' => $displayName,
            'mobile' => $row['mobile'] ?? '--',
            'city' => $row['city'] ?? '--',
            'roles' => $rolesArr,
            'is_active' => (int)$row['is_active']
        ];
    }

    echo json_encode(['status' => 'success', 'kpis' => ['total' => $kpi_total, 'companies' => $kpi_comp, 'individuals' => $kpi_indiv, 'active' => $kpi_act], 'data' => $records]);

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>