<?php

declare(strict_types=1);

namespace App\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Illuminate\Database\Capsule\Manager as DB;

class ClassementController
{
    use ControllerTrait;

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

        $classements = DB::table('classements')
            ->join('produits', 'produits.id', '=', 'classements.produit_id')
            ->where('classements.user_id', $user->id)
            ->select(['classements.*', 'produits.nom as parcours_nom', 'produits.slug'])
            ->get();

        $data = $classements->map(function ($c) use ($user) {
            $total    = DB::table('classements')->where('produit_id', $c->produit_id)->count();
            $position = DB::table('classements')
                ->where('produit_id', $c->produit_id)
                ->where('duree_secondes', '<', $c->duree_secondes)
                ->count() + 1;

            return [
                'produit'           => ['slug' => $c->slug, 'nom' => $c->parcours_nom],
                'duree_secondes'    => $c->duree_secondes,
                'position'          => $position,
                'total_participants'=> $total,
                'source'            => $c->source,
                'date_realisation'  => $c->date_realisation,
            ];
        })->toArray();

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

    public function byParcours(Request $request, Response $response, array $args): Response
    {
        $params    = $request->getQueryParams();
        $produitId = (int)$args['id'];
        $since     = $params['since'] ?? null;

        $userId  = null;
        $payload = $this->getAuthPayload($request);
        if ($payload) $userId = (int)$payload->sub;

        $sinceClause = '';
        $bindings    = [$produitId];

        if ($since === 'today') {
            $sinceClause = 'AND DATE(c.date_debut) = CURDATE()';
        } elseif ($since === '30days') {
            $sinceClause = 'AND c.date_debut >= DATE_SUB(NOW(), INTERVAL 30 DAY)';
        } elseif ($since && strtotime($since)) {
            $sinceClause = 'AND c.date_debut >= ?';
            $bindings[]  = $since;
        }

        $rows = DB::select("
            SELECT
                c.user_id,
                MIN(c.duree_secondes)       AS duree_secondes,
                MAX(c.strava_activity_id)   AS strava_activity_id,
                MAX(c.date_debut)           AS date_realisation,
                CONCAT(u.prenom, ' ', LEFT(u.nom, 1), '.') AS sportif
            FROM chronos c
            JOIN users u ON u.id = c.user_id
            WHERE c.produit_id = ?
              AND c.statut = 'valide'
              AND c.source != 'manuel'
              AND c.duree_secondes IS NOT NULL
              AND c.duree_secondes > 0
              {$sinceClause}
            GROUP BY c.user_id, u.prenom, u.nom
            ORDER BY duree_secondes ASC
        ", $bindings);

        $data = [];
        foreach (array_values($rows) as $i => $c) {
            $data[] = [
                'position'         => $i + 1,
                'sportif'          => $c->sportif,
                'duree_secondes'   => (int)$c->duree_secondes,
                'date_realisation' => $c->date_realisation,
                'strava_confirmed' => !empty($c->strava_activity_id),
                'is_me'            => $userId && (int)$c->user_id === $userId,
                'user_id'          => (int)$c->user_id,
            ];
        }

        return $this->successList($response, $data, ['total' => count($data)]);
    }

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

        $user = $this->getAuthUser($request);
        $id   = (int)$args['id'];

        DB::table('classements')->where('id', $id)->delete();
        $this->logAudit($user->id, 'classement_supprime', 'classement', $id, [], $request);

        return $this->success($response, ['message' => 'Classement supprimé']);
    }
}
