<?php

namespace App\Controllers\Admin;

use App\Models\Magento\MargeModel;

class Marges extends \App\Controllers\BaseController
{
    public function index()
    {
        $margeModel = new MargeModel();

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

        $dateDebutSql = $dateDebut . ' 00:00:00';
        $dateFinSql = $dateFin . ' 23:59:59';

        $produits = $margeModel->getProduitsMargeFaible($dateDebutSql, $dateFinSql);
        $produits = $this->applyExclusions($produits, 'marges_list', 'product_id');

        $data = [
            'produits'   => $produits,
            'dateDebut'  => $dateDebut,
            'dateFin'    => $dateFin,
            'title'      => 'Analyse des marges',
        ];

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

    public function detail(int $productId)
    {
        $margeModel = new MargeModel();

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

        $commandes = $margeModel->getCommandesParProduit($productId, $dateDebutSql, $dateFinSql);
        $produit = $commandes[0] ?? null;

        $productName = $produit['product_name'] ?? 'Produit #' . $productId;

        $data = [
            'productId'  => $productId,
            'produit'    => $produit,
            'commandes'  => $commandes,
            'dateDebut'  => $dateDebut,
            'dateFin'    => $dateFin,
            'title'      => 'Marge : ' . $productName,
        ];

        return view('admin/marges/detail', $data);
    }
}
