<?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 {
    // Dynamic KPI Computation direct from database states
    $kpi_total     = $conn->query("SELECT COUNT(*) as total FROM stores")->fetch_assoc()['total'] ?? 0;
    $kpi_active    = $conn->query("SELECT COUNT(*) as total FROM stores WHERE is_active = 1")->fetch_assoc()['total'] ?? 0;
    $kpi_suspended = $conn->query("SELECT COUNT(*) as total FROM stores WHERE is_active = 0")->fetch_assoc()['total'] ?? 0;

    // Relational INNER JOIN mapping every node directly to its look-up dictionary configurations
    $query = "
        SELECT s.id, s.store_name, s.is_active, t.type_name, t.type_code 
        FROM stores s
        INNER JOIN store_types t ON s.store_type_id = t.id
        ORDER BY s.id DESC
    ";
    
    $result = $conn->query($query);
    $records = [];

    while ($row = $result->fetch_assoc()) {
        $records[] = [
            'id'         => (int)$row['id'],
            'store_name' => $row['store_name'],
            'type_name'  => $row['type_name'],
            'type_code'  => $row['type_code'],
            'is_active'  => (int)$row['is_active']
        ];
    }

    echo json_encode([
        'status' => 'success',
        'kpis' => [
            'total'     => $kpi_total,
            'active'    => $kpi_active,
            'suspended' => $kpi_suspended
        ],
        'data' => $records
    ]);

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