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

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

        $ids = DB::table('favoris')
            ->where('user_id', $user->id)
            ->pluck('produit_id')
            ->toArray();

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

    // ── POST /api/favoris/{produit_id} ──────────────────────
    public function add(Request $request, Response $response, array $args): Response
    {
        $user = $this->getAuthUser($request);
        if (!$user) return $this->error($response, 'UNAUTHORIZED', 'Non authentifié', 401);

        $produitId = (int)($args['produit_id'] ?? 0);
        if (!$produitId) return $this->error($response, 'INVALID', 'produit_id invalide', 400);

        $produit = DB::table('produits')->where('id', $produitId)->first();
        if (!$produit) return $this->error($response, 'NOT_FOUND', 'Parcours introuvable', 404);

        try {
            DB::table('favoris')->insertOrIgnore([
                'user_id'    => $user->id,
                'produit_id' => $produitId,
                'source'     => 'mko',
                'created_at' => date('Y-m-d H:i:s'),
            ]);
        } catch (\Exception $e) {
            // doublon ignoré
        }

        return $this->success($response, ['favori' => true, 'produit_id' => $produitId]);
    }

    // ── DELETE /api/favoris/{produit_id} ────────────────────
    public function remove(Request $request, Response $response, array $args): Response
    {
        $user = $this->getAuthUser($request);
        if (!$user) return $this->error($response, 'UNAUTHORIZED', 'Non authentifié', 401);

        $produitId = (int)($args['produit_id'] ?? 0);
        if (!$produitId) return $this->error($response, 'INVALID', 'produit_id invalide', 400);

        DB::table('favoris')
            ->where('user_id', $user->id)
            ->where('produit_id', $produitId)
            ->delete();

        return $this->success($response, ['favori' => false, 'produit_id' => $produitId]);
    }

    // ── GET /api/favoris/sync-ps ────────────────────────────
    public function syncFromPS(Request $request, Response $response): Response
    {
        $user = $this->getAuthUser($request);
        if (!$user) return $this->error($response, 'UNAUTHORIZED', 'Non authentifié', 401);

        if (!$user->presta_customer_id) {
            return $this->success($response, ['synced' => 0, 'message' => 'Pas de compte PS lié']);
        }

        try {
            $psDb = DB::connection('prestashop');

            $wishlistIds = $psDb->table('MkO025_wishlist')
                ->where('id_customer', $user->presta_customer_id)
                ->pluck('id_wishlist')
                ->toArray();

            if (empty($wishlistIds)) {
                return $this->success($response, ['synced' => 0, 'message' => 'Wishlist PS vide']);
            }

            $psProducts = $psDb->table('MkO025_wishlist_product')
                ->whereIn('id_wishlist', $wishlistIds)
                ->pluck('id_product')
                ->toArray();

            if (empty($psProducts)) {
                return $this->success($response, ['synced' => 0]);
            }

            $mkoIds = DB::table('produits')
                ->whereIn('presta_product_id', $psProducts)
                ->pluck('id')
                ->toArray();

            $synced = 0;
            foreach ($mkoIds as $produitId) {
                try {
                    DB::table('favoris')->insertOrIgnore([
                        'user_id'    => $user->id,
                        'produit_id' => $produitId,
                        'source'     => 'prestashop',
                        'created_at' => date('Y-m-d H:i:s'),
                    ]);
                    $synced++;
                } catch (\Exception $e) {}
            }

            return $this->success($response, ['synced' => $synced]);

        } catch (\Exception $e) {
            return $this->error($response, 'PS_ERROR', 'Erreur connexion PrestaShop : ' . $e->getMessage(), 500);
        }
    }
}
