<?php

declare(strict_types=1);

namespace App\Services;

use Illuminate\Database\Capsule\Manager as DB;

class RelanceService
{
    private MailService $mail;

    public function __construct()
    {
        $this->mail = new MailService();
    }

    // ─── Relances chrono non converti ───

    public function traiterRelancesJ7(): int
    {
        return $this->traiterRelances(7, 'j7_chrono');
    }

    public function traiterRelancesJ30(): int
    {
        return $this->traiterRelances(30, 'j30_chrono');
    }

    public function traiterRelancesJ60(): int
    {
        return $this->traiterRelances(60, 'j60_chrono');
    }

    private function traiterRelances(int $jours, string $typeRelance): int
    {
        $chronos = DB::table('chronos')
            ->where('statut', 'valide')
            ->whereIn('source', ['qr', 'strava', 'manuel'])
            ->where('created_at', '<=', date('Y-m-d H:i:s', strtotime("-{$jours} days")))
            ->get();

        $nb = 0;

        foreach ($chronos as $chrono) {
            // Vérifier si commande existante
            $hasCommande = DB::table('commandes')
                ->where('chrono_id', $chrono->id)
                ->exists();
            if ($hasCommande) continue;

            // Vérifier si relance déjà envoyée
            $alreadySent = DB::table('relances_log')
                ->where('chrono_id', $chrono->id)
                ->where('type_relance', $typeRelance)
                ->exists();
            if ($alreadySent) continue;

            // Récupérer user et produit
            $user    = DB::table('users')->where('id', $chrono->user_id)->first();
            $produit = DB::table('produits')->where('id', $chrono->produit_id)->first();

            if (!$user || !$user->email || !$produit) continue;

            $lienBoutique = $produit->lien_boutique ?? 'https://shop.mykollector.com';
            $sent = false;

            switch ($jours) {
                case 7:
                    $sent = $this->mail->relanceChronoJ7($user->email, $user->prenom ?? 'Sportif', $produit->nom, $lienBoutique);
                    break;
                case 30:
                    $sent = $this->mail->relanceChronoJ30($user->email, $user->prenom ?? 'Sportif', $produit->nom, $lienBoutique);
                    break;
                case 60:
                    $sent = $this->mail->relanceChronoJ60($user->email, $user->prenom ?? 'Sportif', $produit->nom, $lienBoutique);
                    break;
            }

            if ($sent) {
                DB::table('relances_log')->insert([
                    'chrono_id'   => $chrono->id,
                    'type_relance'=> $typeRelance,
                    'sent_at'     => date('Y-m-d H:i:s'),
                ]);
                $nb++;
            }
        }

        DB::table('logs_audit')->insert([
            'action'    => 'relance_envoyee',
            'details'   => json_encode(['type' => $typeRelance, 'nb_total' => $nb]),
            'created_at'=> date('Y-m-d H:i:s'),
        ]);

        return $nb;
    }

    // ─── Auto-validation gravure J+7 ───

    public function autoValidationGravure(): int
    {
        $commandes = DB::table('commandes')
            ->where('statut', 'importee')
            ->where('validation_sportif', 0)
            ->where('type_commande', '!=', 'gravure_seule')
            ->where('created_at', '<=', date('Y-m-d H:i:s', strtotime('-7 days')))
            ->get();

        $nb = 0;

        foreach ($commandes as $commande) {
            DB::table('commandes')->where('id', $commande->id)->update([
                'validation_sportif' => 1,
                'statut'             => 'validee',
                'date_validation'    => date('Y-m-d H:i:s'),
            ]);

            $user = DB::table('users')->where('id', $commande->user_id)->first();
            if ($user && $user->email) {
                $this->mail->autoValidationJ7(
                    $user->email,
                    $user->prenom ?? 'Sportif',
                    $commande->texte_gravure ?? '',
                    $commande->presta_order_ref ?? 'MKO-' . $commande->id
                );
            }

            DB::table('logs_audit')->insert([
                'action'    => 'auto_validation_gravure',
                'entite'    => 'commande',
                'entite_id' => $commande->id,
                'created_at'=> date('Y-m-d H:i:s'),
            ]);

            $nb++;
        }

        return $nb;
    }

    // ─── Relance validation gravure J+3 ───

    public function relanceValidationGravureJ3(): int
    {
        $commandes = DB::table('commandes')
            ->where('statut', 'importee')
            ->where('validation_sportif', 0)
            ->where('type_commande', 'medaille_complete')
            ->where('created_at', '<=', date('Y-m-d H:i:s', strtotime('-3 days')))
            ->get();

        $nb = 0;

        foreach ($commandes as $commande) {
            $alreadySent = DB::table('relances_log')
                ->where('commande_id', $commande->id)
                ->where('type_relance', 'j3_gravure')
                ->exists();
            if ($alreadySent) continue;

            $user = DB::table('users')->where('id', $commande->user_id)->first();
            if (!$user || !$user->email) continue;

            $lienValidation = 'https://chrono.mykollector.com/dashboard.html';
            $sent = $this->mail->relanceValidationJ3(
                $user->email,
                $user->prenom ?? 'Sportif',
                $commande->texte_gravure ?? '',
                $commande->presta_order_ref ?? 'MKO-' . $commande->id,
                $lienValidation
            );

            if ($sent) {
                DB::table('relances_log')->insert([
                    'commande_id' => $commande->id,
                    'type_relance'=> 'j3_gravure',
                    'sent_at'     => date('Y-m-d H:i:s'),
                ]);
                $nb++;
            }
        }

        return $nb;
    }
}
