<?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\Mobilier as ModelsMobilier;
use Modules\Params\Models\ProvinceModel;
use Modules\Params\Models\StatutMobilier;
use Psr\Log\LoggerInterface;
use stdClass;
use UConverter;

use function PHPUnit\Framework\fileExists;

class Mobilier extends BaseController
{
    public ModelsMobilier $mobilier_model;
    public ProvinceModel $province_model;
    public StatutMobilier $statut_mobilier_model;

    protected string $viewPath;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->mobilier_model = new ModelsMobilier();
        $this->province_model = new ProvinceModel();
        $this->statut_mobilier_model = new StatutMobilier();

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


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

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

    function fecth()
    {
        $search_column = ['id', 'province_id', 'branche_id', 'description', 'marque', 'conditions', 'localisation', 'responsable', 'date_achat', 'lieu_achat', 'valeur', 'fournisseur', 'origine', 'valeur_acquisition', 'statut_mobilier_id', 'accessoire', 'user_id'];
        $order_column = ['id', 'description', 'marque',  'date_achat', 'valeur', 'fournisseur',  'valeur_acquisition', 'statut_mobilier_id', 'responsable'];

        $mobilier_model = $this->mobilier_model;

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

        $fetch_data = DatatableQuery::build_query($mobilier_model, $search_column, $order_column);
        $output = $this->formatMobiliers($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/mobilier/save";
        $this->viewData['mobilier'] =  $this->initMobilier($id);
        $this->viewData['provinces'] = CommonTrait::formatData($this->province_model);
        $this->viewData['statuts'] = CommonTrait::formatData($this->statut_mobilier_model);
        $this->viewData['responsables'] = UserTrait::usersArrayFormat();

        if ($id > 0)
            $title = "Editer un inventaire du mobilier";
        else
            $title = "Nouveau un inventaire du mobilier";

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

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

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

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

            $this->viewData['url_list'] = "/inv/mobilier/data";
            $this->viewData['js'] = "Inventaire.js";
            $this->viewData['route'] = "/inv/mobilier/save";
            $this->viewData['mobilier'] =  $this->initMobilier($id);
            $this->viewData['provinces'] = CommonTrait::formatData($this->province_model);
            $this->viewData['statuts'] = CommonTrait::formatData($this->statut_mobilier_model);
            $this->viewData['responsables'] = UserTrait::usersArrayFormat();

            if ($id > 0)
                $title = "Editer un inventaire du mobilier";
            else
                $title = "Nouveau un inventaire du mobilier";

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


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

            $unMobilier = $this->unMobilier();

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

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


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

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

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

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

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

    private function unMobilier()
    {
        $mobilier = [];

        $mobilier['province_id'] = $this->request->getPost('province_id');
        $mobilier['branche_id'] = $this->request->getPost('branche_id');
        $mobilier['description'] = $this->request->getPost('description');
        $mobilier['marque'] = $this->request->getPost('marque');
        $mobilier['conditions'] = $this->request->getPost('conditions');
        $mobilier['localisation'] = $this->request->getPost('localisation');
        $mobilier['responsable'] = $this->request->getPost('responsable');
        $mobilier['date_achat'] = $this->request->getPost('date_achat');
        $mobilier['lieu_achat'] = $this->request->getPost('lieu_achat');
        $mobilier['valeur'] = $this->request->getPost('valeur');
        $mobilier['fournisseur'] = $this->request->getPost('fournisseur');
        $mobilier['origine'] = $this->request->getPost('origine');
        $mobilier['valeur_acquisition'] = $this->request->getPost('valeur_acquisition');
        $mobilier['statut_mobilier_id'] = $this->request->getPost('statut_mobilier_id');
        $mobilier['accessoire'] = $this->request->getPost('accessoire');
        $mobilier['user_id'] = \auth()->user()->id;

        return $mobilier;
    }

    public function initMobilier($id = NULL)
    {
        $mobilier = NULL;
        $mobilier = $this->mobilier_model->find($id);

        if (empty($mobilier)) {

            $mobilier = new stdClass();
            $mobilier->id = 0;
            $mobilier->province_id = 0;
            $mobilier->branche_id = 0;
            $mobilier->description = "";
            $mobilier->marque = '';
            $mobilier->conditions = '';
            $mobilier->localisation = '';
            $mobilier->responsable = "";
            $mobilier->date_achat = "";
            $mobilier->lieu_achat = "";
            $mobilier->valeur = 0;
            $mobilier->fournisseur = "";
            $mobilier->origine = "";
            $mobilier->valeur_acquisition = "";
            $mobilier->statut_mobilier_id = 0;
            $mobilier->accessoire = "";
            $mobilier->user_id = 0;
            $mobilier->created_at = NULL;
        }

        return $mobilier;
    }

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

        $rules = [];
        $rules['province_id'] = ['rules'  => 'required'];
        $rules['branche_id'] = ['rules'  => 'required'];
        $rules['description'] = ['rules'  => 'required'];
        $rules['marque'] = ['rules'  => 'required'];
        $rules['conditions'] = ['rules'  => 'required'];
        $rules['localisation'] = ['rules'  => 'required'];
        $rules['responsable'] = ['rules'  => 'required'];
        $rules['date_achat'] = ['rules'  => 'required'];
        $rules['lieu_achat'] = ['rules'  => 'required'];
        $rules['valeur'] = ['rules'  => 'required'];
        $rules['fournisseur'] = ['rules'  => 'required'];
        $rules['origine'] = ['rules'  => "required"];
        $rules['valeur_acquisition'] = ['rules'  => 'required'];
        $rules['statut_mobilier_id'] = ['rules'  => 'required'];
        $rules['accessoire'] = ['rules'  => 'required'];

        return $rules;
    }

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

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

                $sub_array = array();

                $sub_array[] =  $i;
                // $sub_array[] =  $data->province_id > 0 ? CommonTrait::formatData($this->province_model, $data->province_id) : "";
                $sub_array[] =  $data->description;
                $sub_array[] =  $data->marque;
                $sub_array[] =  $data->date_achat;
                $sub_array[] =  $data->valeur;
                $sub_array[] =  $data->fournisseur;
                $sub_array[] =  $data->valeur_acquisition;
                $sub_array[] =  $data->statut_mobilier_id > 0 ? CommonTrait::formatData($this->statut_mobilier_model, $data->statut_mobilier_id) : "";
                $sub_array[] =  $responsable_par;

                $option = anchor($locale . "/inv/mobilier/add/" . $data->id, "<i class='fa fa-edit'></i>", ['class' => 'text-info']) . " "
                    . anchor($locale . "/inv/mobilier/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/mobilier/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/mobilier_" . $fileName . ".csv";
        $file = fopen($csv_file_name, 'w');

        $arrays = [];
        $arrays[0] = ['', $this->formatText("Inventaire des mobiliers")];
        $arrays[1] = ['', $this->formatText($province)];
        $arrays[2] = [];
        $arrays[3] = [
            '#',
            $this->formatText('Province'),
            $this->formatText('Description'),
            $this->formatText('Marque/Modèle'),
            $this->formatText('Condition'),
            $this->formatText('Localisation'),
            $this->formatText('Responsable'),
            $this->formatText('Date d\'achat'),
            $this->formatText('Lieu d\'achat'),
            $this->formatText('Valeur'),
            $this->formatText('Origine'),
            $this->formatText('Valeur d\'acquisition'),
            $this->formatText('Statut'),
            $this->formatText("Accessoire")
        ];

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

        $i = 1;
        foreach ($mobiliers as $mobilier) {
            $enregistrer_par = $mobilier->responsable > 0 ? UserTrait::user($mobilier->responsable) : NULL;
            $enregistrer_par = $enregistrer_par ? $enregistrer_par->nom . " " . $enregistrer_par->prenom : "";

            $sub_array = [];
            $sub_array[] =  $i;
            $sub_array[] =  $mobilier->province_id > 0 ? CommonTrait::formatData($this->province_model, $mobilier->province_id) : "";
            $sub_array[] =  $mobilier->description;
            $sub_array[] =  $mobilier->marque;
            $sub_array[] =  $mobilier->conditions;
            $sub_array[] =  $mobilier->localisation;
            $sub_array[] =  $enregistrer_par;
            $sub_array[] =  $mobilier->date_achat;
            $sub_array[] =  $mobilier->lieu_achat;
            $sub_array[] =  $mobilier->valeur;
            $sub_array[] =  $mobilier->fournisseur;
            $sub_array[] =  $mobilier->origine;
            $sub_array[] =  $mobilier->valeur_acquisition;
            $sub_array[] =  $mobilier->statut_mobilier_id > 0 ? CommonTrait::formatData($this->statut_mobilier_model, $mobilier->statut_mobilier_id) : "";
            $sub_array[] =  $mobilier->accessoire;

            $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;
    }
}
