<?php
// cron/stats-cache.php — Quotidien 08h00
// Refresh cache statistiques dashboard admin

require_once __DIR__ . '/_bootstrap.php';
use Illuminate\Database\Capsule\Manager as DB;

$stats = [
    'total_commandes'  => DB::table('commandes')->count(),
    'en_lot'           => DB::table('commandes')->where('statut', 'en_lot')->count(),
    'en_gravure'       => DB::table('commandes')->where('statut', 'en_gravure')->count(),
    'expedie_mois'     => DB::table('commandes')->where('statut', 'expedie')->whereMonth('date_expedition', date('m'))->count(),
    'total_chronos'    => DB::table('chronos')->where('statut', 'valide')->count(),
    'sportifs_inscrits'=> DB::table('users')->where('role', 'sportif')->count(),
    'cached_at'        => date('Y-m-d H:i:s'),
];

try {
    DB::connection('workflow')->table('app_config')->updateOrInsert(
        ['cle' => 'stats_cache'],
        ['valeur' => json_encode($stats), 'updated_at' => date('Y-m-d H:i:s')]
    );
} catch (\Exception $e) {
    // Workflow DB peut ne pas être configurée
}

error_log('[CRON stats-cache] ' . date('c') . ' — Cache mis à jour');
