<?php

namespace App\Controllers;

use App\Models\Avance;
use App\Models\Brands;
use App\Models\Orders;
use App\Models\Products;
use App\Models\Stores;
use App\Models\Users;
use App\Models\Recouvrement;
use App\Models\SortieCaisse;
use App\Models\AutresEncaissements; // ✅ AJOUT

class Dashboard extends AdminController
{
    
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        //  Récupérer l'utilisateur en premier 
        $session = session();
        $user_id = $session->get('user');
        
        $productModel  = new Products();
        $orderModel = new Orders();
        $userModel = new Users();
        $storeModel = new Stores();
        $Brancds = new Brands();
        $allUsers = $userModel->getUserData();
        $orderPaid = $orderModel->getPaidOrderData();
        $paymentData = $orderModel->getPaymentModes();
        $Recouvrement = new Recouvrement();
        $totalRecouvrement = $Recouvrement->getTotalRecouvrements();
        $sortieCaisse = new SortieCaisse();
        $total_sortie_caisse = $sortieCaisse->getTotalSortieCaisse();
        
        // ✅ AJOUT : Récupérer les autres encaissements PAR MODE DE PAIEMENT
        $autresEncaissementsModel = new AutresEncaissements();
        
        // Déterminer si l'utilisateur est admin pour filtrer par store
        $isAdmin = in_array($user_id['group_name'], ['DAF', 'Direction', 'SuperAdmin']);
        $storeIdFilter = $isAdmin ? null : $user_id['store_id'];
        
        // Récupérer les totaux des autres encaissements par mode de paiement
        $totauxAutresEncaissements = $autresEncaissementsModel->getTotalEncaissementsByMode($storeIdFilter);
        
        $total_autres_enc_espece = $totauxAutresEncaissements['total_espece'];
        $total_autres_enc_mvola = $totauxAutresEncaissements['total_mvola'];
        $total_autres_enc_virement = $totauxAutresEncaissements['total_virement'];
        $total_autres_encaissements = $total_autres_enc_espece + $total_autres_enc_mvola + $total_autres_enc_virement;
        
        // === EXTRACTION DES SORTIES PAR MODE DE PAIEMENT ===
        $total_sortie_espece = isset($total_sortie_caisse->total_espece) ? (float) $total_sortie_caisse->total_espece : 0;
        $total_sortie_mvola = isset($total_sortie_caisse->total_mvola) ? (float) $total_sortie_caisse->total_mvola : 0;
        $total_sortie_virement = isset($total_sortie_caisse->total_virement) ? (float) $total_sortie_caisse->total_virement : 0;
        
        // === TOTAUX RECOUVREMENT ===
        $me = isset($totalRecouvrement->me) ? (float) $totalRecouvrement->me : 0;
        $bm = isset($totalRecouvrement->bm) ? (float) $totalRecouvrement->bm : 0;
        $be = isset($totalRecouvrement->be) ? (float) $totalRecouvrement->be : 0;
        $mb = isset($totalRecouvrement->mb) ? (float) $totalRecouvrement->mb : 0;
        
        // Avances
        $Avance = new Avance();
        $totalAvance = $Avance->getTotalAvance();
        $paymentDataAvance = $Avance->getPaymentModesAvance();
        
        // === TOTAUX PAIEMENTS ORDERS ===
        $total_orders = isset($paymentData->total) ? (float) $paymentData->total : 0;
        $mv1_orders = isset($paymentData->total_mvola1) ? (float) $paymentData->total_mvola1 : 0;
        $mv2_orders = isset($paymentData->total_mvola2) ? (float) $paymentData->total_mvola2 : 0;
        $es1_orders = isset($paymentData->total_espece1) ? (float) $paymentData->total_espece1 : 0;
        $es2_orders = isset($paymentData->total_espece2) ? (float) $paymentData->total_espece2 : 0;
        $vb1_orders = isset($paymentData->total_virement_bancaire1) ? (float) $paymentData->total_virement_bancaire1 : 0;
        $vb2_orders = isset($paymentData->total_virement_bancaire2) ? (float) $paymentData->total_virement_bancaire2 : 0;
        
        // === TOTAUX PAIEMENTS AVANCES ===
        $total_avances = isset($paymentDataAvance->total) ? (float) $paymentDataAvance->total : 0;
        $mv_avances = isset($paymentDataAvance->total_mvola) ? (float) $paymentDataAvance->total_mvola : 0;
        $es_avances = isset($paymentDataAvance->total_espece) ? (float) $paymentDataAvance->total_espece : 0;
        $vb_avances = isset($paymentDataAvance->total_virement_bancaire) ? (float) $paymentDataAvance->total_virement_bancaire : 0;
        
