<?php

namespace Modules\Inventaire\Controllers;

use App\Controllers\BaseController;
use App\Libraries\DatatableQuery;
use App\Traits\CommonTrait;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Administration\Traits\UserTrait;
use Modules\Inventaire\Models\Equipement as ModelsEquipement;
use Modules\Params\Models\EtatEquiment;
use Modules\Params\Models\ProvinceModel;
use Modules\Params\Models\TypeInventaire;
use Psr\Log\LoggerInterface;
use stdClass;
use UConverter;

use function PHPUnit\Framework\fileExists;

class Equipement extends BaseController
{
    public ModelsEquipement $equipement_model;
    public ProvinceModel $province_model;
    public EtatEquiment $etat_equiment_model;
    public TypeInventaire $type_inventaire_model;

    protected string $viewPath;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->equipement_model = new ModelsEquipement();
        $this->province_model = new ProvinceModel();
        $this->etat_equiment_model = new EtatEquiment();
        $this->type_inventaire_model = new TypeInventaire();

        $this->viewPath = "Modules\\Inventaire\\Views\\";
    }


    public function index()
    {
        $this->viewData['url_list'] = "/inv/equipement/data";
        $this->viewData['js'] = "Common.js";
        $this->viewData['title'] = "Inventaire des equipements";
        $this->viewData['provinces'] = CommonTrait::formatData($this->province_model);
        $this->viewData['etats'] = CommonTrait::formatData($this->etat_equiment_model);

        return view($this->viewPath . 'equipement/index', $this->viewData);
    }

    function fecth()
    {
        $search_column = ['id', 'province_id', 'branche_id', 'type_inventaire_id', 'marque', 'num_serie', 'acheteur', 'partenaire', 'affectation', 'service_utilisateur', 'acte_transfert', 'annee_acquisition', 'valeur_acquisition', 'valeur_residuelle', 'etat_materiel_id', 'observation', 'user_id'];
        $order_column = ['id', 'type_inventaire_id', 'marque', 'num_serie',  'service_utilisateur', 'annee_acquisition', 'valeur_acquisition',  'etat_materiel_id', 'user_id'];

        $equipement_model = $this->equipement_model;

        if (\auth()->user()->inGroup('provinceManager' || $this->request->getPost('province_id') > 0)) {
            $equipement_model->where('province_id', \auth()->user()->province_id);
        }

        $fetch_data = DatatableQuery::build_query($equipement_model, $search_column, $order_column);
        $output = $this->formatEquipements($this->viewData['locale'], $fetch_data);

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

    public function add()
    {
        $uri = current_url(true);
        $id = $uri->getSegment(5);

        $this->viewData['url_list'] = "";
        $this->viewData['js'] = "Inventaire.js";
        $this->viewData['route'] = "/inv/equipement/save";
        $this->viewData['equipement'] =  $this->initEquipement($id);
        $this->viewData['provinces'] = CommonTrait::formatData($this->province_model);
        $this->viewData['etats'] = CommonTrait::formatData($this->etat_equiment_model);
        $this->viewData['types'] = CommonTrait::formatData($this->type_inventaire_model);

        if ($id > 0)
            $title = "Editer un inventaire d'equipement";
        else
            $title = "Nouveau un inventaire d'equipement";

        $this->viewData['title'] = $title;

        return view($this->viewPath . 'equipement/add', $this->viewData);
    }

    public function save()
    {
        $id = $this->request->getPost('id');

        if (!$this->validate($this->_rules())) {

            $this->viewData['url_list'] = "/inv/equipement/data";
            $this->viewData['js'] = "Inventaire.js";
            $this->viewData['route'] = "/inv/equipement/save";
            $this->viewData['equipement'] =  $this->initEquipement($id);
            $this->viewData['provinces'] = CommonTrait::formatData($this->province_model);
            $this->viewData['etats'] = CommonTrait::formatData($this->etat_equiment_model);
            $this->viewData['types'] = CommonTrait::formatData($this->type_inventaire_model);

            if ($id > 0)
                $title = "Editer un inventaire d'equipement";
            else
                $title = "Nouveau un inventaire d'equipement";

            $this->viewData['title'] = $title;


            return view($this->viewPath . 'equipement/add', $this->viewData);
        } else {

            $unEquipement = $this->unEquipement();

            if ($id) {
                $this->session->setFlashdata('message', "<div class='row alert alert-success'>Un inventiare d'équipement a été modifié</div>");
                $stmt = $this->equipement_model->update($id, $unEquipement);
            } else {
                $this->session->setFlashdata('message', "<div class='row alert alert-success'>Un inventiare d'équipement  a été bien enregistré</div>");
                $stmt = $this->equipement_model->save($unEquipement);
            }

            if ($stmt) {
                return redirect()->to(site_url($this->viewData['locale'] . '/inv/equipement'));
            }
        }
    }


    public function delete()
    {
        $uri = current_url(true);
        $id = $uri->getSegment(5);

        $stmnt = $this->equipement_model->delete($id);

        if ($stmnt) {
            $this->session->setFlashdata('message', "<div class='row alert alert-success'>Un inventiare d'équipement a été suprimé</div>");
            return redirect()->to(site_url($this->viewData['locale'] . '/inv/equipement'));
        }
    }

    public function detail()
    {
        $uri = current_url(true);
        $id = $uri->getSegment(5);

        $this->viewData['url_list'] = "/inv/equipement/data";
        $this->viewData['js'] = "Common.js";
        $this->viewData['title'] = "Détail  d'un inventiare d'équipement";
        $this->viewData['equipement'] = $this->initEquipement($id);
        return view($this->viewPath . 'equipement/detail', $this->viewData);
    }

    private function unEquipement()
    {
        $equipement = [];

        $equipement['province_id'] = $this->request->getPost('province_id');
        $equipement['branche_id'] = $this->request->getPost('branche_id');
        $equipement['type_inventaire_id'] = $this->request->getPost('type_inventaire_id');
        $equipement['marque'] = $this->request->getPost('marque');
        $equipement['num_serie'] = $this->request->getPost('num_serie');
        $equipement['acheteur'] = $this->request->getPost('acheteur');
        $equipement['partenaire'] = $this->request->getPost('partenaire');
        $equipement['affectation'] = $this->request->getPost('affectation');
        $equipement['service_utilisateur'] = $this->request->getPost('service_utilisateur');
        $equipement['acte_transfert'] = $this->request->getPost('acte_transfert');
        $equipement['annee_acquisition'] = $this->request->getPost('annee_acquisition');
        $equipement['valeur_acquisition'] = $this->request->getPost('valeur_acquisition');
        $equipement['valeur_residuelle'] = $this->request->getPost('valeur_residuelle');
        $equipement['etat_materiel_id'] = $this->request->getPost('etat_materiel_id');
        $equipement['observation'] = $this->request->getPost('observation');
        $equipement['user_id'] = \auth()->user()->id;

        return $equipement;
    }

    public function initEquipement($id = NULL)
    {
        $equipement = NULL;
        $equipement = $this->equipement_model->find($id);

        if (empty($equipement)) {

            $equipement = new stdClass();
            $equipement->id = 0;
            $equipement->province_id = 0;
            $equipement->branche_id = 0;
            $equipement->type_inventaire_id = "";
            $equipement->marque = '';
            $equipement->num_serie = '';
            $equipement->acheteur = '';
            $equipement->partenaire = "";
            $equipement->affectation = "";
            $equipement->service_utilisateur = "";
            $equipement->acte_transfert = "";
            $equipement->annee_acquisition = 0;
            $equipement->valeur_acquisition = 0;
            $equipement->valeur_residuelle = 0;
            $equipement->etat_materiel_id = 0;
            $equipement->observation = "";
            $equipement->user_id = 0;
            $equipement->created_at = NULL;
        }

        return $equipement;
    }

    private function _rules()
    {
        $year = date('Y');

        $rules = [];
        $rules['province_id'] = ['rules'  => 'required'];
        $rules['branche_id'] = ['rules'  => 'required'];
        $rules['type_inventaire_id'] = ['rules'  => 'required'];
        $rules['marque'] = ['rules'  => 'required'];
        $rules['num_serie'] = ['rules'  => 'required'];
        $rules['acheteur'] = ['rules'  => 'required'];
        $rules['partenaire'] = ['rules'  => 'required'];
        $rules['affectation'] = ['rules'  => 'required'];
        $rules['service_utilisateur'] = ['rules'  => 'required'];
        $rules['acte_transfert'] = ['rules'  => 'required'];
        $rules['annee_acquisition'] = ['rules'  => "required|less_than[$year]|greater_than[1910]"];
        $rules['valeur_acquisition'] = ['rules'  => 'required'];
        $rules['valeur_residuelle'] = ['rules'  => 'required'];
        $rules['etat_materiel_id'] = ['rules'  => 'required'];
        $rules['observation'] = ['rules'  => 'required'];

        return $rules;
    }



    private function formatEquipements($locale, $datas)
    {
        $i = 1;
        $array_data = array();
        if (!empty($datas['data'])) {
            foreach ($datas['data'] as $data) {


                $enregistrer_par = $data->user_id > 0 ? UserTrait::user($data->user_id) : NULL;
                $enregistrer_par = $enregistrer_par ? $enregistrer_par->nom . " " . $enregistrer_par->prenom : "";

                $sub_array = array();

                $sub_array[] =  $i;
                $sub_array[] =  $data->type_inventaire_id > 0 ? CommonTrait::formatData($this->type_inventaire_model, $data->type_inventaire_id) : "";
                //$sub_array[] =  $data->type_inventaire_id;
                $sub_array[] =  $data->marque;
                $sub_array[] =  $data->num_serie;
                $sub_array[] =  $data->service_utilisateur;
                $sub_array[] =  $data->annee_acquisition;
                $sub_array[] =  $data->valeur_acquisition;
                $sub_array[] =  $data->etat_materiel_id > 0 ? CommonTrait::formatData($this->etat_equiment_model, $data->etat_materiel_id) : "";
                $sub_array[] =  $enregistrer_par;

                $option = anchor($locale . "/inv/equipement/add/" . $data->id, "<i class='fa fa-edit'></i>", ['class' => 'text-info']) . " "
                    . anchor($locale . "/inv/equipement/detail/" . $data->id, "<i class='fa fa-eye'></i>", ['class' => 'text-secondary']) . " ";
                if (\auth()->user()->inGroup('secretaire', 'admin') || \auth()->user()->hasPermission('inv.delete')) {

                    $option .= anchor($locale . "/inv/equipement/delete/" . $data->id, "<i class='fa fa-trash'></i>", ['class' => 'text-danger']);
                }
                $sub_array[] = $option;

                $array_data[] = $sub_array;
                $i++;
            }
        }

        return [
            "draw" => intval($_POST["draw"]),
            "recordsTotal" => $datas['recordsTotal'],
            "recordsFiltered" => $datas['recordsFiltered'],
            "data" => $array_data
        ];
    }

    function export()
    {
        $uri = current_url(true);
        $province_id = $uri->getSegment(5);

        if ($province_id > 0) {
            $province = CommonTrait::formatData($this->province_model, $province_id);
        } else {
            $province = "Toutes les provinces";
        }

        $fileName = str_replace(' ', '', $province);
        $csv_file_name = "rapportExport/inventaire/equipement_" . $fileName . ".csv";
        $file = fopen($csv_file_name, 'w');

        $arrays = [];
        $arrays[0] = ['', $this->formatText("Inventaire des équipements")];
        $arrays[1] = ['', $this->formatText($province)];
        $arrays[2] = [];
        $arrays[3] = [
            '#',
            $this->formatText('Province'),
            $this->formatText('Description'),
            $this->formatText('Marque/Modèle'),
            $this->formatText('No de série'),
            $this->formatText('Projet acheteur'),
            $this->formatText('Partenaire'),
            $this->formatText('Affection'),
            $this->formatText('Service utilisateur'),
            $this->formatText('Acte de transfert/cession'),
            $this->formatText('Annee d\'acquisition'),
            $this->formatText('Valeur d\'acquisition'),
            $this->formatText('Valeur résiduelle'),
            $this->formatText('Etat du matériel'),
            $this->formatText("Observation")

        ];

        if ($province_id > 0) {
            $equipements = $this->equipement_model->where('province_id', $province_id)->findAll();
        } else {
            $equipements = $this->equipement_model->findAll();
        }

        $i = 1;
        foreach ($equipements as $equipement) {
            $enregistrer_par = $equipement->user_id > 0 ? UserTrait::user($equipement->user_id) : NULL;
            $enregistrer_par = $enregistrer_par ? $enregistrer_par->nom . " " . $enregistrer_par->prenom : "";

            $sub_array = [];
            $sub_array[] =  $i;
            $sub_array[] =  $equipement->province_id > 0 ? CommonTrait::formatData($this->province_model, $equipement->province_id) : "";
            $sub_array[] =  $equipement->type_inventaire_id > 0 ? CommonTrait::formatData($this->type_inventaire_model, $equipement->type_inventaire_id) : "";
            //$sub_array[] =  $equipement->type_inventaire_id;
            $sub_array[] =  $equipement->marque;
            $sub_array[] =  $equipement->num_serie;
            $sub_array[] =  $equipement->acheteur;
            $sub_array[] =  $equipement->partenaire;
            $sub_array[] =  $equipement->affectation;
            $sub_array[] =  $equipement->service_utilisateur;
            $sub_array[] =  $equipement->acte_transfert;
            $sub_array[] =  $equipement->annee_acquisition;
            $sub_array[] =  $equipement->valeur_acquisition;
            $sub_array[] =  $equipement->valeur_residuelle;
            $sub_array[] =  $equipement->etat_materiel_id > 0 ? CommonTrait::formatData($this->etat_equiment_model, $equipement->etat_materiel_id) : "";
            $sub_array[] =  $equipement->observation;

            $arrays[] = $sub_array;
            $i++;
        }


        foreach ($arrays as $array) {
            fputcsv($file, $array, ";");
        }
        fclose($file);
        $btn = anchor($csv_file_name, "Exporter un <i class='fa fa-file-csv'></i>", ['class' => 'text-success', 'target' => '_blank']);

        $status = 0;
        if (fileExists($csv_file_name)) {
            $status = 1;
        }

        return $this->response->setJSON(['status' => $status, 'btnExport' => $btn]);
    }

    function formatText($string = NULL)
    {
        if (gettype($string) == "string") {
            $string = UConverter::transcode($string, 'ISO-8859-1', 'UTF8');
        }

        if (gettype($string) == "array") {
            foreach ($string as $key => $value) {
                $string[$key] = UConverter::transcode($value, 'ISO-8859-1', 'UTF8');
            }
        }

        return $string;
    }
}
