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

class ProvinceController extends BaseController
{
    public ProvinceModel $provinceModel;
    protected string $viewPath;

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

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

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

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

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

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

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

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

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

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


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

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

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

    private function uneProvince()
    {
        $province = [];
        $province['description'] = $this->request->getPost('description');
        $province['longitude'] = $this->request->getPost('longitude');
        $province['latitude'] = $this->request->getPost('latitude');

        return $province;
    }

    private function initProvince($id = NULL)
    {
        $province = NULL;
        if ($id) {
            $province = $this->provinceModel->find($id);
        } else {
            $province = new stdClass();
            $province->id = 0;
            $province->description = "";
            $province->longitude = "-1.0";
            $province->latitude = "-1.0";
        }

        return $province;
    }

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

        return $rules;
    }



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

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

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

    private function formatProvinces($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;
                $sub_array[] =  $data->latitude;
                $sub_array[] =  $data->longitude;
                $option = anchor($locale . "/params/province/" . $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/province/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
        ];
    }
}
