<?php
// cron/webhook-retry.php — Toutes les 10 min
// Retry imports commandes PS en échec (table ps_import_queue)

require_once __DIR__ . '/_bootstrap.php';

use App\Services\PrestashopService;
use App\Services\GravureService;
use App\Services\MailService;
use Illuminate\Database\Capsule\Manager as DB;

$ps      = new PrestashopService();
$gravure = new GravureService();
$mail    = new MailService();

// Récupérer les commandes en attente de retry (lock léger — pas de SELECT FOR UPDATE)
$pending = DB::table('ps_import_queue')
    ->where('statut', 'en_attente')
    ->where('prochaine_tentative', '<=', date('Y-m-d H:i:s'))
    ->where(function($q) {
        $q->whereNull('locked_at')
          ->orWhere('locked_at', '<', date('Y-m-d H:i:s', time() - 30));
    })
    ->limit(10)
    ->get();

foreach ($pending as $item) {
    // Lock léger
    $locked = DB::table('ps_import_queue')
        ->where('id', $item->id)
        ->where(function($q) {
            $q->whereNull('locked_at')
              ->orWhere('locked_at', '<', date('Y-m-d H:i:s', time() - 30));
        })
        ->update([
            'locked_at' => date('Y-m-d H:i:s'),
            'statut'    => 'en_cours',
        ]);

    if ($locked === 0) continue; // Déjà lockée

    try {
        $result = $ps->syncCommandes($gravure, $mail);

        DB::table('ps_import_queue')->where('id', $item->id)->update([
            'statut'     => 'traite',
            'locked_at'  => null,
        ]);

        error_log('[CRON webhook-retry] Commande ' . $item->presta_order_id . ' importée avec succès');
    } catch (\Exception $e) {
        $tentatives = $item->tentatives + 1;

        if ($tentatives >= 5) {
            // Échec permanent
            DB::table('ps_import_queue')->where('id', $item->id)->update([
                'statut'             => 'echec_permanent',
                'tentatives'         => $tentatives,
                'derniere_tentative' => date('Y-m-d H:i:s'),
                'erreur'             => $e->getMessage(),
                'locked_at'          => null,
            ]);

            // Alerte admin
            $mail->erreurImportPS('PS-' . $item->presta_order_id, $e->getMessage());

            DB::table('notifications')->insert([
                'user_id'    => 1,
                'type'       => 'import_ps_echec_permanent',
                'titre'      => 'Import PS échoué définitivement — commande ' . $item->presta_order_id,
                'message'    => $e->getMessage(),
                'lien'       => 'https://fab.mykollector.com/admin/prestashop.html',
                'lu'         => 0,
                'created_at' => date('Y-m-d H:i:s'),
            ]);
        } else {
            // Planifier prochain retry (backoff exponentiel)
            $nextRetry = date('Y-m-d H:i:s', time() + (600 * $tentatives));
            DB::table('ps_import_queue')->where('id', $item->id)->update([
                'statut'              => 'en_attente',
                'tentatives'          => $tentatives,
                'derniere_tentative'  => date('Y-m-d H:i:s'),
                'prochaine_tentative' => $nextRetry,
                'erreur'              => $e->getMessage(),
                'locked_at'           => null,
            ]);
        }

        error_log('[CRON webhook-retry] Erreur commande ' . $item->presta_order_id . ' (tentative ' . $tentatives . '): ' . $e->getMessage());
    }
}

error_log('[CRON webhook-retry] ' . date('c') . ' — ' . count($pending) . ' commandes traitées');
