<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// Asegurarnos de cargar la librería correctamente
require APPPATH . 'libraries/RestController.php';
require APPPATH . 'libraries/Format.php';

use chriskacerguis\RestServer\RestController;

class Tags extends RestController {
    
    function __construct() {
        parent::__construct();
        $this->load->helper('session');
        $this->load->model('tags_model');
    }
    public function get_all_tags_get() {
        $this->_params_validation_page_order_and_filters();
        $limit_offset_order_and_filters = $this->_get_limit_offset_order_and_filters();
        
        // Verificar si hay filtro adicional de saldo
        $saldo_categoria = $this->get('saldo_categoria');
        if ($saldo_categoria) {
            $limit_offset_order_and_filters['saldo_categoria'] = $saldo_categoria;
        }
        
        // Verificar si hay filtro adicional de asignación
        $asignacion = $this->get('asignacion');
        if ($asignacion) {
            $limit_offset_order_and_filters['asignacion'] = $asignacion;
        }
        
        $data['total_tags'] = $this->tags_model->count_all_tags($limit_offset_order_and_filters);
        if ($data['total_tags'] > 0) {
            $tags = $this->tags_model->get_all_tags($limit_offset_order_and_filters);
            $data['tags'] = $tags;
        } else {
            $data['tags'] = [];
        }
        $this->response($data, RestController::HTTP_OK);
    }
    
    // Método para obtener todos los TAGs por categoría de saldo sin paginación
    public function get_tags_by_saldo_get() {
        $saldo_categoria = $this->get('categoria');
        if (!in_array($saldo_categoria, ['sin_saldo', 'con_saldo', 'todos'])) {
            $this->response(['message' => 'Categoría de saldo inválida'], RestController::HTTP_BAD_REQUEST);
        }
        
        $status = $this->get('status') ?: 1;
        
        $tags = $this->tags_model->get_all_tags_by_saldo($saldo_categoria, $status);
        
        $this->response(['tags' => $tags], RestController::HTTP_OK);
    }
    
    // Método para obtener TAGs por estado de asignación sin paginación
    public function get_tags_by_asignacion_get() {
        $asignacion = $this->get('categoria');
        if (!in_array($asignacion, ['sin_asignar', 'asignados', 'todos'])) {
            $this->response(['message' => 'Categoría de asignación inválida'], RestController::HTTP_BAD_REQUEST);
        }
        
        $status = $this->get('status') ?: 1;
        
        $tags = $this->tags_model->get_all_tags_by_asignacion($asignacion, $status);
        
        $this->response(['tags' => $tags], RestController::HTTP_OK);
    }

    public function get_tag_by_id_get() {
        $this->_params_validation_id();
        $tag = $this->tags_model->get_tag_by_id($this->get('id'));
        if ($tag !== NULL) {
            $this->response(["tag" => $tag], RestController::HTTP_OK);
        } else {
            $this->response(['message' => "Error al obtener el TAG, contacte a soporte técnico."], RestController::HTTP_NOT_FOUND);
        }
    }
    public function create_post() {
        $this->_form_validation_create();
        
        // Verificar si el TAG ya existe
        $numero_tag = $this->post('numero_tag');
        if ($this->tags_model->tag_exists($numero_tag)) {
            $this->response(['message' => 'El número de TAG ya existe en el sistema'], RestController::HTTP_BAD_REQUEST);
            return;
        }
        
        $data_insert = $this->_fill_data_insert();
        $id = $this->tags_model->insert($data_insert);
        if ($id) {
            $this->response(['message' => 'TAG creado correctamente'], RestController::HTTP_OK);
        } else {
            $this->response(['message' => 'Error al crear el TAG'], RestController::HTTP_INTERNAL_ERROR);
        }
    }

    public function assign_tag_post() {
        $this->_form_validation_assign();
        // Verificar que el número económico no tenga ya un TAG activo
        if ($this->tags_model->check_numero_economico_has_active_tag($this->post('numero_economico_id'))) {
            $this->response(['message' => 'El número económico ya tiene un TAG activo asignado'], RestController::HTTP_BAD_REQUEST);
        }

        $data = array(
            'fecha_asignacion' => date('Y-m-d H:i:s'),
            'comentario_asignacion' => $this->post('comentario')
        );

        if ($this->tags_model->assign_to_numero_economico($this->get('id'), $this->post('numero_economico_id'), $data)) {
            $this->response(['message' => 'TAG asignado correctamente'], RestController::HTTP_OK);
        } else {
            $this->response(['message' => 'Error al asignar el TAG'], RestController::HTTP_INTERNAL_ERROR);
        }
    }
    public function recharge_tag_post() {
        $this->_params_validation_id();
        $this->_form_validation_recharge();
        
        $data = array(
            'monto' => $this->post('monto'),
            'comentario' => $this->post('comentario')
        );
    
        if ($this->tags_model->recharge_tag($this->get('id'), $data)) {
            $this->response(['message' => 'Recarga realizada correctamente'], RestController::HTTP_OK);
        } else {
            $this->response(['message' => 'Error al realizar la recarga'], RestController::HTTP_INTERNAL_ERROR);
        }
    }

