<?php

namespace App\Controllers\Logistica;

use App\Controllers\BaseController;
use App\Services\ImpresoraEtiquetaService;
use App\Services\EtiquetasTitulosService;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use Hermawan\DataTables\DataTable;

class EtiquetasTitulosController extends BaseController
{

    protected ImpresoraEtiquetaService $impresoraEtiquetaService;
    protected string $locale;
    protected array $viewData;

    protected static $controllerSlug = 'etiquetas_titulos';
    protected static $viewPath = 'themes/vuexy/form/logistica/';

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        $this->impresoraEtiquetaService = service('impresora_etiqueta');
        $this->locale = session()->get('lang');
        $this->model = model('App\Models\Etiquetas\EtiquetasTitulosModel');

        $this->viewData['pageTitle'] = lang('Logistica.logistica');

        // Breadcrumbs
        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_logistica"), 'route' => route_to("LogisticaPanel"), 'active' => false],
        ];


        parent::initController($request, $response, $logger);
    }

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

            $query = EtiquetasTitulosService::getOtsWithTitulos();

            if ($this->request->getGet("q")) {
                $query->groupStart()
                    ->orLike("ot.id", $this->request->getGet("q"))
                    ->orLike("pr.titulo)", $this->request->getGet("q"))
                    ->groupEnd();
            }


            $result = $query->orderBy("id", "DESC")->get()->getResultObject();

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

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

            $ot_id = $this->request->getGet("ot_id");

            $query = EtiquetasTitulosService::getDireccionesOT($ot_id);

            if ($this->request->getGet("q")) {
                $query->groupStart()
                    ->orLike("pd.direccion", $this->request->getGet("q"))
                    ->groupEnd();
            }


            $result = $query->orderBy("pd.direccion", "ASC")->get()->getResultObject();

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

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

            $data = [];
            $data['user_id'] = auth()->user()->id;
            $data['ot_id'] = $this->request->getPost('ot_id') ?? null;
            $data['direccion'] = $this->request->getPost('direccion') ?? null;
            $data['unidades_caja'] = $this->request->getPost('unidades_caja') ?? null;

            if (
                $this->request->getPost('ot_id') == null ||
                $this->request->getPost('direccion') == null ||
                $this->request->getPost('unidades_caja') == null
            ) {
                return [
                    'status' => false,
                    'message' => lang('Logistica.errorMissingData')
                ];
            }

            $result = EtiquetasTitulosService::addEtiqueta($data);

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

    public function deleteEtiqueta($id = null)
    {
        if ($this->request->isAJAX()) {
            $id = $this->request->getPost('id') ?? null;

            if ($id == null) {
                return [
                    'status' => false,
                    'message' => lang('Logistica.errorMissingData')
                ];
            }

            $modelLineas = model('App\Models\Etiquetas\EtiquetasTitulosLineasModel');
            $ids = $modelLineas->where('etiqueta_titulos_id', $id)->findColumn('id');
            if ($ids) {
                $modelLineas->delete($ids);
            }
            $model = model('App\Models\Etiquetas\EtiquetasTitulosModel');
            $id = $model->where('id', $id)->findColumn('id');
            if ($id) {
                $model->delete($id);
            }
            $result = [
                'status' => true,
                'message' => lang('Logistica.success.jhn<successDeleteEtiqueta'),
            ];

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

    }


    public function edit($id = null)
    {

        if (empty($id)) {
            return redirect()->to(base_url('logistica/selectEnvios/simple'))->with('error', lang('Logistica.errors.noEnvio'));
        }
        $model = model('App\Models\Etiquetas\EtiquetasTitulosModel');
        $etiquetaEntity = $model->select('etiquetas_titulos.*, clientes.nombre as cliente')
            ->join('clientes', 'clientes.id = etiquetas_titulos.cliente_id', 'left')
            ->where('etiquetas_titulos.id', $id)
            ->first();
        if (empty($etiquetaEntity)) {
            return redirect()->to(base_url('logistica/etiquetasLogistica'))->with('error', lang('Logistica.errors.noEnvio'));
        }


        $modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
        $impresoras = $modelImpresora->select('id, name')
            ->where('deleted_at', null)
            ->where('tipo', 1)
            ->orderBy('name', 'desc')
            ->findAll();
        $etiquetaEntity->impresoras = $impresoras;

        $viewData = [
            'currentModule' => static::$controllerSlug,
            'boxTitle' => '<i class="ti ti-ticket ti-xl"></i>' . ' ' . lang('Logistica.EtiquetasTitulos') . ' [' . $etiquetaEntity->id . ']: ' . $etiquetaEntity->direccion,
            'usingServerSideDataTable' => true,
            'etiquetaEntity' => $etiquetaEntity,
        ];

        $viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class

        return view(static::$viewPath . 'viewEtiquetasTitulosEdit', $viewData);
    }


    public function datatable()
    {
        $q = $this->model->getEtiquetasTitulos();

        if (!empty($otsFilter)) {
            $q->groupStart();
            $q->like('etl.ot_id', $otsFilter);
            $q->groupEnd();
        }

        $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-pencil ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a>
                            <a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete" data-id="' . $q->id . '"></i></a>
                        </div>
                    ';
            });

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

    public function findOtsWithAddress()
    {
        if ($this->request->isAJAX()) {
            $id = $this->request->getGet('id') ?? null;

            $query = EtiquetasTitulosService::findOTsWithAddress($id);

            if ($this->request->getGet("q")) {
                $query->groupStart()
                    ->orLike("name", $this->request->getGet("q"))
                    ->groupEnd();
            }


            $result = $query->orderBy("id", "DESC")->get()->getResultObject();

            return $this->response->setJSON($result);

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

    public function addLineasEtiqueta()
    {

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

            $etiqueta_id = $this->request->getPost('etiqueta_id') ?? null;
            $ot_id = $this->request->getPost('ot_id') ?? null;
            $unidades = $this->request->getPost('unidades') ?? null;
            $cajas = $this->request->getPost('cajas') ?? null;

            $result = EtiquetasTitulosService::addLineasEtiqueta($etiqueta_id, $ot_id, $unidades, $cajas);
            return $this->response->setJSON($result);
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }

    }

    public function datatableLineasEtiquetas($id = null)
    {

        $model = model('App\Models\Etiquetas\EtiquetasTitulosLineasModel');

        $id = $this->request->getGet('id') ?? null;
        $direccion = $this->request->getGet('direccion') ?? null;

        $q = $model->getDatatableQuery($id, $direccion);


        $result = DataTable::of($q)
            ->add(
                "rowSelected",
                callback: function ($q) {
                    return '<input type="checkbox" class="form-check-input checkbox-linea-envio" name="row_selected[]" value="' . $q->id . '">';
                }
            )
            ->edit(
                "ot",
                function ($row, $meta) {
                    return '<a href="' . base_url('produccion/ordentrabajo/edit/' . $row->ot) . '" target="_blank">' . $row->ot . '</a>';
                }
            )
            ->edit(
                "unidades",
                function ($row, $meta) {
                    return '<input type="number" class="form-control input-lineas input-unidades text-center" 
                        data-id="' . $row->id . '" data-name="unidades" value="' . $row->unidades . '">';
                }
            )
            ->edit(
                "numero_caja",
                function ($row, $meta) {
                    return '<input type="number" class="form-control input-lineas input-cajas text-center" 
                        data-id="' . $row->id . '" data-name="numero_caja" value="' . $row->numero_caja . '">';
                }
            )
            ->add("unidades_raw", fn($row) => $row->unidades)
            ->add("pesoUnidad_raw", fn($row) => $row->pesoUnidad)
            ->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" data-id="' . $q->id . '"></i></a>
                        </div>
                    ';
                }
            );

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

    public function deleteLineasEtiqueta()
    {
        if ($this->request->isAJAX()) {
            $ids = $this->request->getPost('ids') ?? [];

            if ($ids == [] || $ids == null) {
                return [
                    'status' => false,
                    'message' => lang('Logistica.errors.errorMissingData')
                ];
            }

            $model = model('App\Models\Etiquetas\EtiquetasTitulosLineasModel');
            for ($i = 0; $i < count($ids); $i++) {
                $model->delete($ids[$i]);
            }


            $result = [
                'status' => true,
                'message' => lang('Logistica.success.successDeleteLines'),
            ];

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

    public function updateLineasEtiqueta()
    {

        if ($this->request->isAJAX()) {
            $id = $this->request->getPost('id') ?? null;
            $name = $this->request->getPost('name') ?? null;
            $value = $this->request->getPost('value') ?? null;

            if ($id == null || $name == null || $value == null) {
                return [
                    'status' => false,
                    'message' => lang('Logistica.errors.errorMissingData')
                ];
            }

            $model = model('App\Models\Etiquetas\EtiquetasTitulosLineasModel');
            $model->update($id, [$name => $value]);

            $result = [
                'status' => true,
                'message' => lang('Logistica.success.successUpdateLine'),
            ];

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

    public function updateComentarios()
    {

        if ($this->request->isAJAX()) {
            $id = $this->request->getPost('id') ?? null;
            $comentarios = $this->request->getPost('comentarios') ?? null;

            if ($id == null || $comentarios == null) {
                return [
                    'status' => false,
                    'message' => lang('Logistica.errors.errorMissingData')
                ];
            }

            $model = model('App\Models\Etiquetas\EtiquetasTitulosModel');
            $model->update($id, ['comentarios' => $comentarios]);

            $result = [
                'status' => true,
                'message' => lang('Logistica.success.comentariosUpdated'),
            ];

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

    public function updateOrdenCajas()
    {
        $rawInput = $this->request->getBody();
        $data = json_decode($rawInput, true);
        $orden = $data['orden'] ?? [];

        if (!is_array($orden)) {
            return $this->response->setJSON([
                'status' => false,
                'message' => 'Datos inválidos'
            ]);
        }

        $model = model('App\Models\Etiquetas\EtiquetasTitulosLineasModel');

        foreach ($orden as $item) {
            if (isset($item['id'], $item['numero_caja'])) {
                $model->update($item['id'], [
                    'numero_caja' => $item['numero_caja'],
                    'updated_at' => date('Y-m-d H:i:s') // opcional
                ]);
            }
        }

        return $this->response->setJSON([
            'status' => true,
            'message' => 'Orden de cajas actualizado correctamente'
        ]);
    }

    public function renumberCajas()
    {
        $id = $this->request->getPost('id') ?? null;

        if ($id == null) {
            return [
                'status' => false,
                'message' => lang('Logistica.errors.errorMissingData')
            ];
        }

        $result = EtiquetasTitulosService::reordenarCajas($id);

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

    public function imprimirEtiquetas()
    {
        $etiqueta_id = $this->request->getPost('etiqueta_id') ?? null;
        $ids = $this->request->getPost('ids') ?? [];
        $impresora_id = $this->request->getPost('impresora_id') ?? null;

        $modelImpresora = model('App\Models\Configuracion\ImpresoraEtiquetaModel');
        $impresora = $modelImpresora->select('id, name, ip, port, user, pass')
            ->where('deleted_at', null)
            ->where('id', $impresora_id)
            ->orderBy('name', 'asc')
            ->first();
        if ($impresora == null) {
            return $this->response->setJSON([
                'status' => false,
                'message' => 'Impresora no válida'
            ]);
        }

        if ($etiqueta_id == null || $ids == []) {
            return [
                'status' => false,
                'message' => lang('Logistica.errors.errorMissingData')
            ];
        }

        $result = EtiquetasTitulosService::imprimirEtiquetas($etiqueta_id, $ids, $impresora);

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

}