<?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\StatutAchat as ModelsStatutAchat;
use Psr\Log\LoggerInterface;
use stdClass;

class StatutAchat extends BaseController
{
    public ModelsStatutAchat $statut_achat_model;
    protected string $viewPath;

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

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

        $this->viewData['url_list'] = "/params/statut_achat/data";
        $this->viewData['js'] = "";
        $this->viewData['route'] = "/params/statut_achat/save";
        $this->viewData['statut'] =  $this->initStatutAchat($id);

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

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

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

            $this->viewData['url_list'] = "/params/statut_achat/data";
            $this->viewData['js'] = "";
            $this->viewData['route'] = "/params/statut_achat/save";
            $this->viewData['statut'] =  $this->initStatutAchat($id);

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

            $unStatutAchat = $this->unStatutAchat();
            if ($id) {
                $this->session->setFlashdata('message', "<div class='row alert alert-success'>Le statut achat <b> " . $unStatutAchat['description'] . "</b> a été modifiée</div>");
                $stmt = $this->statut_achat_model->update($id, $unStatutAchat);
            } else {
                $this->session->setFlashdata('message', "<div class='row alert alert-success'>Le statut achat <b> " . $unStatutAchat['description'] . "</b> a été bien enregistrée</div>");
                $stmt = $this->statut_achat_model->save($unStatutAchat);
            }

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


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

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

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

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

        return $statut_achat;
    }

    private function initStatutAchat($id = NULL)
    {
        $statut_achat = NULL;
        if ($id) {
            $statut_achat = $this->statut_achat_model->find($id);
        } else {
            $statut_achat = new stdClass();
            $statut_achat->id = 0;
            $statut_achat->description = "";
        }

        return $statut_achat;
    }

    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->statut_achat_model, $search_column, $order_column);
        $output = $this->formatStatutAchats($this->viewData['locale'], $fetch_data);

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

    private function formatStatutAchats($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/statut_achat/" . $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/statut_achat/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
        ];
    }
}
