<?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'];
        $annee     = $params['annee'] ?? null;

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

        $query = DB::table('classements')
            ->join('users', 'users.id', '=', 'classements.user_id')
            ->where('classements.produit_id', $produitId)
            ->select([
                'classements.*',
                DB::raw("CONCAT(users.prenom, ' ', LEFT(users.nom, 1), '.') as sportif"),
            ])
            ->orderBy('classements.duree_secondes', 'asc');

        if ($annee) {
            $query->whereYear('classements.date_realisation', $annee);
        }

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

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

        $data = $classements->map(function ($c, $i) use ($offset, $userId) {
            return [
                'position'         => $offset + $i + 1,
                'sportif'          => $c->sportif,
                'duree_secondes'   => $c->duree_secondes,
                'date_realisation' => $c->date_realisation,
                'strava_confirmed' => !empty($c->strava_activity_id),
                'is_me'            => $userId && $c->user_id === $userId,
            ];
        })->toArray();

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

    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é']);
    }
}
