<?php
namespace App\Models;

use CodeIgniter\Model;
class Recouvrement extends Model{
   /**
     * table name
     * @var string
     */
    protected $table = 'recouvrement';
    protected $primaryKey = 'recouvrement_id';

    protected $allowedFields = [
        'recouvrement_montant', 'recouvrement_date','get_money', 'send_money', 'recouvrement_personnel','user_id','store_id',]; 

        public function addRecouvrement( array $data) {
            try {
                return  $this->insert($data);
            } catch (\Exception $e) {
                log_message('error', 'Erreur lors de l\'ajout du recouvrement : ' . $e->getMessage());
                return false;
            }  
        }

        public function updateRecouvrement(int $id, array $data) {
            // Vérifier si l'ID est valide (par exemple, positif et non nul)
            if ($id <= 0) {
                log_message('error', 'ID invalide pour la mise à jour du recouvrement : ' . $id);
                return false;
            }
        
            try {
                // Essayer de mettre à jour les données
                return $this->update($id, $data);
            } catch (\Exception $e) {
                // En cas d'exception, loguer l'erreur
                log_message('error', 'Erreur lors de la mise à jour du recouvrement : ' . $e->getMessage());
                return false; 
            }
        }
        

        public function getRecouvrementsByDate(string $date) {
            try {
                return $this->where('recouvrement_date', $date)->findAll(); // Récupère tous les recouvrements pour une date donnée
            } catch (\Exception $e) {
                log_message('error', 'Erreur lors de la récupération des recouvrements par date : ' . $e->getMessage());
                return false; // Retourne false en cas d'erreur
            }
        }
        
        
        public function getAllRecouvrements(int $id=null) {
            if($id){
                try {
                    return $this->where('user_id',$id)
                    ->orderBy('recouvrement_date', 'DESC') 
                    ->findAll();
                } catch (\Exception $e) {
                    log_message('error', 'Erreur lors de la récupération des recouvrements : ' . $e->getMessage());
                    return false;
                }
            }
            try {
                return $this->orderBy('recouvrement_date', 'DESC') ->findAll();
            } catch (\Exception $e) {
                log_message('error', 'Erreur lors de la récupération des recouvrements : ' . $e->getMessage());
                return false;
            }
        }

        
        public function getTotalRecouvrements(int $id = null, $start_date = null, $end_date =  null) {
            $session = session();
            $users =  $session->get('user');
            $isAdmin = in_array($users['group_name'], ['DAF', 'Direction', 'SuperAdmin']);
            if($isAdmin){
                if ($id) {
                return $this->db->table('recouvrement')
                ->select('
                    COUNT(*) as tr,
                    SUM(CASE WHEN send_money = "MVOLA" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS me,
                    SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "MVOLA" THEN recouvrement_montant ELSE 0 END) AS bm,
                    SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS be,
                    SUM(CASE WHEN send_money = "MVOLA" AND get_money = "Virement Bancaire" THEN recouvrement_montant ELSE 0 END) AS mb,

                ')
                ->where('user_id',$id)
                ->get()
                ->getRowObject();
            }
            if ($start_date && $end_date) {
                return $this->db->table('recouvrement')
                    ->select('
                        COUNT(*) as tr,
                        SUM(CASE WHEN send_money = "MVOLA" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS me,
                        SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "MVOLA" THEN recouvrement_montant ELSE 0 END) AS bm,
                        SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS be,
                        SUM(CASE WHEN send_money = "MVOLA" AND get_money = "Virement Bancaire" THEN recouvrement_montant ELSE 0 END) AS mb
                    ')
                    ->where("recouvrement_date BETWEEN '$start_date' AND '$end_date'")
                    ->get()
                    ->getRowObject();
            }
            
            try {
                return $this->db->table('recouvrement')
                ->select('
                    SUM(CASE WHEN send_money = "MVOLA" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS me,
                    SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "MVOLA" THEN recouvrement_montant ELSE 0 END) AS bm,
                    SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS be,
                    SUM(CASE WHEN send_money = "MVOLA" AND get_money = "Virement Bancaire" THEN recouvrement_montant ELSE 0 END) AS mb,

                ')
                ->get()
                ->getRowObject();
            } catch (\Exception $e) {
                log_message('error', 'Erreur lors de la récupération des recouvrements : ' . $e->getMessage());
                return false;
            }
            } else {
                if ($id) {
                    return $this->db->table('recouvrement')
                        ->select('
                            COUNT(*) as tr,
                            SUM(CASE WHEN send_money = "MVOLA" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS me,
                            SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "MVOLA" THEN recouvrement_montant ELSE 0 END) AS bm,
                            SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS be,
                            SUM(CASE WHEN send_money = "MVOLA" AND get_money = "Virement Bancaire" THEN recouvrement_montant ELSE 0 END) AS mb,

                        ')
                        ->where('user_id', $id)
                        ->get()
                        ->getRowObject();
                }
                if ($start_date && $end_date) {
                return $this->db->table('recouvrement')
                    ->select('
                        COUNT(*) as tr,
                        SUM(CASE WHEN send_money = "MVOLA" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS me,
                        SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "MVOLA" THEN recouvrement_montant ELSE 0 END) AS bm,
                        SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS be,
                        SUM(CASE WHEN send_money = "MVOLA" AND get_money = "Virement Bancaire" THEN recouvrement_montant ELSE 0 END) AS mb
                    ')
                    ->where('store_id', $users['store_id'])
                    ->where("recouvrement_date BETWEEN '$start_date' AND '$end_date'")
                    ->get()
                    ->getRowObject();
            }
                try {
                    return $this->db->table('recouvrement')
                        ->select('
                            COUNT(*) as tr,
                            SUM(CASE WHEN send_money = "MVOLA" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS me,
                            SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "MVOLA" THEN recouvrement_montant ELSE 0 END) AS bm,
                            SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS be,
                            SUM(CASE WHEN send_money = "MVOLA" AND get_money = "Virement Bancaire" THEN recouvrement_montant ELSE 0 END) AS mb,

                        ')
                        ->where('store_id', $users['store_id'])
                        ->get()
                        ->getRowObject();
                } catch (\Exception $e) {
                    log_message('error', 'Erreur lors de la récupération des recouvrements : ' . $e->getMessage());
                    return false;
                }
            }
            
        }
        
        public function deleteRecouvrement(int $id) {
            try{
                return $this->delete($id);
            }catch(\Exception $e){
                log_message('error', 'Erreur lors de la récupération des recouvrements par plage de dates : ' . $e->getMessage());
                return false; 
            }
        }

        public function getRecouvrementSingle(int $id)
    {
        $reparation = $this->select('*')
            ->where('recouvrement_id', $id)
            ->first();
        // return $this->where('user_id', $id)->findAll();

        return $reparation;
    }
    public function getTotalByPaymentMode($start_date = null, $end_date = null)
{
    $session = session();
    $users = $session->get('user');
    $isAdmin = in_array($users['group_name'], ['DAF', 'Direction', 'SuperAdmin']);
    
    $builder = $this->db->table('recouvrement');
    
    // Conditions de base selon le rôle
    if (!$isAdmin) {
        $builder->where('store_id', $users['store_id']);
    }
    
    // Filtre par date si fourni
    if ($start_date && $end_date) {
        $builder->where("recouvrement_date BETWEEN '$start_date' AND '$end_date'");
    }
    
    return $builder->select('
        SUM(CASE WHEN send_money = "MVOLA" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS me,
        SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "MVOLA" THEN recouvrement_montant ELSE 0 END) AS bm,
        SUM(CASE WHEN send_money = "Virement Bancaire" AND get_money = "En espèce" THEN recouvrement_montant ELSE 0 END) AS be,
        SUM(CASE WHEN send_money = "MVOLA" AND get_money = "Virement Bancaire" THEN recouvrement_montant ELSE 0 END) AS mb
    ')->get()->getRowObject();
}
}