<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class PrestaShopProxyController extends Controller
{
    private $wsKey;
    private $apiUrl;

    public function __construct()
    {
        $this->wsKey = config('services.prestashop.ws_key');
        $this->apiUrl = config('services.prestashop.api_url');
    }

    /**
     * Proxy générique pour les requêtes PrestaShop
     * Sécurise le WS_KEY côté serveur
     */
    public function proxy(Request $request)
    {
        // Récupérer le endpoint demandé
        $endpoint = $request->input('endpoint', '');
        $method = $request->input('method', 'GET');
        $params = $request->input('params', []);
        $body = $request->input('body', null);

        // Construire l'URL complète
        $url = rtrim($this->apiUrl, '/') . '/' . ltrim($endpoint, '/');

        // Ajouter le WS_KEY aux paramètres
        $params['ws_key'] = $this->wsKey;
        $params['output_format'] = 'JSON';

        try {
            // Faire la requête vers PrestaShop
            $response = Http::timeout(30)
                ->withHeaders([
                    'Accept' => 'application/json',
                ])
                ->send($method, $url, [
                    'query' => $params,
                    'json' => $body,
                ]);

            // Retourner la réponse
            return response()->json([
                'success' => $response->successful(),
                'status' => $response->status(),
                'data' => $response->json(),
            ], $response->status());

        } catch (\Exception $e) {
            Log::error('PrestaShop Proxy Error', [
                'endpoint' => $endpoint,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'error' => 'Erreur lors de la communication avec PrestaShop',
                'detail' => config('app.debug') ? $e->getMessage() : null,
            ], 500);
        }
    }

    /**
     * Récupérer les produits (exemple spécifique)
     */
    public function getProducts(Request $request)
    {
        $params = [
            'display' => 'full',
            'limit' => $request->input('limit', 50),
        ];

        if ($request->has('filter')) {
            $params['filter'] = $request->input('filter');
        }

        $url = rtrim($this->apiUrl, '/') . '/products';
        $params['ws_key'] = $this->wsKey;
        $params['output_format'] = 'JSON';

        try {
            $response = Http::timeout(30)->get($url, $params);

            return response()->json([
                'success' => true,
                'data' => $response->json(),
            ]);

        } catch (\Exception $e) {
            Log::error('PrestaShop Get Products Error', [
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'error' => 'Erreur lors de la récupération des produits',
            ], 500);
        }
    }

    /**
     * Récupérer les catégories
     */
    public function getCategories(Request $request)
    {
        $url = rtrim($this->apiUrl, '/') . '/categories';
        $params = [
            'ws_key' => $this->wsKey,
            'output_format' => 'JSON',
            'display' => 'full',
        ];

        try {
            $response = Http::timeout(30)->get($url, $params);

            return response()->json([
                'success' => true,
                'data' => $response->json(),
            ]);

        } catch (\Exception $e) {
            Log::error('PrestaShop Get Categories Error', [
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'error' => 'Erreur lors de la récupération des catégories',
            ], 500);
        }
    }

    /**
     * Créer/Modifier un produit (Admin uniquement)
     */
    public function updateProduct(Request $request, $id = null)
    {
        // Validation
        $request->validate([
            'name' => 'required|string',
            'price' => 'required|numeric',
            'description' => 'nullable|string',
        ]);

        $method = $id ? 'PUT' : 'POST';
        $url = rtrim($this->apiUrl, '/') . '/products' . ($id ? "/$id" : '');

        $params = [
            'ws_key' => $this->wsKey,
            'output_format' => 'JSON',
        ];

        // Construire le XML PrestaShop (format requis)
        $xml = $this->buildProductXml($request->all(), $id);

        try {
            $response = Http::timeout(30)
                ->withHeaders([
                    'Content-Type' => 'application/xml',
                ])
                ->send($method, $url, [
                    'query' => $params,
                    'body' => $xml,
                ]);

            return response()->json([
                'success' => $response->successful(),
                'data' => $response->json(),
            ], $response->status());

        } catch (\Exception $e) {
            Log::error('PrestaShop Update Product Error', [
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'error' => 'Erreur lors de la mise à jour du produit',
            ], 500);
        }
    }

    /**
     * Construire le XML pour PrestaShop
     */
    private function buildProductXml(array $data, $id = null)
    {
        // Simplification - à adapter selon votre structure PrestaShop
        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">';
        $xml .= '<product>';
        if ($id) {
            $xml .= "<id>$id</id>";
        }
        $xml .= '<name><language id="1">' . htmlspecialchars($data['name']) . '</language></name>';
        $xml .= '<price>' . $data['price'] . '</price>';
        if (isset($data['description'])) {
            $xml .= '<description><language id="1">' . htmlspecialchars($data['description']) . '</language></description>';
        }
        $xml .= '</product>';
        $xml .= '</prestashop>';

        return $xml;
    }
}
