<?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;
class Dashboard extends AdminController
{
    
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $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();
        $total_sortie_caisse1= $total_sortie_caisse->mr;
        // dd($totalRecouvrement);
        $total_recouvrement_me = $totalRecouvrement->me;
        $total_recouvrement_bm = $totalRecouvrement->bm;
        $total_recouvrement_be = $totalRecouvrement->be;
        $total_recouvrement_mb = $totalRecouvrement->mb;
        // total avance
        $Avance =  new Avance();
        $totalAvance = $Avance->getTotalAvance();
        $total_avance = $totalAvance->ta;
        // Initialisation des totaux avec 0 au cas où il n'y aurait pas de données
        $total = isset($paymentData->total) ? $paymentData->total : 0;
        $total_mvola1 = isset($paymentData->total_mvola1) ? $paymentData->total_mvola1 : 0;
        $total_mvola2 = isset($paymentData->total_mvola2) ? $paymentData->total_mvola2 : 0;
        $total_espece1 = isset($paymentData->total_espece1) ? $paymentData->total_espece1 : 0;
        $total_espece2 = isset($paymentData->total_espece2) ? $paymentData->total_espece2 : 0;
        $total_virement_bancaire1 = isset($paymentData->total_virement_bancaire1) ? $paymentData->total_virement_bancaire1 : 0;
        $total_virement_bancaire2 = isset($paymentData->total_virement_bancaire2) ? $paymentData->total_virement_bancaire2 : 0;

        $total_mvola = $total_mvola1 + $total_mvola2;
        $total_mvola1 = $total_mvola - $total_recouvrement_me - $total_recouvrement_mb + $total_recouvrement_bm;

        $total_espece = $total_espece1 + $total_espece2;
        $total_espece1 = $total_espece + $total_recouvrement_me + $total_recouvrement_be - $total_sortie_caisse1 + $total_avance;
        
        //die("Test Stephane " . $total_recouvrement_me);
        $total_virement_bancaire = $total_virement_bancaire1 + $total_virement_bancaire2;
        $total_virement_bancaire1 = $total_virement_bancaire - $total_recouvrement_be -$total_recouvrement_bm + $total_recouvrement_mb;

        // check avance expired
        $avance = new Avance();
        $avance->checkExpiredAvance();
        
        $data = [
            'total' => $total,
            'total_mvola' => $total_mvola1,
            'total_espece' => $total_espece1,
            'total_virement_bancaire' => $total_virement_bancaire1,
            'user_permission' => $this->permission,
            
        ];

        $data['total_products'] = $productModel->countTotalProducts();
        $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); // Keep only non-empty arrays
        });

        // Re-index the array (optional, if you want sequential keys)
        $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;
        // Check if the user is an Conseil
        $session = session();
        $user_id = $session->get('user');
        $data['is_admin'] = false;
        $data['isCommercial'] = false;
        $data['isChef'] = false;
        $data['isCaissier'] = false;
        $data['isMecanicien'] = false;
        if ($user_id['group_name'] == "Direction" || $user_id['group_name'] == "Conseil") {
            $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;
          }
        if ($user_id['group_name'] == "Caissière") {
            $data['isCaissier'] = true;
        }
        if ($user_id['group_name'] == "MECANICIEN") {
            $data['isMecanicien'] = 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);
    }

}