
<?php

class Tickets extends MY_Controller{
    public function  __construct(){
        parent::__construct();
        $this->load->library('form_validation');
    }
    public function index(){
        $this->data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
		$this->data['page_title'] = lang('list_tickets');
		$bc = array(array('link' => '#', 'page' => lang('list_tickets')));
		$meta = array('page_title' => lang('list_tickets'), 'bc' => $bc);
        $this->page_construct('tickets/index', $this->data, $meta);
    }
    public function get_tickets() {
        $rows = array();
        $temporal = array();
        $columnas = array(
            0 => 'id_ticket',
            1 => 'numero',
            2 => 'fec_emision',
            3 => 'fec_periodo_ini',
            4 => 'fec_periodo_fin',
            5 => 'fec_vencimiento', 
            6 => 'imp_total', 
            7 => 'fec_pago',
            8 => 'estado',
            9 => 'action',
             
        );
    
        // Obtener los datos de la solicitud
        $data = $_GET;
        $filtro = $_GET["search"]['value'];
        $orderby = $columnas[$data['order'][0]['column']];
        $orderdir = $_GET['order'][0]['dir'];
        $start = $_GET['start'];
        $length = $_GET['length'];
        $draw = $_GET["draw"];
    
        // Construir la URL del API
        $api_url = $this->config->item('api_admin');
        $url = $api_url . "client/ticket/{$this->session->userdata('ruc')}?orderby=$orderby&orderdir=$orderdir&start=$start&length=$length";
        log_message("error", $url);
        if ($filtro != "") {
            $url .= "&search=$filtro";
        }
        
        $context = stream_context_create(
			array(
				'http' => array(
					'method' => 'GET',
					'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
					//'content' => json_encode($context_data)
				)
			)
		);
        $response = file_get_contents($url, false, $context);
        $tickets = json_decode($response, true);
        log_message('error',$url);
        log_message('error',$response);
    
        if ($tickets) {
            $contador_total = $tickets['total'];
            $contador_filtrado = isset($tickets['recordsFiltered']) ? $tickets['recordsFiltered'] : $contador_total;
            $rows['draw'] = $draw;
            $rows['recordsTotal'] = $contador_total;
            $rows['recordsFiltered'] = $contador_filtrado;
        
    
                foreach ($tickets['list'] as $item) {
                    $id_ticket = $item['id_ticket'];
                    $numero = $item['numero'];
                    $fec_emision = date('d-m-Y H:i:s', strtotime($item['fec_emision']));
                    $fec_periodo_ini = date('d-m-Y H:i:s', strtotime($item['fec_periodo_ini']));
                    $fec_periodo_fin = date('d-m-Y H:i:s', strtotime($item['fec_periodo_fin']));
                    $fec_vencimiento = date('d-m-Y H:i:s', strtotime($item['fec_vencimiento']));
                    $imp_total = $item['imp_total'];
                    $fec_pago = $item['fec_pago'];
                    $estado = ($item['estado'] == 1) ? 'Pendiente' : (($item['estado'] == 2) ? 'Pagado' : (($item['estado'] == 3) ? 'Anulado' : 'Desconocido'));

                    $verdetalle = "
                    <div class = 'col-xs-2'> 
                    <a  title='" . lang("view_detail") . "' class='ver-detalle-btn btn btn-primary btn-xs' data-toggle='modal' data-target='#modaldetalle' data-id='".$id_ticket."'>
                    <i class='fa fa-edit'></i>
                    			
                    </div>";
                    $html_action = "<div class='text-center'>";
					$html_action .= "<div class='btn-group'>";
					$html_action .= $verdetalle;
                    $html_action .= "</div>";
					$html_action .= "</div>";
                
                    $datos = array(
                        'id' => $id_ticket, 
                        'numero' => $numero, 
                        'fec_periodo_ini' =>$fec_periodo_ini,
                        'fec_periodo_fin' =>$fec_periodo_fin ,
                        'fec_vencimiento' =>$fec_vencimiento,
                        'fec_emision' => $fec_emision, 
                        'imp_total' => $imp_total,
                        'fec_pago' =>$fec_pago,
                        'estado' =>$estado,
                        "action" => $html_action,
                        
                    );
                    array_push($temporal, $datos);
                }
            } else {
                $error_message = 'Error al cargar los tickets. Por favor, inténtalo de nuevo más tarde.';
                $contador_total = 0;
                $contador_filtrado = 0;
                $rows['error'] = $error_message;
                $rows['draw'] = $draw;
                $rows['recordsTotal'] = $contador_total;
                $rows['recordsFiltered'] = $contador_filtrado;
            }
         
         // Construir la respuesta JSON
        $rows['data'] = $temporal;

        // Enviar la respuesta
        echo json_encode($rows);
        }
        public function detalle($id_ticket) {
            
            // Construir la URL del API para obtener los detalles del ticket
            $api_url = $this->config->item('api_admin');
            $url = $api_url . "client/ticket_detalle/{$id_ticket}";
            // Hacer la solicitud al API
            $context = stream_context_create(
                array(
                    'http' => array(
                        'method' => 'GET',
                        'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n"
                    )
                )
            );
            $response = file_get_contents($url, false, $context);
            $detalle_ticket = json_decode($response, true);
            
            log_message('error',$url);
            log_message('error',$response);
            
            // Devolver los detalles del ticket
           echo json_encode($detalle_ticket);       
        }       
} 