        // === COMBINAISON ORDERS + AVANCES + AUTRES ENCAISSEMENTS (BRUT) ===
        $total_mvola_brut = $mv1_orders + $mv2_orders + $mv_avances + $total_autres_enc_mvola;
        $total_espece_brut = $es1_orders + $es2_orders + $es_avances + $total_autres_enc_espece;
        $total_vb_brut = $vb1_orders + $vb2_orders + $vb_avances + $total_autres_enc_virement;
        $total_brut = $total_orders + $total_avances + $total_autres_encaissements;
        
        // === AJUSTEMENTS AVEC RECOUVREMENTS ET SORTIES ===
        $total_mvola_final = $total_mvola_brut - $me - $mb + $bm - $total_sortie_mvola;
        $total_espece_final = $total_espece_brut + $me + $be - $total_sortie_espece;
        $total_virement_bancaire_final = $total_vb_brut - $be - $bm + $mb - $total_sortie_virement;
        
        // === CALCUL DU TOTAL GÉNÉRAL ===
        $total_sortie_global = $total_sortie_espece + $total_sortie_mvola + $total_sortie_virement;
        $total_final = $total_brut - $total_sortie_global;
        
        // ✅ MODIFICATION : La caissière voit EXACTEMENT les mêmes montants que Direction/Conseil
        $data = [
            // === POUR DIRECTION/CONSEIL (AVEC TOUS LES AJUSTEMENTS) ===
            'total' => $total_final,
            'total_mvola' => $total_mvola_final,
            'total_espece' => $total_espece_final,
            'total_virement_bancaire' => $total_virement_bancaire_final,
            
            // === POUR CAISSIÈRE (MÊME CALCUL QUE DIRECTION) ===
            'total_caisse' => $total_final,
            'total_mvola_caisse' => $total_mvola_final,
            'total_espece_caisse' => $total_espece_final,
            'total_vb_caisse' => $total_virement_bancaire_final,
            
            // === DÉTAIL POUR LA CAISSIÈRE ===
            'total_orders_only' => $total_orders,
            'total_avances' => $total_avances,
            
            // ✅ AJOUT : Détails des autres encaissements
            'total_autres_encaissements' => $total_autres_encaissements,
            'total_autres_enc_espece' => $total_autres_enc_espece,
            'total_autres_enc_mvola' => $total_autres_enc_mvola,
            'total_autres_enc_virement' => $total_autres_enc_virement,
            
            // ✅ Détails des sorties
            'total_sorties' => $total_sortie_global,
            'total_sortie_espece' => $total_sortie_espece,
            'total_sortie_mvola' => $total_sortie_mvola,
            'total_sortie_virement' => $total_sortie_virement,
            
            // ✅ Détails des recouvrements
            'recouvrement_me' => $me,
            'recouvrement_be' => $be,
            'recouvrement_bm' => $bm,
            'recouvrement_mb' => $mb,
            'total_recouvrements' => $me + $be + $bm + $mb,
            
            // Détail avances par mode de paiement
            'total_avances_mvola' => $mv_avances,
            'total_avances_espece' => $es_avances,
            'total_avances_virement' => $vb_avances,
            
            // Détail orders par mode de paiement
            'total_mvola_orders' => $mv1_orders + $mv2_orders,
            'total_espece_orders' => $es1_orders + $es2_orders,
            'total_vb_orders' => $vb1_orders + $vb2_orders,
            
            // ✅ Montants bruts (AVEC autres encaissements)
            'total_brut' => $total_brut,
            'total_mvola_brut' => $total_mvola_brut,
            'total_espece_brut' => $total_espece_brut,
            'total_vb_brut' => $total_vb_brut,
        ];

        // === ✅ Compter les produits selon le store de l'utilisateur ===
        $data['total_products'] = $productModel->countProductsByUserStore();
        
        // === ✅ Récupérer le nom du store pour l'affichage ===
        if (!$isAdmin && !empty($user_id['store_id']) && $user_id['store_id'] != 0) {
            $store = $storeModel->getStoresData($user_id['store_id']);
            $data['store_name'] = $store['name'] ?? 'Votre magasin';
        } else {
            $data['store_name'] = 'Tous les magasins';
        }
        
