<?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 GpxController
{
    use ControllerTrait;

    // ── POST /api/parcours/upload-gpx ──────────────────────
    // Reçoit : multipart/form-data { gpx: file, slug: string }
    // Stocke : fab.mykollector.com/gpx/{slug}.gpx
    // Retourne : { url: "https://fab.mykollector.com/gpx/{slug}.gpx" }
    public function upload(Request $request, Response $response): Response
    {
        $user = $this->getAuthUser($request);
        if (!$user) return $this->error($response, 'UNAUTHORIZED', 'Non authentifié', 401);

        $files = $request->getUploadedFiles();
        $body  = $request->getParsedBody();

        $file = $files['gpx'] ?? null;
        $slug = preg_replace('/[^a-z0-9\-]/', '', strtolower($body['slug'] ?? ''));

        if (!$file || $file->getError() !== UPLOAD_ERR_OK) {
            return $this->error($response, 'NO_FILE', 'Fichier GPX manquant', 400);
        }
        if (!$slug) {
            return $this->error($response, 'NO_SLUG', 'Slug manquant', 400);
        }

        // Vérifier extension
        $filename = $file->getClientFilename();
        if (!str_ends_with(strtolower($filename), '.gpx')) {
            return $this->error($response, 'INVALID_TYPE', 'Format attendu : .gpx', 400);
        }

        // Dossier de stockage
        $gpxDir = $_ENV['GPX_DIR'] ?? '/home/mykollu/fab/gpx';
        if (!is_dir($gpxDir)) {
            mkdir($gpxDir, 0755, true);
        }

        $destFile = $gpxDir . '/' . $slug . '.gpx';
        $file->moveTo($destFile);

        // Mettre à jour gpx_url dans la BDD
        $url = 'https://fab.mykollector.com/gpx/' . $slug . '.gpx';
        DB::table('produits')
            ->where('slug', $slug)
            ->update(['gpx_url' => $url]);

        return $this->success($response, [
            'url'  => $url,
            'slug' => $slug,
        ]);
    }
}