    public function unassign_tag_post() {
        $this->_params_validation_id();
        
        // Datos para la tabla tags_numeros_economicos
        $data_unassign = array(
            'fecha_baja' => date('Y-m-d H:i:s'),
            'comentario_baja' => $this->post('comentario'),
            'status' => -1,
            'updated_at' => date('Y-m-d H:i:s')
        );
        
        // Datos para la tabla tags
        $data_tag = array(
            'status' => -1,
            'updated_at' => date('Y-m-d H:i:s')
        );
    
        if ($this->tags_model->unassign_tag($this->get('id'), $data_unassign, $data_tag)) {
            $this->response(['message' => 'TAG dado de baja correctamente'], RestController::HTTP_OK);
        } else {
            $this->response(['message' => 'Error al dar de baja el TAG'], RestController::HTTP_INTERNAL_ERROR);
        }
    }
    public function get_last_recharge_movement_get() {
        $this->_params_validation_id();
        $tag_id = $this->get('id');
        
        $this->load->model('tags_movimientos_model');
        $movimiento = $this->tags_movimientos_model->get_last_recharge_by_tag_id($tag_id);
        
        if ($movimiento) {
            $this->response(['movimiento' => $movimiento], RestController::HTTP_OK);
        } else {
            $this->response(['message' => 'No se encontraron movimientos de recarga para este TAG'], RestController::HTTP_NOT_FOUND);
        }
    }

    private function _form_validation_create() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('numero_tag', 'Número de TAG', 'trim|required|max_length[50]');
        if (!$this->form_validation->run()) {
            $this->response(array('message' => validation_errors()), RestController::HTTP_BAD_REQUEST);
        }
    }

    private function _form_validation_assign() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('numero_economico_id', 'Número Económico', 'trim|required|is_natural_no_zero');
        $this->form_validation->set_rules('comentario', 'Comentario', 'trim|max_length[500]');
        if (!$this->form_validation->run()) {
            $this->response(array('message' => validation_errors()), RestController::HTTP_BAD_REQUEST);
        }
    }

    private function _fill_data_insert() {
        return array(
            'numero_tag' => $this->post('numero_tag'),
            'saldo' => 0.00,
            'fecha_activacion' => date('Y-m-d H:i:s'),
            'status' => 1,
            'created_at' => date('Y-m-d H:i:s')
        );
    }

    private function _get_limit_offset_order_and_filters() {
        $default_order = array();
        $this->load->helper('pagination_order_filters');
        $limit_offset_order_and_filters = get_limit_offset_order_and_filters($default_order);
        
        // Agregar el filtro adicional por saldo si existe
        $saldo_categoria = $this->get('saldo_categoria');
        if ($saldo_categoria) {
            $limit_offset_order_and_filters['saldo_categoria'] = $saldo_categoria;
        }
        
        // Agregar el filtro adicional por asignación si existe
        $asignacion = $this->get('asignacion');
        if ($asignacion) {
            $limit_offset_order_and_filters['asignacion'] = $asignacion;
        }
        
        return $limit_offset_order_and_filters;
    }

    private function _params_validation_page_order_and_filters() {
        $this->load->library('params_validation');
        $this->params_validation->set_rules('pagina', 'Paginación', 'trim|is_natural_no_zero');
        $this->params_validation->set_rules('by_page', 'Cantidad de elementos por página', 'trim|is_natural_no_zero');
        $this->params_validation->set_rules('saldo_categoria', 'Categoría de saldo', 'trim');
        $this->params_validation->set_rules('asignacion', 'Estado de asignación', 'trim');
        if (!$this->params_validation->run()) {
            $this->response(['message' => params_validation_errors()], RestController::HTTP_BAD_REQUEST);
        }
    }

    private function _params_validation_id() {
        $this->load->library('params_validation');
        $this->params_validation->set_rules('id', 'ID', 'trim|required|is_natural_no_zero');
        if (!$this->params_validation->run()) {
            $this->response(array('message' => params_validation_errors()), RestController::HTTP_BAD_REQUEST);
        }
    }
    private function _form_validation_recharge() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('monto', 'Monto', 'trim|required|numeric|greater_than[0]');
        $this->form_validation->set_rules('comentario', 'Comentario', 'trim|max_length[500]');
        if (!$this->form_validation->run()) {
            $this->response(array('message' => validation_errors()), RestController::HTTP_BAD_REQUEST);
        }
    }
}