<?php

namespace App\Controllers\Admin;

use App\Libraries\ClaudeAnalysisClient;
use App\Models\Magento\VentesFiltresModel;
use CodeIgniter\HTTP\ResponseInterface;

class AnalyseVentes extends \App\Controllers\BaseController
{
    public function index()
    {
        return view('admin/analyseventes/index', [
            'title' => 'Analyse ventes',
        ]);
    }

    public function searchCriteria(): ResponseInterface
    {
        $query = trim($this->request->getGet('q') ?? '');
        $target = strtolower(trim((string)($this->request->getGet('target') ?? 'all')));
        $model = new VentesFiltresModel();

        $products = [];
        $brands = [];

        if ($target === 'product' || $target === 'all') {
            $products = $model->searchProducts($query);
        }
        if ($target === 'brand' || $target === 'all') {
            $brands = $model->searchBrands($query);
        }

        return $this->response->setJSON([
            'products' => $products,
            'brands' => $brands,
        ]);
    }

    public function getAnalysis(): ResponseInterface
    {
        $dateFrom = trim((string)($this->request->getGet('date_from') ?? ''));
        $dateTo = trim((string)($this->request->getGet('date_to') ?? ''));

        $targets = $this->request->getGet('targets') ?? [];
        if (is_string($targets)) {
            $decoded = json_decode($targets, true);
            $targets = is_array($decoded) ? $decoded : [];
        }

        $model = new VentesFiltresModel();
        $data = $model->getSalesAnalysis($dateFrom, $dateTo, is_array($targets) ? $targets : []);

        return $this->response->setJSON([
            'months' => $data['months'] ?? [],
            'top_products' => $data['top_products'] ?? [],
            'message' => empty($data['months']) ? 'Aucune donnée trouvée pour cette sélection.' : '',
        ]);
    }

    public function getAiInsights(): ResponseInterface
    {
        $dateFrom = trim((string)($this->request->getPost('date_from') ?? ''));
        $dateTo = trim((string)($this->request->getPost('date_to') ?? ''));

        $targets = $this->request->getPost('targets') ?? [];
        if (is_string($targets)) {
            $decoded = json_decode($targets, true);
            $targets = is_array($decoded) ? $decoded : [];
        }

        if ($dateFrom === '' || $dateTo === '' || !is_array($targets) || empty($targets)) {
            return $this->response->setStatusCode(422)->setJSON([
                'insights' => '',
                'message' => 'Paramètres invalides pour l\'analyse IA.',
            ]);
        }

        $model = new VentesFiltresModel();
        $data = $model->getSalesAnalysis($dateFrom, $dateTo, $targets);

        if (empty($data['months'])) {
            return $this->response->setJSON([
                'insights' => '',
                'message' => 'Aucune donnée disponible pour générer une analyse IA.',
            ]);
        }

        $client = new ClaudeAnalysisClient();
        if (!$client->isConfigured()) {
            return $this->response->setStatusCode(500)->setJSON([
                'insights' => '',
                'message' => 'ANTHROPIC_API_KEY manquant dans la configuration serveur.',
            ]);
        }

        try {
            $result = $client->generateSalesInsights([
                'date_from' => $dateFrom,
                'date_to' => $dateTo,
                'targets' => $targets,
                'months' => $data['months'] ?? [],
                'top_products' => $data['top_products'] ?? [],
            ]);
        } catch (\Throwable $e) {
            return $this->response->setStatusCode(500)->setJSON([
                'insights' => '',
                'message' => 'Erreur IA: ' . $e->getMessage(),
            ]);
        }

        return $this->response->setJSON([
            'insights' => (string)($result['text'] ?? ''),
            'usage' => $result['usage'] ?? ['prompt_tokens' => 0, 'completion_tokens' => 0, 'total_tokens' => 0],
            'estimated_cost_usd' => (float)($result['estimated_cost_usd'] ?? 0),
            'model' => (string)($result['model'] ?? ''),
            'message' => '',
        ]);
    }
}
