<?php
// cron/kpi_rollup.php
// Run daily to compute KPI snapshots and persist to sd_kpi_snapshots

require_once __DIR__ . '/../api/_pdo_db_connect.php';
require_once __DIR__ . '/../Controllers/KPIController.php';

// Calculate yesterday
$yesterday = new DateTime('yesterday');
$start = $yesterday->format('Y-m-d');
$end   = $yesterday->format('Y-m-d');

$kpi = new KPIController($pdo);

// For rollup, take snapshots per team and global
try {
    // 1) Global snapshot
    $global = $kpi->getKpiSummary($start, $end, []);

    // Insert snapshot
    $stmt = $pdo->prepare("INSERT INTO sd_kpi_snapshots (snapshot_date, team_id, payload, created_at) VALUES (:snapshot_date, NULL, :payload, NOW())");
    $stmt->execute([
        ':snapshot_date' => $start,
        ':payload' => json_encode($global)
    ]);

    // 2) Team-level snapshots (if you have as_team table)
    $teamsStmt = $pdo->prepare("SELECT team_id FROM as_team");
    $teamsStmt->execute();
    $teams = $teamsStmt->fetchAll(PDO::FETCH_COLUMN);

    foreach ($teams as $teamId) {
        $tData = $kpi->getKpiSummary($start, $end, ['team_id' => (int)$teamId]);
        $stmt = $pdo->prepare("INSERT INTO sd_kpi_snapshots (snapshot_date, team_id, payload, created_at) VALUES (:snapshot_date, :team_id, :payload, NOW())");
        $stmt->execute([
            ':snapshot_date' => $start,
            ':team_id' => $teamId,
            ':payload' => json_encode($tData)
        ]);
    }

    echo "KPI rollup completed for {$start}\n";
    exit(0);

} catch (Exception $e) {
    echo "KPI rollup error: " . $e->getMessage() . "\n";
    exit(1);
}
