<?php

namespace App\Controllers\Admin;

use App\Models\Magento\PromoProduitModel;
use CodeIgniter\HTTP\ResponseInterface;

class PromosProduits extends \App\Controllers\BaseController
{
    public function index()
    {
        $model = new PromoProduitModel();

        $dateDebut = $this->request->getGet('date_debut') ?: date('Y-m-d', strtotime('-30 days'));
        $dateFin   = $this->request->getGet('date_fin') ?: date('Y-m-d');

        try {
            $produits     = $model->getPromoProduits($dateDebut, $dateFin);
            $summary      = $model->getPromoProduitsSummary($dateDebut, $dateFin);
            $unusedRules  = $model->getUnusedRules($dateDebut, $dateFin);
        } catch (\Throwable $e) {
            log_message('error', '[PromosProduits::index] ' . $e->getMessage());
            return $this->response->setJSON([
                'error' => $e->getMessage(),
                'file'  => $e->getFile(),
                'line'  => $e->getLine(),
                'trace' => $e->getTraceAsString(),
            ]);
        }

        $data = [
            'title'       => 'Promos produits',
            'produits'    => $produits,
            'summary'     => $summary,
            'unusedRules' => $unusedRules,
            'dateDebut'   => $dateDebut,
            'dateFin'     => $dateFin,
        ];

        return view('admin/promos_produits/index', $data);
    }

    /**
     * Endpoint JSON : clients ayant reçu le produit cadeau (et ses enfants configurables).
     */
    public function getClients(int $productId): ResponseInterface
    {
        if ($productId <= 0) {
            return $this->response->setJSON(['error' => 'ID produit invalide.'])->setStatusCode(400);
        }

        $model = new PromoProduitModel();

        $dateDebut = $this->request->getGet('date_debut') ?: null;
        $dateFin   = $this->request->getGet('date_fin')   ?: null;

        try {
            $clients = $model->getClientsByProductId($productId, $dateDebut, $dateFin);
        } catch (\Throwable $e) {
            log_message('error', '[PromosProduits::getClients] ' . $e->getMessage());
            return $this->response->setJSON([
                'error' => $e->getMessage(),
                'file'  => $e->getFile(),
                'line'  => $e->getLine(),
                'trace' => $e->getTraceAsString(),
            ])->setStatusCode(500);
        }

        return $this->response->setJSON([
            'product_id' => $productId,
            'clients'    => $clients,
        ]);
    }
}
