<?php
// cron/stock-alerts.php — Quotidien 09h00
// Alertes stock bas emballages fabricants + MKO

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

$mail = new MailService();

$stocksBas = DB::table('stocks')
    ->join('ateliers', 'ateliers.id', '=', 'stocks.atelier_id')
    ->whereColumn('stocks.quantite', '<', 'stocks.seuil_alerte')
    ->select(['stocks.*', 'ateliers.nom as atelier_nom'])
    ->get();

foreach ($stocksBas as $stock) {
    // Vérifier si alerte déjà envoyée aujourd'hui
    $alreadySent = DB::table('logs_audit')
        ->where('action', 'alerte_stock_bas')
        ->where('entite_id', $stock->id)
        ->whereDate('created_at', date('Y-m-d'))
        ->exists();

    if ($alreadySent) continue;

    $mail->stockBas(
        $stock->type_stock,
        $stock->atelier_nom,
        $stock->quantite,
        $stock->seuil_alerte
    );

    DB::table('logs_audit')->insert([
        'action'    => 'alerte_stock_bas',
        'entite'    => 'stock',
        'entite_id' => $stock->id,
        'details'   => json_encode(['quantite' => $stock->quantite, 'seuil' => $stock->seuil_alerte]),
        'created_at'=> date('Y-m-d H:i:s'),
    ]);
}

error_log('[CRON stock-alerts] ' . date('c') . ' — ' . count($stocksBas) . ' alertes vérifiées');
