<?php

namespace App\Models;

use CodeIgniter\Model;

class AutresEncaissements extends Model
{
    protected $table = 'autres_encaissements';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'type_encaissement',
        'autre_type',
        'montant',
        'mode_paiement', 
        'commentaire',
        'user_id',
        'store_id',
        'created_at',
        'updated_at'
    ];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    /**
     * Récupérer tous les encaissements avec les infos utilisateur et magasin
     * 
     * @param int|null $storeId ID du magasin (optionnel)
     * @return array
     */
    public function getEncaissementsWithDetails($storeId = null)
    {
        $builder = $this->db->table($this->table);
        $builder->select('
            autres_encaissements.*,
            CONCAT(users.firstname, " ", users.lastname) as user_name,
            users.email as user_email,
            stores.name as store_name
        ');
        $builder->join('users', 'users.id = autres_encaissements.user_id', 'left');
        $builder->join('stores', 'stores.id = autres_encaissements.store_id', 'left');
        
        if ($storeId) {
            $builder->where('autres_encaissements.store_id', $storeId);
        }
        
        $builder->orderBy('autres_encaissements.created_at', 'DESC');
        
        return $builder->get()->getResultArray();
    }

    /**
     * Récupérer un encaissement par ID avec détails
     * 
     * @param int $id ID de l'encaissement
     * @return array|null
     */
    public function getTotalEncaissementsByMode($storeId = null, $startDate = null, $endDate = null)
    {
        $builder = $this->db->table($this->table);
        $builder->select('
            SUM(CASE WHEN mode_paiement = "Espèces" THEN montant ELSE 0 END) as total_espece,
            SUM(CASE WHEN mode_paiement = "MVola" THEN montant ELSE 0 END) as total_mvola,
            SUM(CASE WHEN mode_paiement = "Virement Bancaire" THEN montant ELSE 0 END) as total_virement
        ');
        
        if ($storeId) {
            $builder->where('store_id', $storeId);
        }
        
        if ($startDate) {
            $builder->where('DATE(created_at) >=', $startDate);
        }
        
        if ($endDate) {
            $builder->where('DATE(created_at) <=', $endDate);
        }
        
        $result = $builder->get()->getRow();
        
        return [
            'total_espece' => $result ? (float)$result->total_espece : 0,
            'total_mvola' => $result ? (float)$result->total_mvola : 0,
            'total_virement' => $result ? (float)$result->total_virement : 0,
        ];
    }

    public function getEncaissementById($id)
    {
        $builder = $this->db->table($this->table);
        $builder->select('
            autres_encaissements.*,
            CONCAT(users.firstname, " ", users.lastname) as user_name,
            users.email as user_email,
            stores.name as store_name
        ');
        $builder->join('users', 'users.id = autres_encaissements.user_id', 'left');
        $builder->join('stores', 'stores.id = autres_encaissements.store_id', 'left');
        $builder->where('autres_encaissements.id', $id);
        
        return $builder->get()->getRowArray();
    }

 /**
 * Statistiques par type d'encaissement
 * 
 * @param int|null $storeId ID du magasin
 * @param string|null $startDate Date de début (Y-m-d)
 * @param string|null $endDate Date de fin (Y-m-d)
 * @return array
 */
public function getStatsByType($storeId = null, $startDate = null, $endDate = null)
{
    $builder = $this->db->table($this->table);
    
    // ✅ SÉLECTION DES CHAMPS (sans commentaire dans le SELECT)
    $builder->select('
        type_encaissement,
        mode_paiement,
        COUNT(*) as total_count,
        SUM(montant) as total_montant
    ');
    
    if ($storeId) {
        $builder->where('store_id', $storeId);
    }
    
    if ($startDate) {
        $builder->where('DATE(created_at) >=', $startDate);
    }
    
    if ($endDate) {
        $builder->where('DATE(created_at) <=', $endDate);
    }
    
    // ✅ GROUPER PAR type_encaissement ET mode_paiement
    $builder->groupBy('type_encaissement, mode_paiement');
    
    return $builder->get()->getResultArray();
}
    /**
     * Total des encaissements
     * 
     * @param int|null $storeId ID du magasin
     * @param string|null $startDate Date de début (Y-m-d)
     * @param string|null $endDate Date de fin (Y-m-d)
     * @return float
     */
    public function getTotalEncaissements($storeId = null, $startDate = null, $endDate = null)
    {
        $builder = $this->db->table($this->table);
        $builder->selectSum('montant', 'total');
        
        if ($storeId) {
            $builder->where('store_id', $storeId);
        }
        
        if ($startDate) {
            $builder->where('DATE(created_at) >=', $startDate);
        }
        
        if ($endDate) {
            $builder->where('DATE(created_at) <=', $endDate);
        }
        
        $result = $builder->get()->getRow();
        return $result ? (float)$result->total : 0;
    }
    /**
     * Nombre d'encaissements aujourd'hui
     * 
     * @param int|null $storeId ID du magasin
     * @return int
     */
    public function getTodayCount($storeId = null)
    {
        $builder = $this->db->table($this->table);
        $builder->where('DATE(created_at)', date('Y-m-d'));
        
        if ($storeId) {
            $builder->where('store_id', $storeId);
        }
        
        return $builder->countAllResults();
    }

    /**
     * Nombre total d'encaissements
     * 
     * @param int|null $storeId ID du magasin
     * @param string|null $startDate Date de début (Y-m-d)
     * @param string|null $endDate Date de fin (Y-m-d)
     * @return int
     */
    public function getTotalCount($storeId = null, $startDate = null, $endDate = null)
    {
        $builder = $this->db->table($this->table);
        
        if ($storeId) {
            $builder->where('store_id', $storeId);
        }
        
        if ($startDate) {
            $builder->where('DATE(created_at) >=', $startDate);
        }
        
        if ($endDate) {
            $builder->where('DATE(created_at) <=', $endDate);
        }
        
        return $builder->countAllResults();
    }

    /**
     * Encaissements récents (7 derniers jours)
     * 
     * @param int|null $storeId ID du magasin
     * @param int $limit Nombre de résultats
     * @return array
     */
    public function getRecentEncaissements($storeId = null, $limit = 10)
    {
        $builder = $this->db->table($this->table);
        $builder->select('
            autres_encaissements.*,
            CONCAT(users.firstname, " ", users.lastname) as user_name,
            stores.name as store_name
        ');
        $builder->join('users', 'users.id = autres_encaissements.user_id', 'left');
        $builder->join('stores', 'stores.id = autres_encaissements.store_id', 'left');
        
        if ($storeId) {
            $builder->where('autres_encaissements.store_id', $storeId);
        }
        
        $builder->where('DATE(autres_encaissements.created_at) >=', date('Y-m-d', strtotime('-7 days')));
        $builder->orderBy('autres_encaissements.created_at', 'DESC');
        $builder->limit($limit);
        
        return $builder->get()->getResultArray();
    }

    /**
     * Encaissements par utilisateur
     * 
     * @param int $userId ID de l'utilisateur
     * @param string|null $startDate Date de début
     * @param string|null $endDate Date de fin
     * @return array
     */
    public function getEncaissementsByUser($userId, $startDate = null, $endDate = null)
    {
        $builder = $this->db->table($this->table);
        $builder->where('user_id', $userId);
        
        if ($startDate) {
            $builder->where('DATE(created_at) >=', $startDate);
        }
        
        if ($endDate) {
            $builder->where('DATE(created_at) <=', $endDate);
        }
        
        $builder->orderBy('created_at', 'DESC');
        
        return $builder->get()->getResultArray();
    }

    /**
     * Recherche d'encaissements
     * 
     * @param string $keyword Mot-clé de recherche
     * @param int|null $storeId ID du magasin
     * @return array
     */
    public function searchEncaissements($keyword, $storeId = null)
    {
        $builder = $this->db->table($this->table);
        $builder->select('
            autres_encaissements.*,
            CONCAT(users.firstname, " ", users.lastname) as user_name,
            stores.name as store_name
        ');
        $builder->join('users', 'users.id = autres_encaissements.user_id', 'left');
        $builder->join('stores', 'stores.id = autres_encaissements.store_id', 'left');
        
        $builder->groupStart()
            ->like('autres_encaissements.type_encaissement', $keyword)
            ->orLike('autres_encaissements.commentaire', $keyword)
            ->orLike('CONCAT(users.firstname, " ", users.lastname)', $keyword)
        ->groupEnd();
        
        if ($storeId) {
            $builder->where('autres_encaissements.store_id', $storeId);
        }
        
        $builder->orderBy('autres_encaissements.created_at', 'DESC');
        
        return $builder->get()->getResultArray();
    }
}