<?php

declare(strict_types=1);

use DI\ContainerBuilder;
use Slim\Factory\AppFactory;
use Dotenv\Dotenv;

define('BASE_PATH', dirname(__DIR__));

require BASE_PATH . '/vendor/autoload.php';

// Charger .env
$dotenv = Dotenv::createImmutable(BASE_PATH);
$dotenv->load();

// Configurer PHP-DI
$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions(BASE_PATH . '/src/App/dependencies.php');
$container = $containerBuilder->build();

// Configurer Eloquent ORM
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection([
    'driver'    => 'mysql',
    'host'      => $_ENV['DB_HOST'],
    'port'      => $_ENV['DB_PORT'] ?? 3306,
    'database'  => $_ENV['DB_NAME'],
    'username'  => $_ENV['DB_USER'],
    'password'  => $_ENV['DB_PASS'],
    'charset'   => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix'    => '',
], 'default');

// Base workflow (mykolluwork)
if (!empty($_ENV['DB_WORK_NAME'])) {
    $capsule->addConnection([
        'driver'    => 'mysql',
        'host'      => $_ENV['DB_WORK_HOST'],
        'port'      => $_ENV['DB_WORK_PORT'] ?? 3306,
        'database'  => $_ENV['DB_WORK_NAME'],
        'username'  => $_ENV['DB_WORK_USER'],
        'password'  => $_ENV['DB_WORK_PASS'],
        'charset'   => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix'    => '',
    ], 'workflow');
}

// Base PrestaShop (mykollu584) — pour sync wishlist
if (!empty($_ENV['PS_DB_NAME'])) {
    $capsule->addConnection([
        'driver'    => 'mysql',
        'host'      => $_ENV['PS_DB_HOST'] ?? $_ENV['DB_HOST'],
        'port'      => $_ENV['PS_DB_PORT'] ?? 3306,
        'database'  => $_ENV['PS_DB_NAME'],
        'username'  => $_ENV['PS_DB_USER'] ?? $_ENV['DB_USER'],
        'password'  => $_ENV['PS_DB_PASS'] ?? $_ENV['DB_PASS'],
        'charset'   => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix'    => '',
    ], 'prestashop');
}

$capsule->setAsGlobal();
$capsule->bootEloquent();

// Créer app Slim
AppFactory::setContainer($container);
$app = AppFactory::create();

// Middlewares globaux
$app->addRoutingMiddleware();
$app->addBodyParsingMiddleware();

// CORS Middleware
$app->add(new \App\Middleware\CorsMiddleware());

// Maintenance Middleware
$app->add(new \App\Middleware\MaintenanceMiddleware());

// Error handler
$errorMiddleware = $app->addErrorMiddleware(
    (bool)($_ENV['APP_DEBUG'] ?? false),
    true,
    true
);
$errorMiddleware->setDefaultErrorHandler(function ($request, $exception, $displayErrorDetails) use ($app) {
    $response = $app->getResponseFactory()->createResponse();
    $response->getBody()->write(json_encode([
        'error' => true,
        'code'  => 'INTERNAL_ERROR',
        'message' => $displayErrorDetails ? $exception->getMessage() : 'Erreur interne du serveur'
    ]));
    return $response->withHeader('Content-Type', 'application/json')->withStatus(500);
});

// ═══════════════════════════════════════
// ROUTES
// ═══════════════════════════════════════

$app->get('/api/health', function ($request, $response) {
    $response->getBody()->write(json_encode(['status' => 'ok', 'version' => '1.1']));
    return $response->withHeader('Content-Type', 'application/json');
});

