<?php

namespace App\Controllers\Pedidos;
use App\Entities\Pedidos\AlbaranEntity;
use App\Models\Pedidos\AlbaranModel;


class Albaran extends \App\Controllers\BaseResourceController
{ 
    protected $modelName = AlbaranModel::class;
    protected $format = 'json';

    protected static $singularObjectNameCc = 'albaran';
    protected static $singularObjectName = 'Albaran';
    protected static $pluralObjectName = 'Albaranes';
    protected static $controllerSlug = 'albaran';

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
    }

    public function index()
    {
        
    } 

    public function delete($id = null)
    {
        if ($this->request->isAJAX()) {

            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();

            $model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
            $model_linea->where('albaran_id', $id)->delete();

            $this->model->where('id', $id)->delete();

            $data = [
                'error' => 0,
                $csrfTokenName => $newTokenHash
            ];
            return $this->respond($data);
        }
        else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function addLinea($albaran_id){

        if ($this->request->isAJAX()) {

            $model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();

            // si es un post, es el iva
            if($this->request->getPost()){
                $reqData = $this->request->getPost();
                $albaran_id = $reqData['albaran_id'] ?? 0;

                $albaran = $this->model->find($albaran_id);
                if($albaran == false){
                    $data = [
                        'error' => 'Albaran no encontrado',
                        $csrfTokenName => $newTokenHash
                    ];
                    return $this->respond($data);
                }
                $presupuesto_model = model('App\Models\Presupuestos\PresupuestoModel');
                $presupuesto = $presupuesto_model->find($albaran->presupuesto_id);
                if($presupuesto == false){
                    $data = [
                        'error' => 'Presupuesto no encontrado',
                        $csrfTokenName => $newTokenHash
                    ];
                    return $this->respond($data);
                }
                $iva_reducido = $presupuesto->iva_reducido;
                $lineas = $model_linea->where('albaran_id', $albaran_id)->findAll();
                $total = 0;
                foreach($lineas as $linea){
                    $total += $linea->total;
                }
                $iva = $iva_reducido? $total * 4.0  / 100: $total * 21.0 / 100;
                $data_linea= [
                    'albaran_id' => $albaran_id,
                    'titulo' => $iva_reducido?lang('Pedidos.iva4'):lang('Pedidos.iva21'),
                    'cantidad' => 1,
                    'precio_unidad' => round($iva,2),
                    'total' => round($iva,2),
                    'user_created_id' => auth()->user()->id,
                    'user_updated_id' => auth()->user()->id
                ];
                $id_linea = $model_linea->insert($data_linea);
                $linea = $model_linea->find($id_linea);
                $data = [
                    'error' => 0,
                    'data' => $linea,
                    $csrfTokenName => $newTokenHash
                ];
                return $this->respond($data);
            }
            else{
                $linea = [
                    'albaran_id' => $albaran_id,
                    'user_created_id' => auth()->user()->id,
                    'user_updated_id' => auth()->user()->id
                ];
                $id_linea = $model_linea->insert($linea);
                $data = $model_linea->find($id_linea);
    
                $data = [
                    'error' => 0,
                    'data' => $data,
                    $csrfTokenName => $newTokenHash
                ];
                return $this->respond($data);
            }
        }
        else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function add()
    {
        if ($this->request->isAJAX()) {

            $user = auth()->user()->id;

            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();

            $reqData = $this->request->getPost();
            $pedido_id = $reqData['pedido_id'] ?? 0;
            $presupuestos_id = $reqData['presupuestos_id'] ?? 0;
            
            $return_data = $this->model->generarAlbaranes($pedido_id, $presupuestos_id, $user);
            $data = [
                'data' => $return_data,
                $csrfTokenName => $newTokenHash
            ];
            
            return $this->respond($data);

        }
        else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function update($id = null){

        if ($this->request->isAJAX()) {
            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();

            if ($id == null) :
                $data = [
                    'error' => 2,
                    $csrfTokenName => $newTokenHash
                ];
                return $this->respond($data);
            endif;
            $id = filter_var($id, FILTER_SANITIZE_URL);
            $albaranEntity = $this->model->find($id);

            if ($albaranEntity == false) :
                $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
                $data = [
                    'error' => $message,
                    $csrfTokenName => $newTokenHash
                ];
                return $this->respond($data);
            endif;

            if ($this->request->getPost()) :

                $nullIfEmpty = true; // !(phpversion() >= '8.1');

                $postData = $this->request->getPost();

                $sanitizedData = $this->sanitized($postData, $nullIfEmpty);
                
                // JJO
                $sanitizedData['user_updated_id'] = auth()->user()->id;

                $noException = true;
                if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :

                    if ($this->canValidate()) :
                        try {
                            $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
                        } catch (\Exception $e) {
                            $noException = false;
                            $this->dealWithException($e);
                        }
                    else:
                        $this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Pedidos.albaran'))]);
                        $this->session->setFlashdata('formErrors', $this->model->errors());

                    endif;

                    $albaranEntity->fill($sanitizedData);

                endif;
                if ($noException && $successfulResult) :
                    $id = $albaranEntity->id ?? $id;
                    $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';

                    $data = [
                        'error' => 0,
                        $csrfTokenName => $newTokenHash
                    ];
                    return $this->respond($data);

                endif; // $noException && $successfulResult
            endif; // ($requestMethod === 'post')

            $data = [
                'error' => 1,
                $csrfTokenName => $newTokenHash
            ];
            return $this->respond($data);
        }
        else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }


    public function updateLinea($id = null){

        if ($this->request->isAJAX()) {

            $model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();

            if ($id == null) :
                $data = [
                    'error' => 2,
                    $csrfTokenName => $newTokenHash
                ];
                return $this->respond($data);
            endif;
            $id = filter_var($id, FILTER_SANITIZE_URL);
            $albaranEntity = $model_linea->find($id);

            if ($albaranEntity == false) :
                $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
                $data = [
                    'error' => $message,
                    $csrfTokenName => $newTokenHash
                ];
                return $this->respond($data);
            endif;

            if ($this->request->getPost()) :

                $nullIfEmpty = true; // !(phpversion() >= '8.1');

                $postData = $this->request->getPost();

                $sanitizedData = $this->sanitized($postData, $nullIfEmpty);
                
                // JJO
                $sanitizedData['user_updated_id'] = auth()->user()->id;

                $noException = true;
                if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :

                    if ($this->canValidate()) :
                        try {
                            $successfulResult = $model_linea->skipValidation(true)->update($id, $sanitizedData);
                        } catch (\Exception $e) {
                            $noException = false;
                            $this->dealWithException($e);
                        }
                    else:
                        $this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Pedidos.albaran'))]);
                        $this->session->setFlashdata('formErrors', $model_linea->errors());

                    endif;

                    $albaranEntity->fill($sanitizedData);

                endif;
                if ($noException && $successfulResult) :
                    $id = $albaranEntity->id ?? $id;
                    $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';

                    $data = [
                        'error' => 0,
                        $csrfTokenName => $newTokenHash
                    ];
                    return $this->respond($data);

                endif; // $noException && $successfulResult
            endif; // ($requestMethod === 'post')

            $data = [
                'error' => 1,
                $csrfTokenName => $newTokenHash
            ];
            return $this->respond($data);
        }
        else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function borrarLinea(){
        if ($this->request->isAJAX()) {

            $model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();

            $reqData = $this->request->getPost();
            $id = $reqData['id'] ?? 0;
            $id = filter_var($id, FILTER_SANITIZE_URL);
            $albaranLineaEntity = $model_linea->find($id);

            if ($albaranLineaEntity == false) :
                $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
                $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
                $data = [
                    'error' => $message,
                    $csrfTokenName => $newTokenHash
                ];
                return $this->respond($data);
            endif;

            $successfulResult = $model_linea->skipValidation(true)->update($id, ['deleted_at' => date('Y-m-d H:i:s')]);
            
            if ($successfulResult) :
                $data = [
                    'error' => 0,
                    $csrfTokenName => $newTokenHash
                ];
            else:
                $data = [
                    'error' => 1,
                    $csrfTokenName => $newTokenHash
                ];
            endif;
            return $this->respond($data);
        }
        else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function getAlbaranes($pedido_id = null){
        if ($this->request->isAJAX()) {

            $model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();

            $returnData = [];
            $albaranes = $this->model->asArray()->where('pedido_id', $pedido_id)->findAll();

            foreach($albaranes as $albaran){
                $albaran['fecha_albaran'] = $albaran['updated_at'];
                array_push($returnData, 
                [
                    'albaran' => $albaran,
                    'lineas' => $model_linea->asArray()->where('albaran_id', $albaran['id'])->findAll()]
                );
            }

            $data = [
                'data' => $returnData,
                $csrfTokenName => $newTokenHash
            ];
            return $this->respond($data);
        }
        else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }
}
 