<?php

namespace App\Controllers;

use App\Controllers\AdminController;
use App\Models\Orders;
use App\Models\Recouvrement;
use App\Models\SortieCaisse;
use App\Models\Avance;

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

    private $pageTitle = 'Recouvrements';

        public function index()
    {
        $this->verifyRole('viewRecouvrement');

        $data = $this->getTotalsArray();

        $this->render_template('recouvrement/index', $data);
    }


    // Create an AJAX endpoint to access the fetchTotal() function
    public function getTotalData()
    {
        echo $this->fetchTotal();
        exit;
    }

        public function fetchTotal()
    {
        $data = $this->getTotalsArray();

        return $this->response->setJSON($data);
    }

     private function getTotalsArray(): array
    {
        $orders        = new Orders();
        $recouvrement  = new Recouvrement();
        $sortieCaisse  = new SortieCaisse();
        $avance        = new Avance();

        // Récupère les données brutes
        $paymentData            = $orders->getPaymentModes();
        $total_sortie_caisse    = $sortieCaisse->getTotalSortieCaisse()->mr ?? 0;
        $totalRecouvrement      = $recouvrement->getTotalRecouvrements();

        // Totaux recouvrement
        $me = $totalRecouvrement->me ?? 0;
        $bm = $totalRecouvrement->bm ?? 0;
        $be = $totalRecouvrement->be ?? 0;
        $mb = $totalRecouvrement->mb ?? 0;
        $ta = $avance->getTotalAvance()->ta ?? 0;

        // Totaux paiements initiaux
        $t       = $paymentData->total           ?? 0;
        $mv1     = $paymentData->total_mvola1    ?? 0;
        $mv2     = $paymentData->total_mvola2    ?? 0;
        $es1     = $paymentData->total_espece1   ?? 0;
        $es2     = $paymentData->total_espece2   ?? 0;
        $vb1     = $paymentData->total_virement_bancaire1 ?? 0;
        $vb2     = $paymentData->total_virement_bancaire2 ?? 0;

        // Calculs
        $total_mvola   = $mv1 + $mv2;
        $mv_calc       = $total_mvola - $me - $mb + $bm;

        $total_espece  = $es1 + $es2;
        $es_calc       = $total_espece + $me + $be - $total_sortie_caisse + $ta;

        $total_vb      = $vb1 + $vb2;
        $vb_calc       = $total_vb - $be - $bm + $mb;

        // Retourne le tableau à utiliser
        return [
            'total'                   => $t,
            'total_mvola'             => $mv_calc,
            'total_espece'            => $es_calc,
            'total_virement_bancaire' => $vb_calc,
            'page_title'              => $this->pageTitle,
            'permission'             => $this->permission
        ];
    }

    public function fetchRecouvrementData()
    {
        helper(['url', 'form']);
        $Recouvrement = new Recouvrement();

        // Initialiser les variables pour DataTables
        $draw = intval($this->request->getVar('draw'));
        $session = session();
        $users = $session->get('user');
        if($users['group_name'] === "Caissière"){
            $data = $Recouvrement->getAllRecouvrements($users['id'] );
            $totalRecords = count($data); // Nombre total de recouvrements

            $result = [
                "draw" => $draw,
                "recordsTotal" => $totalRecords,
                "recordsFiltered" => $totalRecords,
                "data" => []
            ];

            foreach ($data as $key => $value) {
                $buttons = '';
                if (in_array('updateRecouvrement', $this->permission)) {
                    $buttons .= '<button type="button" class="btn btn-default" onclick="editFunc(' . $value['recouvrement_id'] . ')" data-toggle="modal" data-target="#updateModal"><i class="fa fa-pencil"></i></button>';
                }

                if (in_array('deleteRecouvrement', $this->permission)) {
                    $buttons .= ' <button type="button" class="btn btn-danger" onclick="removeFunc(' . $value['recouvrement_id'] . ')" data-toggle="modal" data-target="#removeModal"><i class="fa fa-trash"></i></button>';
                }
                $result['data'][$key] = [
                    $value['recouvrement_id'],
                    number_format($value['recouvrement_montant'], 0, '.', ' '),
                    $value['recouvrement_date'],
                    $value['recouvrement_personnel'],
                    $value['send_money'],
                    $value['get_money'],
                    $buttons
                ];
            }
            return $this->response->setJSON($result);
        }

        $data = $Recouvrement->getAllRecouvrements();
        $totalRecords = count($data); // Nombre total de recouvrements

        $result = [
            "draw" => $draw,
            "recordsTotal" => $totalRecords,
            "recordsFiltered" => $totalRecords,
            "data" => []
        ];

        foreach ($data as $key => $value) {
            $buttons = '';
            if (in_array('updateRecouvrement', $this->permission)) {
                $buttons .= '<button type="button" class="btn btn-default" onclick="editFunc(' . $value['recouvrement_id'] . ')" data-toggle="modal" data-target="#updateModal"><i class="fa fa-pencil"></i></button>';
            }

            if (in_array('deleteRecouvrement', $this->permission)) {
                $buttons .= ' <button type="button" class="btn btn-danger" onclick="removeFunc(' . $value['recouvrement_id'] . ')" data-toggle="modal" data-target="#removeModal"><i class="fa fa-trash"></i></button>';
            }
            $result['data'][$key] = [
                $value['recouvrement_id'],
                number_format($value['recouvrement_montant'], 0, '.', ' '),
                $value['recouvrement_date'],
                $value['recouvrement_personnel'],
                $value['send_money'],
                $value['get_money'],
                $buttons
            ];
        }
        return $this->response->setJSON($result);
    }


    public function removeRecouvrement()
    {
        $this->verifyRole('deleteRecouvrement');
        $recouvrement_id = $this->request->getPost('recouvrement_id');


        $response = [];

        if ($recouvrement_id) {
            $Recouvrement = new Recouvrement();
            if ($Recouvrement->deleteRecouvrement($recouvrement_id)) {
                $response['success'] = true;
                $response['messages'] = "Recouvrement supprimé avec succès !";
            } else {
                $response['success'] = false;
                $response['messages'] = "Erreur lors de la suppression du recouvrement.";
            }
        } else {
            $response['success'] = false;
            $response['messages'] = "Veuillez actualiser la page.";
        }
        return $this->response->setJSON($response);
    }

    public function createRecouvrement()
    {
        $this->verifyRole('createRecouvrement');

        $data['page_title'] = $this->pageTitle;

        // echo "<pre>";
        // die(var_dump($this->request->getPost()));

        // Load validation service
        $validation = \Config\Services::validation();

        $validation->setRules([
            'send_mode' => 'required',
            'get_mode' => 'required',
            'recouvrement_montant' => 'required',
            'recouvrement_date' => 'required',
        ]);

        $validationData = [
            'send_mode' => $this->request->getPost('send_mode'),
            'get_mode' => $this->request->getPost('get_mode'),
            'recouvrement_montant' => $this->request->getPost('recouvrement_montant'),
            'recouvrement_date' => $this->request->getPost('recouvrement_date'),
        ];

        // Set validation rules

        $Notification = new NotificationController();
        $Recouvrement = new Recouvrement();
        // $recouvrement_id = $this->request->getPost('recouvrement_id');
        $session = session();
        $users = $session->get('user');
        if ($users && isset($users['firstname'], $users['lastname'])) {
            $fullname = $users['firstname'] . ' ' . $users['lastname'];
        }

        // $orders = new Orders();
        // $Recouvrement = new Recouvrement();
        // $paymentData = $orders->getPaymentModes();
        // $totalRecouvrement = $Recouvrement->getTotalRecouvrements();
        // $total_recouvrement = $totalRecouvrement->total_recouvrement;
        // Initialisation des totaux avec 0 au cas où il n'y aurait pas de données
        // $total_mvola1 = isset($paymentData->total_mvola1) ? $paymentData->total_mvola1 : 0;
        // $total_mvola2 = isset($paymentData->total_mvola2) ? $paymentData->total_mvola2 : 0;

        // $total_mvola = $total_mvola1 + $total_mvola2;
        // $total_mvola1 = $total_mvola - $total_recouvrement;

        // die(var_dump($data['recouvrement']))

        // if ($data['recouvrement_montant'] <= $total_mvola1) {
        //     if ($Recouvrement->addRecouvrement($data)) {
        //         session()->setFlashdata('success', 'Créé avec succès');

        //         $Notification->createNotification("Un nouveau recouvrement crée", "TOUS", 0, 'recouvrement/');
        //         return redirect()->to('recouvrement/');
        //     } else {
        //         session()->setFlashdata('errors', 'Error occurred while creating the product');
        //         return redirect()->to('recouvrement/');
        //     }
        // } else {
        //     session()->setFlashdata('errors', 'Solde MVOLA insuffisant');
        //     return redirect()->to('recouvrement/');
        // }

        if ($validation->run($validationData)) {
            //     // Prepare data
            $session = session();
            $users = $session->get('user');
            $data = [
                'recouvrement_montant' => $this->request->getPost('recouvrement_montant'),
                'recouvrement_date' => $this->request->getPost('recouvrement_date'),
                'recouvrement_personnel' => $fullname,
                'get_money' => $this->request->getPost('get_mode'),
                'send_money' => $this->request->getPost('send_mode'),
                'user_id' => $users['id'],
                'store_id' => $users['store_id'],
    
            ];

            if ($Recouvrement->addRecouvrement($data)) {
                $Notification->createNotification("Un nouveau recouvrement a été crée", "Direction", (int)$users["store_id"], 'recouvrement');
                $response['success'] = true;
                $response['messages'] = 'Recouvrement créé avec succès';
            } else {
                $response['success'] = false;
                $response['messages'] = 'Erreur lors de la création du recouvrement.';
            }
        } else {
            // Validation failed, return error messages
            $response['success'] = false;
            $response['messages'] = $validation->getErrors();
        }

        return $this->response->setJSON($response);
    }



    public function updateRecouvrement($recouvrement_id)
    {
        $this->verifyRole('updateRecouvrement');

        $data['page_title'] = $this->pageTitle;

        // Load validation service
        $validation = \Config\Services::validation();

        // Set validation rules
        $validation->setRules([
            'product[]' => 'required'
        ]);

        $validationData = [
            'product[]' => $this->request->getPost('product[]')
        ];

        $Recouvrement = new Recouvrement();
        // $recouvrement_id = (int) $this->request->getPost('recouvrement_id');
        if ($this->request->getMethod() === 'post') {
            $data = [
                'recouvrement_montant' => (int) $this->request->getPost('recouvrement_montant_edit'),
                'recouvrement_date' => $this->request->getPost('recouvrement_date_edit')

            ];
            if ($Recouvrement->updateRecouvrement($recouvrement_id, $data)) {
                // $Notification->createNotification("Un nouveau recouvrement crée", "Conseil", $users['store_id'], 'recouvrement');
                return $this->response->setJSON([
                    'success' => true,
                    'messages' => 'Recouvrement modifié avec succès !'
                ]);
            } else {
                return $this->response->setJSON([
                    'success' => false,
                    'messages' => 'Erreur lors de la modification du recouvrement.'
                ]);
            }
        }
    }

    public function fetchRecouvrementSingle($id)
    {
        // die(var_dump('hghjbhj'));
        if ($id) {
            $recouvrement = new Recouvrement();

            $data = $recouvrement->getRecouvrementSingle($id);
            echo json_encode($data);
        }
    }

    public function fetchTotalRecouvrementData() {
        helper(['url', 'form']);
        $Recouvrement = new Recouvrement();
        $start_date = $this->request->getGet('start_date');
        $end_date = $this->request->getGet('end_date');
        if ($start_date && $end_date) {
            
        // Initialiser les variables pour DataTables
        $draw = intval($this->request->getVar('draw'));
        $session = session();
        $users = $session->get('user');
        if($users['group_name'] === "Caissière"){
            $data = $Recouvrement->getTotalRecouvrements($users['id'] );

            $result = [
                "draw" => $draw,
                "recordsTotal" => 1,
                "recordsFiltered" => 1,
                "data" => []
            ];

            $totalRecouvrement = $Recouvrement->getTotalRecouvrements($users['id'], $start_date, $end_date );
            $total_recouvrement_me = $totalRecouvrement->me;
            $total_recouvrement_bm = $totalRecouvrement->bm;
            $total_recouvrement_be = $totalRecouvrement->be;
            $total_recouvrement_mb = $totalRecouvrement->mb;
            $total_recouvrement = $total_recouvrement_me + $total_recouvrement_me + $total_recouvrement_be + $total_recouvrement_mb; 
                $data = [
                    number_format($total_recouvrement_me,0,'.',' '),
                    number_format($total_recouvrement_bm,0,'.',' '),
                    number_format($total_recouvrement_be,0,'.',' '),
                    number_format($total_recouvrement_mb,0,'.',' '),
                    number_format($total_recouvrement,0,'.',' '),
                ];
            }
            return $this->response->setJSON($result);
        }
        // Initialiser les variables pour DataTables
        $draw = intval($this->request->getVar('draw'));
        $session = session();
        $users = $session->get('user');
        if($users['group_name'] === "Caissière"){
            $data = $Recouvrement->getTotalRecouvrements($users['id'] );

            $result = [
                "draw" => $draw,
                "recordsTotal" => 1,
                "recordsFiltered" => 1,
                "data" => []
            ];
            $totalRecouvrement = $Recouvrement->getTotalRecouvrements($users['id'] );
            $total_recouvrement_me = $totalRecouvrement->me;
            $total_recouvrement_bm = $totalRecouvrement->bm;
            $total_recouvrement_be = $totalRecouvrement->be;
            $total_recouvrement_mb = $totalRecouvrement->mb;
            $total_recouvrement = $total_recouvrement_me + $total_recouvrement_me + $total_recouvrement_be + $total_recouvrement_mb; 
                $data = [
                    number_format($total_recouvrement_me,0,'.',' '),
                    number_format($total_recouvrement_bm,0,'.',' '),
                    number_format($total_recouvrement_be,0,'.',' '),
                    number_format($total_recouvrement_mb,0,'.',' '),
                    number_format($total_recouvrement,0,'.',' '),
                ];
            }
            return $this->response->setJSON($result);
    }
}
