<?php

namespace App\Controllers\Admin;

use App\Models\Magento\DeclinModel;

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

        $dateFin      = $this->request->getGet('date_fin') ?: date('Y-m-d');
        $fenetreJours = (int) ($this->request->getGet('fenetre') ?: 30);
        $seuilDeclin  = (float) ($this->request->getGet('seuil') ?: -20);

        if ($fenetreJours <= 0) {
            $fenetreJours = 30;
        }

        $p2Fin   = $dateFin;
        $p2Debut = date('Y-m-d', strtotime("-{$fenetreJours} days +1 day", strtotime($p2Fin)));
        $p1Fin   = date('Y-m-d', strtotime('-1 day', strtotime($p2Debut)));
        $p1Debut = date('Y-m-d', strtotime("-{$fenetreJours} days +1 day", strtotime($p1Fin)));

        try {
            $produits = $model->getDeclinProduits($p1Debut, $p1Fin, $p2Debut, $p2Fin, $seuilDeclin);
            $marques  = $model->getDeclinMarques($p1Debut, $p1Fin, $p2Debut, $p2Fin, $seuilDeclin);
        } catch (\Throwable $e) {
            log_message('error', '[Declin::index] ' . $e->getMessage());
            return $this->response->setJSON([
                'error' => $e->getMessage(),
                'file'  => $e->getFile(),
                'line'  => $e->getLine(),
                'trace' => $e->getTraceAsString(),
            ]);
        }

        $totalCaPerdu = 0;
        foreach ($produits as $produit) {
            if ($produit['variation_revenue'] < 0) {
                $totalCaPerdu += $produit['variation_revenue'];
            }
        }

        $data = [
            'title'         => 'Déclin produits / marques',
            'produits'      => $produits,
            'marques'       => $marques,
            'dateFin'       => $dateFin,
            'fenetreJours'  => $fenetreJours,
            'seuilDeclin'   => $seuilDeclin,
            'p1Debut'       => $p1Debut,
            'p1Fin'         => $p1Fin,
            'p2Debut'       => $p2Debut,
            'p2Fin'         => $p2Fin,
            'totalCaPerdu'  => $totalCaPerdu,
        ];

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