<?php

namespace App\Controllers\Albaranes;
use App\Entities\Albaranes\AlbaranEntity;
use App\Models\Albaranes\AlbaranModel;
use Hermawan\DataTables\DataTable;

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\Albaranes\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\Albaranes\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 updateAlbaran()
    {

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

            $fieldName = $this->request->getPost('fieldName');
            $fieldValue = $this->request->getPost('fieldValue');
            $id = $this->request->getPost('albaranId');

            if ($id == null) {
                $data = [
                    'success' => false,
                    'message' => lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]),
                ];
                return $this->respond($data);
            }
            $albaranEntity = $this->model->find($id);

            if ($albaranEntity == false) {
                $data = [
                    'success' => false,
                    'message' => lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]),
                ];
                return $this->respond($data);
            }

            if($fieldName == 'fecha_albaran'){
                if($fieldValue == null || $fieldValue == '')
                    $fieldValue = null;
                else
                    $fieldValue = date('Y-m-d H:i:s', strtotime($fieldValue));
            } 

            $albaranEntity->fill([
                $fieldName => $fieldValue,
                'user_updated_id' => auth()->user()->id,
            ]);
            $successfulResult = $this->model->skipValidation(true)->update($id, $albaranEntity);
            if ($successfulResult) {
                $data = [
                    'success' => true,
                    'message' => lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.',
                ];
            } else {
                $data = [
                    'success' => false,
                    'message' => lang('Basic.global.updateError', [lang('Basic.global.record')]) . '.',
                ];
            }

            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\Albaranes\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 getAlbaranes()
    {

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

            $envio_id = $this->request->getGet('envio_id');
            $albaranes = $this->model->getAlbaranesEnvio($envio_id);
            $data = [
                'status' => true,
                'data' => $albaranes,
            ];
            return $this->respond($data);
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function generateAlbaran()
    {

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

            $reqData = $this->request->getPost();
            $envio_id = $reqData['envio_id'] ?? 0;
            $envio_lineas = $reqData['envio_lineas'] ?? [];
            $cajas = $reqData['cajas'] ?? 0;

            $response = $this->model->generarAlbaranes($envio_id, $envio_lineas, $cajas);

            return $this->respond($response);

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

    public function datatablesLineasAlbaran()
    {

        $albaranId = $this->request->getGet('albaranId');
        $model = model('App\Models\Albaranes\AlbaranLineaModel');
        $q = $model->getDatatableQuery($albaranId);

        $result = DataTable::of($q)
            ->add(
                "action",
                callback: function ($q) {
                    return '
                        <div class="btn-group btn-group-sm">
                            <a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete-albaran-lineas mx-2" data-id="' . $q->id . '"></i></a>
                        </div>
                    ';
                }
            )
            ->edit('pedido', function ($q) {
                return '<a href="' . base_url('pedidos/edit/' . $q->pedido) . '" target="_blank">' . $q->pedido . '</a>';
            })
            ->edit('unidades', function ($q) {
                if(str_contains($q->titulo, 'IVA'))
                    return null;
                else
                    return '<input type="number" class="form-control form-control-sm input-albaran-linea text-center" 
                        value="' . $q->unidades . '" data-id="' . $q->id . '" data-field="cantidad" />';
            })
            ->edit('titulo', function ($q) {
                return '<input type="text" class="form-control form-control-sm input-albaran-linea" value="' . $q->titulo . 
                    '" data-id="' . $q->id . '" data-field="titulo" />';
            })
            ->edit('total', function ($q) {
                return '<input class="form-control autonumeric-2  input-albaran-linea
                    form-control-sm text-center" value="' . $q->total . '" data-id="' . $q->id . '" data-field="total" />';
            })
            ->edit('precio_unidad', function ($q) {
                if(str_contains($q->titulo, 'IVA'))
                    return null;
                else
                    return '<input class="form-control autonumeric-4 form-control-sm text-center  input-albaran-linea" value="' .
                        number_format((float) $q->precio_unidad, 4, ',', '') .
                        '" data-id="' . $q->id . '" data-field="precio_unidad" />';
            });


        return $result->toJson(returnAsObject: true);
    }

    public function updateAlbaranLinea(){

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

            $model_linea = model('App\Models\Albaranes\AlbaranLineaModel');


            $fieldName = $this->request->getPost('fieldName');
            $fieldValue = $this->request->getPost('fieldValue');
            $id = $this->request->getPost('lineaId');

            $linea = $model_linea->find($id);
            if ($linea == false) {
                $data = [
                    'success' => false,
                    'message' => lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]),
                ];
                return $this->respond($data);
            }
            if($fieldName == 'cantidad') {
                $linea->total = round($linea->precio_unidad * intval($fieldValue), 4);
                $linea->cantidad = intval($fieldValue);
            } 
            else if($fieldName == 'precio_unidad') {
                $fieldValue2 = str_replace(',', '.', $fieldValue);
                $linea->total = round(round(floatval($fieldValue2), 4) * intval($linea->cantidad), 2);
                $linea->precio_unidad = round(floatval($fieldValue2), 4);
            } 
            else if($fieldName == 'total') {
                $linea->total = round(floatval($fieldValue), 2);
                $linea->precio_unidad = round(floatval($fieldValue) / intval($linea->cantidad), 4);
            }
            else{
                $linea->$fieldName = $fieldValue;
            }
            $linea->user_updated_id = auth()->user()->id;
            $linea->updated_at = date('Y-m-d H:i:s');
            
            $model_linea->update($id, $linea->toArray());

            $data = [
                'success' => true,
                'message' => lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.',
            ];
            return $this->respond($data);
            
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function addLineasIva(){

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

            $albaran_id = $this->request->getPost('albaranId');
            $model_linea = model('App\Models\Albaranes\AlbaranLineaModel');

            $lineas_albaran = $model_linea->where('albaran_id', $albaran_id)->findAll();
            $iva_reducido = 0;
            $iva_no_reducido = 0;
            foreach ($lineas_albaran as $linea) {
                if($linea->iva_reducido == 1) {
                    $iva_reducido += round(floatval($linea->total)*0.04, 2);
                } else {
                    $iva_no_reducido += round(floatval($linea->total)*0.21, 2);
                }
            }
            $iva_reducido = round($iva_reducido, 2);
            $iva_no_reducido = round($iva_no_reducido, 2);
            if($iva_reducido > 0) {
                $linea = [
                    'albaran_id' => $albaran_id,
                    'titulo' => lang('Albaran.iva4'),
                    'total' => round($iva_reducido, 2),
                    'user_created_id' => auth()->user()->id,
                    'user_updated_id' => auth()->user()->id
                ];
                $model_linea->insert($linea);
            }
            if($iva_no_reducido > 0) {
                $linea = [
                    'albaran_id' => $albaran_id,
                    'titulo' => lang('Albaran.iva21'),
                    'total' => round($iva_no_reducido, 2),
                    'user_created_id' => auth()->user()->id,
                    'user_updated_id' => auth()->user()->id
                ];
                $model_linea->insert($linea);
            }
            $data = [
                'success' => true,
                'message' => lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.',
            ];
            return $this->respond($data);

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

    public function addBlankLineaAlbaran(){

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

            $albaran_id = $this->request->getPost('albaranId');
            $model_linea = model('App\Models\Albaranes\AlbaranLineaModel');

            $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 = [
                'success' => true,
            ];
            return $this->respond($data);
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function borrarLinea()
    {

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

            $model_linea = model('App\Models\Albaranes\AlbaranLineaModel');

            $reqData = $this->request->getPost();
            $id = $reqData['linea'] ?? 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]);
                $data = [
                    'success' => false,
                    'error' => $message,
                ];
                return $this->respond($data);
            endif;

            $successfulResult = $model_linea->skipValidation(true)->update($id, ['deleted_at' => date('Y-m-d H:i:s')]);

            if ($successfulResult):
                $data = [
                    'success' => true,
                ];
            else:
                $data = [
                    'success' => false,
                    'error' => lang('Basic.global.deleteError', [lang('Basic.global.record')]) . '.',
                ];
            endif;
            return $this->respond($data);
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function borrarAlbaran()
    {

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

            $id = $this->request->getPost('albaranId');
            $model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
            $model_linea->where('albaran_id', $id)->delete();

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

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

}
