<?php
namespace App\Controllers;

use App\Models\Commande;
use App\Services\PrestashopService;
use App\Services\MailService;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Illuminate\Database\Capsule\Manager as DB;

class CommandeController
{
    use ControllerTrait;

    public function __construct(
        private PrestashopService $ps,
        private MailService $mail
    ) {}

    public function mes(Request $request, Response $response): Response
    {
        $user = $this->getAuthUser($request);
        if (!$user) return $this->error($response, 'UNAUTHORIZED', 'Non authentifié', 401);

        [$page, $limit, $offset] = $this->paginate($request);

        $query = DB::table('commandes')
            ->join('produits', 'produits.id', '=', 'commandes.produit_id')
            ->where('commandes.user_id', $user->id)
            ->select(['commandes.*', 'produits.slug as produit_slug', 'produits.nom as produit_nom'])
            ->orderBy('commandes.created_at', 'desc');

        $total    = $query->count();
        $commandes = $query->skip($offset)->take($limit)->get();

        return $this->successList($response, $commandes->map(fn($c) => [
            'id'               => $c->id,
            'presta_order_ref' => $c->presta_order_ref,
            'produit'          => ['slug' => $c->produit_slug, 'nom' => $c->produit_nom],
            'statut'           => $c->statut,
            'texte_gravure'    => $c->texte_gravure,
            'validation_sportif'=> (bool)$c->validation_sportif,
            'numero_suivi'     => $c->numero_suivi,
            'transporteur'     => $c->transporteur,
            'date_expedition'  => $c->date_expedition,
        ])->toArray(), ['page' => $page, 'limit' => $limit, 'total' => $total]);
    }

    public function index(Request $request, Response $response): Response
    {
        $guard = $this->requireRole($request, $response, ['admin_fab', 'super_admin']);
        if ($guard) return $guard;

        [$page, $limit, $offset] = $this->paginate($request);
        $params  = $request->getQueryParams();

        $query = DB::table('commandes')
            ->join('produits', 'produits.id', '=', 'commandes.produit_id')
            ->leftJoin('users', 'users.id', '=', 'commandes.user_id')
            ->select(['commandes.*', 'produits.nom as produit_nom', 'users.prenom', 'users.nom as user_nom'])
            ->orderBy('commandes.created_at', 'desc');

        if (!empty($params['statut']))   $query->where('commandes.statut', $params['statut']);
        if (!empty($params['produit_id'])) $query->where('commandes.produit_id', (int)$params['produit_id']);
        if (!empty($params['type']))     $query->where('commandes.type_commande', $params['type']);
        if (!empty($params['search']))   $query->where(function($q) use ($params) {
            $q->where('commandes.presta_order_ref', 'like', '%' . $params['search'] . '%')
              ->orWhere('users.nom', 'like', '%' . $params['search'] . '%')
              ->orWhere('users.prenom', 'like', '%' . $params['search'] . '%');
        });

        $total    = $query->count();
        $commandes = $query->skip($offset)->take($limit)->get();

        return $this->successList($response, $commandes->toArray(), ['page' => $page, 'limit' => $limit, 'total' => $total]);
    }

    public function show(Request $request, Response $response, array $args): Response
    {
        $guard = $this->requireRole($request, $response, ['admin_fab', 'super_admin']);
        if ($guard) return $guard;

        $commande = Commande::with(['user', 'produit', 'chrono'])->find((int)$args['id']);
        if (!$commande) return $this->error($response, 'NOT_FOUND', 'Commande introuvable', 404);

        return $this->success($response, $commande->toArray());
    }

    public function updateStatut(Request $request, Response $response, array $args): Response
    {
        $guard = $this->requireRole($request, $response, ['admin_fab', 'super_admin']);
        if ($guard) return $guard;

        $user     = $this->getAuthUser($request);
        $body     = (array)$request->getParsedBody();
        $statut   = $body['statut'] ?? '';
        $commande = Commande::find((int)$args['id']);
        if (!$commande) return $this->error($response, 'NOT_FOUND', 'Commande introuvable', 404);

        $commande->update(['statut' => $statut]);
        $this->logAudit($user->id, 'commande_statut_modifie', 'commande', $commande->id, ['statut' => $statut], $request);

        return $this->success($response, ['id' => $commande->id, 'statut' => $statut]);
    }

    public function validerGravure(Request $request, Response $response, array $args): Response
    {
        $user     = $this->getAuthUser($request);
        if (!$user) return $this->error($response, 'UNAUTHORIZED', 'Non authentifié', 401);

        $commandeId = (int)$args['id'];
        $body       = (array)$request->getParsedBody();
        $valide     = (bool)($body['valide'] ?? false);
        $nouveauTexte = $body['nouveau_texte'] ?? null;

        $commande = Commande::where('id', $commandeId)->where('user_id', $user->id)->first();
        if (!$commande) return $this->error($response, 'FORBIDDEN', 'Accès refusé', 403);
        if ($commande->validation_sportif) return $this->error($response, 'ALREADY_VALIDATED', 'Déjà validé', 409);

        $updates = [
            'validation_sportif' => 1,
            'date_validation'    => date('Y-m-d H:i:s'),
            'statut'             => 'validee',
        ];

        if (!$valide && $nouveauTexte) {
            $updates['texte_gravure'] = $nouveauTexte;
        }

        $commande->update($updates);

        // Push statut PS "En gravure" (ID 24)
        try {
            $this->ps->pushStatutCommande($commande->presta_order_id, (int)($_ENV['PRESTASHOP_STATUT_GRAVAGE_ID'] ?? 24));
            $commande->update(['presta_synced' => 1]);
        } catch (\Exception $e) {
            error_log('[CommandeController] Push PS échoué: ' . $e->getMessage());
        }

        // statut → validee (le lot est créé manuellement par l'opérateur fab depuis fab.mykollector.com)
        return $this->success($response, ['id' => $commandeId, 'statut' => 'validee', 'validation_sportif' => true]);
    }
}
