<?php

namespace Modules\Params\Controllers;

use App\Controllers\BaseController;
use App\Libraries\DatatableQuery;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Params\Models\EtatEquiment as ModelsEtatEquiment;
use Psr\Log\LoggerInterface;
use stdClass;

class EtatEquiment extends BaseController
{
    public ModelsEtatEquiment $etat_equipement_model;
    protected string $viewPath;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->etat_equipement_model = new ModelsEtatEquiment();
        $this->viewPath = "Modules\\Params\\Views\\";
    }

    public function index()
    {
        $uri = current_url(true);
        $id = $uri->getSegment(4);

        $this->viewData['url_list'] = "/params/etat_equipement/data";
        $this->viewData['js'] = "";
        $this->viewData['route'] = "/params/etat_equipement/save";
        $this->viewData['etat'] =  $this->initEtatEquipement($id);

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

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

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

            $this->viewData['url_list'] = "/params/etat_equipement/data";
            $this->viewData['js'] = "";
            $this->viewData['route'] = "/params/etat_equipement/save";
            $this->viewData['etat'] =  $this->initEtatEquipement($id);

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

            $unEtatEquipement = $this->unEtatEquipement();
            if ($id) {
                $this->session->setFlashdata('message', "<div class='row alert alert-success'>L'état d'équipement <b>" . $unEtatEquipement['description'] . "</b> a été modifiée</div>");
                $stmt = $this->etat_equipement_model->update($id, $unEtatEquipement);
            } else {
                $this->session->setFlashdata('message', "<div class='row alert alert-success'>L'état d'équipement <b>" . $unEtatEquipement['description'] . "</b> a été bien enregistrée</div>");
                $stmt = $this->etat_equipement_model->save($unEtatEquipement);
            }

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


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

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

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

    private function unEtatEquipement()
    {
        $etat_equipement = [];
        $etat_equipement['description'] = $this->request->getPost('description');

        return $etat_equipement;
    }

    private function initEtatEquipement($id = NULL)
    {
        $etat_equipement = NULL;
        if ($id) {
            $etat_equipement = $this->etat_equipement_model->find($id);
        } else {
            $etat_equipement = new stdClass();
            $etat_equipement->id = 0;
            $etat_equipement->description = "";
        }

        return $etat_equipement;
    }

    private function _rules()
    {
        $rules = [];
        $rules['description'] = ['rules'  => 'required|min_length[2]|max_length[100]'];

        return $rules;
    }



    function fecth()
    {
        $search_column = ['id', 'description'];
        $order_column = ['id', 'description'];

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

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

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

                $sub_array = array();

                $sub_array[] =  $i;
                $sub_array[] =  $data->description;
                $option = anchor($locale . "/params/etat_equipement/" . $data->id, "<i class='fa fa-edit'></i>", ['class' => 'text-info']);
                
                if (\auth()->user()->inGroup('secretaire', 'admin') || \auth()->user()->hasPermission('params.delete')) {
                    $option .= anchor($locale . "/params/etat_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
        ];
    }
}
