<?php

namespace App\Controllers\Admin;

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

class Dealers extends \App\Controllers\BaseController
{
    protected $helpers = ['dealer'];

    public function index()
    {
        $cache = \Config\Services::cache();
        $model = new DealerModel();

        $dealers = $cache->remember('dealers_list', 300, static function () use ($model) {
            return $model->getDealers();
        });

        $summary = $cache->remember('dealers_summary', 300, static function () use ($model) {
            return $model->getDealersSummary();
        });

        return view('admin/dealers/index', [
            'title'     => 'Dealers',
            'dealers'   => $dealers,
            'summary'   => $summary,
        ]);
    }

    public function detail(int $dealerId)
    {
        if ($dealerId <= 0) {
            return redirect()->to('/admin/dealers')->with('error', 'ID dealer invalide.');
        }

        $model = new DealerModel();
        $dealer = $model->getDealerById($dealerId);

        if ($dealer === null) {
            return redirect()->to('/admin/dealers')->with('error', 'Dealer introuvable.');
        }

        $yearComparison = $model->getDealerYearComparison($dealerId);
        $curve = $model->getDealerMonthlyCurve($dealerId, 2);
        $customersWithCa = $model->getCustomersByDealerWithCa($dealerId);

        $dateDebut = date('Y-m-d', strtotime('-2 years'));
        $dateFin = date('Y-m-d');

        $chartMonths = array_column($curve, 'month');
        $chartCommandes = array_column($curve, 'nb_commandes');
        $chartCa = array_column($curve, 'ca_total');

        return view('admin/dealers/detail', [
            'title'               => 'Dealer : ' . ($dealer['admin_fullname'] ?? 'Détail'),
            'dealer'              => $dealer,
            'year_comparison'     => $yearComparison,
            'curve'               => $curve,
            'customers_with_ca'   => $customersWithCa,
            'date_debut'          => $dateDebut,
            'date_fin'            => $dateFin,
            'chart_months'        => $chartMonths,
            'chart_commandes'     => $chartCommandes,
            'chart_ca'            => $chartCa,
        ]);
    }

    /**
     * Endpoint JSON pour les courbes d'un dealer (2 dernières années).
     */
    public function getCurve(int $dealerId): ResponseInterface
    {
        if ($dealerId <= 0) {
            return $this->response->setJSON(['error' => 'ID dealer invalide.'])->setStatusCode(400);
        }

        $model = new DealerModel();
        $curve = $model->getDealerMonthlyCurve($dealerId, 2);

        return $this->response->setJSON([
            'months'     => array_column($curve, 'month'),
            'commandes'  => array_column($curve, 'nb_commandes'),
            'ca'         => array_column($curve, 'ca_total'),
        ]);
    }
}
