<?php
namespace App\Models;
use CodeIgniter\Model;

class Reports extends Model
{
    /**
     * table name
     * @var string
     */
    protected $table = 'orders';
    
    /**
     * total month
     * @return array<int|string>
     */
    private function months()
    {
        return ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
    }
    
    /**
     * Getting the year of the orders (paid_status = 1 or 3)
     * @return array
     */
    public function getOrderYear()
    {
        $result = $this->whereIn('paid_status', [1, 3])->findAll(); // ← CHANGÉ ICI
        
        $return_data = array_map(function($v) {
            return date('Y', strtotime($v['date_time']));
        }, $result);
        
        return array_values(array_unique($return_data));
    }
    
    /**
     * Getting the order reports based on the year and months
     * @param mixed $year
     * @return array<array>
     */
    public function getOrderData($year)
    {    
        if ($year) {
            $months = $this->months();
           
            // Fetch orders with paid_status = 1 or 3
            $result = $this->whereIn('paid_status', [1, 3])->findAll();
            
            $final_data = [];
            
            foreach ($months as $month) {
                $get_mon_year = $year . '-' . $month;    
                $final_data[$get_mon_year] = [];
               
                foreach ($result as $v) {
                    $month_year = date('Y-m', strtotime($v['date_time']));                    
                    if ($get_mon_year == $month_year) {
                        // Modifier le montant selon votre logique
                        if (!empty($v['discount']) && $v['discount'] > 0) {
                            $v['amount_to_display'] = $v['discount']; // Utiliser le rabais
                        } else {
                            $v['amount_to_display'] = $v['gross_amount']; // Utiliser gross_amount
                        }
                        $final_data[$get_mon_year][] = $v;
                    }
                }
            }
           
            return $final_data;
        }
        
        return [];
    }
}