        $data['total_paid_orders'] = $orderModel->countTotalPaidOrders();
        $data['total_users'] = $userModel->countTotalUsers();
        $data['total_stores'] = $storeModel->countTotalStores();
        
        
        $newData = [];
        for ($i=0; $i < count($orderPaid); $i++) {
            $transitionData = [];
            for ($k=0; $k < count($allUsers); $k++) { 
                if ($allUsers[$k]['id'] == $orderPaid[$i]['user_id']) {
                    $transitionData2 = [
                        'userId' => $allUsers[$k]['id'],
                        'userName' => $allUsers[$k]['username'],
                        'billId' => $orderPaid[$i]['id'],
                        'billNo' => $orderPaid[$i]['bill_no'],
                        'dateVente' => $orderPaid[$i]['date_time'],
                        'montantNet' => $orderPaid[$i]['net_amount'],
                    ];
                    $transitionData[] = $transitionData2;
                }
            }
            $newData[] = $transitionData;
        }
        
        //data for the camember in dashboard
        $totalStoreOrder = $orderModel->getTotalOrderPerStore();
        $totalOrders = $orderModel->getTotalOrders(); 
        $totalOrdersCount = (int) $totalOrders->total_orders;
        if($totalOrdersCount>0){
            foreach ($totalStoreOrder as $totalOrdersInStore) {
                $storeList = $storeModel->getStoreById($totalOrdersInStore->store_id);
                $labelStore[] = $storeList->name ?? 'Inconnu';
                $totalPerStore[] = ((int)$totalOrdersInStore->total / $totalOrdersCount) * 100; 
            }
        }
        else{
            $labelStore[] = "zéro vente";
            $totalPerStore[] = 0;
        }
        $data['labelStore'] = json_encode($labelStore);
        $data['totalPerStore'] = json_encode($totalPerStore);

        // filter to keep non empty array
        $filteredArray = array_filter($newData, function($item) {
            return !empty($item);
        });

        // Re-index the array
        $userWhoSoldProducts = array_values($filteredArray);

        // Count occurrences of each userId
        $userIdCounts = array_reduce($userWhoSoldProducts, function($carry, $item) {
            $userId = $item[0]['userId'];
            if (!isset($carry[$userId])) {
                $carry[$userId] = 0;
            }
            $carry[$userId]++;
            return $carry;
        }, []);

        $countId = [];
        foreach ($userIdCounts as $key => $value) {
            $countId[] = $key;
        }

        $data['count_id'] = $countId;
        
        $data['is_admin'] = false;
        $data['isCommercial'] = false;
        $data['isChef'] = false;
        $data['isCaissier'] = false;
        $data['isMecanicien'] = false;
        $data['isSecurite'] = false;
        
        if ($user_id['group_name'] == "Direction" || $user_id['group_name'] == "DAF" || $user_id['group_name'] == "SuperAdmin") {
            $data['is_admin'] = true;
        }

        $data['user_order'] = [];
        
        if ($user_id['group_name'] == \strtoupper("commerciale")) {
            $data['isCommercial'] = true;
            $data['user_order'] = json_encode($orderModel->getSingleStat($user_id['id']), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
        }
        if ($user_id['group_name'] == "Cheffe d'Agence") {
            $data['isChef'] = true;
        }
        
        // ✅ AJOUT POUR CAISSIER : Passer les données de performance
        if ($user_id['group_name'] == "Caissière") {
            $data['isCaissier'] = true;
        }
        
        if ($user_id['group_name'] == "MECANICIEN") {
            $data['isMecanicien'] = true;
        }
        if ($user_id['group_name'] == "Sécurité" || $user_id['group_name'] == "SECURITE") {
            $data['isSecurite'] = true;
        }
        
        $data['page_title'] = 'Dashboard';
        $data['marques_total'] = json_encode($orderModel->getTotalProductvente());
        $data['marques'] = json_encode($Brancds->getName());
        
        $Orders = new Orders();
        $Products = new Products();
        $Stores = new Stores();
        $productVente = $Orders->getTotalProductvente();
        $produitStock = $Products->getProductData();
        $stor = $Stores->getActiveStore();

        $data['ventes'] = \json_encode($productVente);
        $data['stock'] = \json_encode($produitStock);
        $data['stores'] = $stor;

        // Load the dashboard view with the data
        return  $this->render_template('dashboard', $data);
    }

}