<?php
// cron/agent-heartbeat-check.php — Toutes les 5 min
// Vérifier silence agents DXF > 15 min → alerte admin email + notification

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

$mail = new MailService();

$ateliers = DB::table('ateliers')->where('actif', 1)->get();

foreach ($ateliers as $atelier) {
    $agent = DB::table('users')
        ->where('atelier_id', $atelier->id)
        ->whereNotNull('agent_api_key')
        ->orderBy('agent_last_heartbeat', 'desc')
        ->first();

    if (!$agent || !$agent->agent_last_heartbeat) continue;

    $minutesSilence = (time() - strtotime($agent->agent_last_heartbeat)) / 60;

    if ($minutesSilence > 15) {
        // Vérifier si alerte déjà envoyée dans les 30 dernières minutes
        $alreadyAlerted = DB::table('logs_audit')
            ->where('action', 'alerte_agent_silence')
            ->where('entite_id', $atelier->id)
            ->where('created_at', '>', date('Y-m-d H:i:s', time() - 1800))
            ->exists();

        if ($alreadyAlerted) continue;

        $mail->agentSilence($atelier->nom, (int)$minutesSilence);

        DB::table('notifications')->insert([
            'user_id'    => 1,
            'type'       => 'agent_silence',
            'titre'      => 'Agent DXF inactif — ' . $atelier->nom,
            'message'    => "Silence depuis " . round($minutesSilence) . " minutes",
            'lien'       => 'https://fab.mykollector.com/agent/',
            'lu'         => 0,
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        DB::table('logs_audit')->insert([
            'action'    => 'alerte_agent_silence',
            'entite'    => 'atelier',
            'entite_id' => $atelier->id,
            'details'   => json_encode(['minutes_silence' => round($minutesSilence)]),
            'created_at'=> date('Y-m-d H:i:s'),
        ]);

        error_log('[CRON agent-heartbeat-check] ALERTE — ' . $atelier->nom . ' silence depuis ' . round($minutesSilence) . 'min');
    }
}

error_log('[CRON agent-heartbeat-check] ' . date('c') . ' — Vérification terminée');