$app->get('/api/debug/psdb', function ($request, $response) {
    try {
        $host = $_ENV['PS_DB_HOST'] ?? 'NON_DEFINI';
        $name = $_ENV['PS_DB_NAME'] ?? 'NON_DEFINI';
        $user = $_ENV['PS_DB_USER'] ?? 'NON_DEFINI';
        $pass = $_ENV['PS_DB_PASS'] ?? '';
        $dsn  = "mysql:host={$host};dbname={$name};charset=utf8mb4";
        $pdo  = new PDO($dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
        $stmt = $pdo->query("SELECT COUNT(*) as nb FROM MkO025_customer");
        $nb   = $stmt->fetch(PDO::FETCH_ASSOC)['nb'];
        $data = ['connected' => true, 'host' => $host, 'db' => $name, 'customers' => $nb];
    } catch (\Exception $e) {
        $data = ['connected' => false, 'host' => $host ?? '?', 'db' => $name ?? '?', 'error' => $e->getMessage()];
    }
    $response->getBody()->write(json_encode($data));
    return $response->withHeader('Content-Type', 'application/json');
});

$app->post('/api/setup', [\App\Controllers\AdminController::class, 'setup']);

// ── AUTH ──────────────────────────────
$app->post('/api/auth/register',         [\App\Controllers\AuthController::class, 'register']);
$app->post('/api/auth/login',            [\App\Controllers\AuthController::class, 'login']);
$app->post('/api/auth/logout',           [\App\Controllers\AuthController::class, 'logout']);
$app->post('/api/auth/refresh',          [\App\Controllers\AuthController::class, 'refresh']);
$app->get('/api/auth/me',                [\App\Controllers\AuthController::class, 'me']);
$app->post('/api/auth/forgot-password',  [\App\Controllers\AuthController::class, 'forgotPassword']);
$app->post('/api/auth/reset-password',   [\App\Controllers\AuthController::class, 'resetPassword']);
$app->get('/api/auth/2fa/setup',         [\App\Controllers\AuthController::class, 'totpSetup']);
$app->post('/api/auth/2fa/confirmer',    [\App\Controllers\AuthController::class, 'totpConfirmer']);
$app->delete('/api/auth/2fa',            [\App\Controllers\AuthController::class, 'totpDesactiver']);

// ── USER ──────────────────────────────
$app->patch('/api/user/profil',    [\App\Controllers\UserController::class, 'updateProfil']);
$app->patch('/api/user/password',  [\App\Controllers\UserController::class, 'updatePassword']);
$app->get('/api/user/export',      [\App\Controllers\UserController::class, 'exportData']);
$app->delete('/api/user/data',     [\App\Controllers\UserController::class, 'deleteAccount']);
$app->delete('/api/user/account',  [\App\Controllers\UserController::class, 'deleteAccount']);

// ── NOTIFICATIONS ────────────────────
$app->get('/api/notifications',              [\App\Controllers\UserController::class, 'notifications']);
$app->patch('/api/notifications/{id}',       [\App\Controllers\UserController::class, 'marquerNotifLue']);
$app->post('/api/notifications/lire-tout',   [\App\Controllers\UserController::class, 'marquerToutLu']);

// ── PARCOURS ──────────────────────────
$app->get('/api/parcours',              [\App\Controllers\ParcoursController::class, 'index']);
$app->get('/api/parcours/nearby',       [\App\Controllers\ParcoursController::class, 'nearby']);
$app->get('/api/parcours/slug/{slug}',  [\App\Controllers\ParcoursController::class, 'bySlug']);
$app->get('/api/parcours/{id}',         [\App\Controllers\ParcoursController::class, 'show']);
$app->post('/api/parcours',             [\App\Controllers\ParcoursController::class, 'create']);
$app->patch('/api/parcours/{id}',       [\App\Controllers\ParcoursController::class, 'update']);
$app->delete('/api/parcours/{id}',      [\App\Controllers\ParcoursController::class, 'destroy']);

// ── GPX ───────────────────────────────
$app->post('/api/parcours/upload-gpx', [\App\Controllers\GpxController::class, 'upload']);

// ── FAVORIS ──────────────────────────
$app->get('/api/favoris',                 [\App\Controllers\FavorisController::class, 'index']);
$app->get('/api/favoris/sync-ps',         [\App\Controllers\FavorisController::class, 'syncFromPS']);
$app->post('/api/favoris/{produit_id}',   [\App\Controllers\FavorisController::class, 'add']);
$app->delete('/api/favoris/{produit_id}', [\App\Controllers\FavorisController::class, 'remove']);

// ── CHRONOS ───────────────────────────
$app->post('/api/chrono/start',                     [\App\Controllers\ChronoController::class, 'start']);
$app->post('/api/chrono/stop',                      [\App\Controllers\ChronoController::class, 'stop']);
$app->post('/api/chrono/manuel',                    [\App\Controllers\ChronoController::class, 'manuel']);
$app->get('/api/chrono/history',                    [\App\Controllers\ChronoController::class, 'history']);
$app->patch('/api/chrono/{id}/valider',             [\App\Controllers\ChronoController::class, 'valider']);
$app->patch('/api/chrono/{id}/ajuster-date',        [\App\Controllers\ChronoController::class, 'ajusterDate']);
$app->get('/api/chrono/{produit_id}/mes',           [\App\Controllers\ChronoController::class, 'mesByParcours']);
$app->get('/api/chrono/anomalies',                  [\App\Controllers\ChronoController::class, 'anomalies']);
$app->patch('/api/chrono/{id}/invalider',           [\App\Controllers\ChronoController::class, 'invalider']);
$app->patch('/api/chrono/{id}',                     [\App\Controllers\ChronoController::class, 'updateMien']);
$app->delete('/api/chrono/{id}',                    [\App\Controllers\ChronoController::class, 'deleteMien']);

// ── COMMANDES ─────────────────────────
$app->get('/api/commandes/mes',                     [\App\Controllers\CommandeController::class, 'mes']);
$app->get('/api/commandes',                         [\App\Controllers\CommandeController::class, 'index']);
$app->get('/api/commandes/{id}',                    [\App\Controllers\CommandeController::class, 'show']);
$app->put('/api/commandes/{id}/statut',             [\App\Controllers\CommandeController::class, 'updateStatut']);
$app->post('/api/commandes/{id}/valider-gravure',   [\App\Controllers\CommandeController::class, 'validerGravure']);

// ── STRAVA ────────────────────────────
$app->get('/api/strava/auth-url',           [\App\Controllers\StravaController::class, 'authUrl']);
$app->get('/api/strava/callback',           [\App\Controllers\StravaController::class, 'callback']);
$app->get('/api/strava/activites',          [\App\Controllers\StravaController::class, 'activites']);
$app->get('/api/strava/alertes',            [\App\Controllers\StravaController::class, 'alertes']);
$app->post('/api/strava/import/{id}',       [\App\Controllers\StravaController::class, 'import']);
$app->get('/api/strava/webhook',            [\App\Controllers\StravaController::class, 'webhookVerify']);
$app->post('/api/strava/webhook',           [\App\Controllers\StravaController::class, 'webhookReceive']);
$app->delete('/api/strava/disconnect',      [\App\Controllers\StravaController::class, 'disconnect']);

// ── CLASSEMENTS ───────────────────────
$app->get('/api/classements/mes',               [\App\Controllers\ClassementController::class, 'mes']);
$app->get('/api/classements/parcours/{id}',     [\App\Controllers\ClassementController::class, 'byParcours']);
$app->delete('/api/classements/{id}',           [\App\Controllers\ClassementController::class, 'supprimer']);

// ── PORTAIL FAB ───────────────────────
$app->get('/api/fab/commandes',                 [\App\Controllers\FabController::class, 'commandes']);
$app->get('/api/fab/commandes/{id}',            [\App\Controllers\FabController::class, 'commandeDetail']);
$app->post('/api/fab/gravure/prendre',          [\App\Controllers\FabController::class, 'prendreEnCharge']);
$app->patch('/api/fab/gravure/{id}/terminer',   [\App\Controllers\FabController::class, 'terminerGravure']);
$app->post('/api/fab/expedition',               [\App\Controllers\FabController::class, 'expedition']);
$app->post('/api/fab/expedition/batch',         [\App\Controllers\FabController::class, 'expeditionBatch']);
$app->post('/api/fab/sav/express',              [\App\Controllers\FabController::class, 'savExpress']);
$app->post('/api/fab/defaut',                   [\App\Controllers\FabController::class, 'signalerDefaut']);
$app->get('/api/fab/notifications',             [\App\Controllers\FabController::class, 'notifications']);

// ── LOTS ──────────────────────────────
$app->get('/api/lots',              [\App\Controllers\FabController::class, 'lots']);
$app->post('/api/lots',             [\App\Controllers\FabController::class, 'creerLot']);
$app->get('/api/lots/{id}',         [\App\Controllers\FabController::class, 'lotDetail']);
$app->patch('/api/lots/{id}/statut',[\App\Controllers\FabController::class, 'updateStatutLot']);
$app->get('/api/lots/{id}/csv',     [\App\Controllers\FabController::class, 'exportCsv']);
$app->get('/api/lots/{id}/dxf-archive', [\App\Controllers\FabController::class, 'dxfArchive']);

// ── AGENT DXF ─────────────────────────
$app->get('/api/agent/lots-en-attente',                         [\App\Controllers\AgentController::class, 'lotsEnAttente']);
$app->get('/api/agent/template-gravure/{id}/fichier',           [\App\Controllers\AgentController::class, 'templateFichier']);
$app->post('/api/agent/lot/{id}/rapport',                       [\App\Controllers\AgentController::class, 'rapport']);
$app->get('/api/agent/etiquettes-en-attente',                   [\App\Controllers\AgentController::class, 'etiquettesEnAttente']);
$app->get('/api/agent/etiquette/{id}/pdf',                      [\App\Controllers\AgentController::class, 'etiquettePdf']);
$app->post('/api/agent/commande/{id}/etiquette-generee',        [\App\Controllers\AgentController::class, 'confirmerEtiquette']);
$app->post('/api/agent/heartbeat',                              [\App\Controllers\AgentController::class, 'heartbeat']);

// ── PRESTASHOP ────────────────────────
$app->get('/api/cron/sync-commandes',              [\App\Controllers\PrestashopController::class, 'cronSync']);
$app->post('/api/prestashop/sync-commandes',        [\App\Controllers\PrestashopController::class, 'syncCommandes']);
$app->post('/api/prestashop/sync-commandes-b2b',    [\App\Controllers\PrestashopController::class, 'syncCommandesB2b']);
$app->post('/api/prestashop/test-connexion',        [\App\Controllers\PrestashopController::class, 'testConnexion']);
$app->post('/api/prestashop/test-produit',          [\App\Controllers\PrestashopController::class, 'testProduit']);

// ── SAV ───────────────────────────────
$app->get('/api/sav',       [\App\Controllers\FabController::class, 'savList']);
$app->post('/api/sav',      [\App\Controllers\FabController::class, 'savCreate']);
$app->patch('/api/sav/{id}',[\App\Controllers\FabController::class, 'savUpdate']);

// ── CHAT ──────────────────────────────
$app->get('/api/chat/conversations',                    [\App\Controllers\ChatController::class, 'conversations']);
$app->get('/api/chat/{id}/messages',                    [\App\Controllers\ChatController::class, 'messages']);
$app->post('/api/chat/{id}/messages',                   [\App\Controllers\ChatController::class, 'envoyer']);

// ── CONTACTS ──────────────────────────
$app->get('/api/contacts',                          [\App\Controllers\ContactController::class, 'index']);
$app->get('/api/contacts/fabricants',               [\App\Controllers\ContactController::class, 'fabricants']);
$app->get('/api/contacts/graveurs',                 [\App\Controllers\ContactController::class, 'graveurs']);
$app->post('/api/contacts',                         [\App\Controllers\ContactController::class, 'create']);
$app->patch('/api/contacts/{id}',                   [\App\Controllers\ContactController::class, 'update']);
$app->delete('/api/contacts/{id}',                  [\App\Controllers\ContactController::class, 'archive']);
$app->post('/api/contacts/{id}/creer-acces-fab',    [\App\Controllers\ContactController::class, 'creerAccesFab']);
$app->get('/api/contacts/{id}/operateurs',          [\App\Controllers\ContactController::class, 'operateurs']);

// ── STOCKS ────────────────────────────
$app->get('/api/stocks',                [\App\Controllers\FabController::class, 'stocks']);
$app->post('/api/stocks/mouvement',     [\App\Controllers\FabController::class, 'stockMouvement']);

// ── ADMIN ─────────────────────────────
$app->get('/api/admin/stats',               [\App\Controllers\AdminController::class, 'stats']);
$app->get('/api/admin/logs',                [\App\Controllers\AdminController::class, 'logs']);
$app->get('/api/admin/config',              [\App\Controllers\AdminController::class, 'getConfig']);
$app->patch('/api/admin/config',            [\App\Controllers\AdminController::class, 'updateConfig']);
$app->get('/api/admin/users',               [\App\Controllers\AdminController::class, 'users']);
$app->post('/api/admin/users',              [\App\Controllers\AdminController::class, 'createUser']);
$app->patch('/api/admin/users/{id}',        [\App\Controllers\AdminController::class, 'updateUser']);
$app->get('/api/admin/agent-status',        [\App\Controllers\AdminController::class, 'agentStatus']);
$app->post('/api/admin/agent/regenerer-cle',[\App\Controllers\AdminController::class, 'regenererCleAgent']);
$app->post('/api/admin/backup',             [\App\Controllers\AdminController::class, 'backup']);
$app->get('/api/admin/backup/dropbox-config',   [\App\Controllers\AdminController::class, 'dropboxConfig']);
$app->post('/api/admin/backup/dropbox-config',  [\App\Controllers\AdminController::class, 'saveDropboxConfig']);
$app->post('/api/admin/backup/dropbox-test',    [\App\Controllers\AdminController::class, 'testDropbox']);
$app->post('/api/admin/backup/dropbox-now',     [\App\Controllers\AdminController::class, 'backupDropboxNow']);
$app->get('/api/admin/schema-version',          [\App\Controllers\AdminController::class, 'schemaVersion']);
$app->get('/api/admin/sportifs',                [\App\Controllers\AdminController::class, 'sportifs']);
$app->get('/api/admin/sportifs/{id}',           [\App\Controllers\AdminController::class, 'sportifDetail']);
$app->post('/api/admin/notifications/check-sportifs', [\App\Controllers\AdminController::class, 'checkSportifs']);

// ── WORKFLOW ──────────────────────────
$app->get('/api/wf/todos',                          [\App\Controllers\WorkflowController::class, 'todos']);
$app->post('/api/wf/todos',                         [\App\Controllers\WorkflowController::class, 'createTodo']);
$app->patch('/api/wf/todos/{id}',                   [\App\Controllers\WorkflowController::class, 'updateTodo']);
$app->post('/api/wf/todos/{id}/cocher',             [\App\Controllers\WorkflowController::class, 'cocherTodo']);
$app->delete('/api/wf/todos/{id}',                  [\App\Controllers\WorkflowController::class, 'deleteTodo']);
$app->get('/api/wf/journal',                        [\App\Controllers\WorkflowController::class, 'journal']);
$app->post('/api/wf/journal',                       [\App\Controllers\WorkflowController::class, 'saveJournal']);
$app->get('/api/wf/journal/resume-semaine',         [\App\Controllers\WorkflowController::class, 'resumeSemaine']);
$app->get('/api/wf/assistant/historique',           [\App\Controllers\WorkflowController::class, 'assistantHistorique']);
$app->post('/api/wf/assistant/chat',                [\App\Controllers\WorkflowController::class, 'assistantChat']);
$app->delete('/api/wf/assistant/historique',        [\App\Controllers\WorkflowController::class, 'clearHistorique']);
$app->get('/api/wf/calendrier',                     [\App\Controllers\WorkflowController::class, 'calendrier']);
$app->post('/api/wf/calendrier/event',              [\App\Controllers\WorkflowController::class, 'createEvent']);
$app->patch('/api/wf/calendrier/event/{id}',        [\App\Controllers\WorkflowController::class, 'updateEvent']);
$app->delete('/api/wf/calendrier/event/{id}',       [\App\Controllers\WorkflowController::class, 'deleteEvent']);
$app->get('/api/wf/config',                         [\App\Controllers\WorkflowController::class, 'config']);

$app->run();
