<?php
// api/kpi/live.php
header('Content-Type: application/json');

// Basic auth check - reuse your middleware
// Adjust path if your middleware auth_check.php has a different location.
require_once __DIR__ . '/../_pdo_db_connect.php';
require_once __DIR__ . '/../middleware/auth_check.php';
require_once __DIR__ . '/../../Controllers/KPIController.php';

// Run token check (auth_check is expected to set $current_user or die)
$auth = new AuthCheck();
$user = $auth->requireAuth(); // implement in your middleware: returns user array with id, role, team_id

// Validate inputs
$start = isset($_GET['start']) ? trim($_GET['start']) : null;
$end = isset($_GET['end']) ? trim($_GET['end']) : null;
if (!$start || !$end) {
    http_response_code(400);
    echo json_encode(['error' => 'start and end query params are required. Format: YYYY-MM-DD']);
    exit;
}

// Optional filters: fallback to token claims
$filters = [];
if (!empty($_GET['user_id'])) $filters['user_id'] = (int)$_GET['user_id'];
if (!empty($_GET['team_id'])) $filters['team_id'] = (int)$_GET['team_id'];
if (!empty($_GET['role'])) $filters['role'] = trim($_GET['role']);

// If no explicit filters, scope by token (recommended)
if (empty($filters['user_id']) && empty($filters['team_id'])) {
    if (!empty($user['id'])) $filters['user_id'] = (int)$user['id'];
    if (!empty($user['team_id'])) $filters['team_id'] = (int)$user['team_id'];
    if (!empty($user['role'])) $filters['role'] = $user['role'];
}

try {
    // $pdo is created by your _pdo_db_connect.php
    // If your connection variable name differs, adjust here.
    $kpi = new KPIController($pdo);
    $data = $kpi->getKpiSummary($start, $end, $filters);

    echo json_encode(['status' => 'ok', 'data' => $data]);
    exit;
} catch (Exception $ex) {
    http_response_code(500);
    echo json_encode(['error' => 'internal_server_error', 'msg' => $ex->getMessage()]);
    exit;
}
