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

class Guide extends MY_Controller
{

    function __construct() {
        parent::__construct();

        if (!$this->loggedIn) {
            redirect('login');
        }
        $this->load->library('form_validation');
        $this->load->model('products_model');
        $this->load->model('site');
        $this->load->model('sales_model');
        $this->load->model('pos_model');
        $this->load->model('mov_model');
        $this->load->model('Warehouses_model');
    }

    function index($idGuide = null,$msn=null){
        //obtengo los tipos de documento.
        $guideType= $idGuide;
        
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;
                       
        $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)
            )
        ));
        // $url = $this->config->item('api_general');
        // $urlDoc="doc";
        // $response = file_get_contents($url . $urlDoc, false, $context);
        // $documentsType = json_decode($response, true);
        // if($documentsType['result']=='ok'){
        //     $documents=$documentsType['data'];
        // }else{
        //     $documents=[];
        // }

        // $this->data['documents'] = $documents; 
        $this->data['error'] = validation_errors() ? validation_errors() : $this->session->flashdata('error');
        if($guideType=="i"){
            $this->data['page_title'] = lang('list_guides_entrance');
            $title= lang('list_guides_entrance');
        }elseif($guideType=="s"){
            $this->data['page_title'] = lang('list_guides_departure');
            $title= lang('list_guides_departure');
        }else{
            $this->data['page_title'] = lang('guides');
            $title= lang('guides');
        }
        
        $this->data['msn'] = $msn;
        $this->data['idGuide'] = $idGuide;
        $this->data['guideType'] = $guideType;
        // var_dump($this->data);
        // exit;
        $bc = array(array('link' => '#', 'page' => lang('guide')));
        $meta = array('page_title' => $title, 'bc' => $bc, 'msn'=> $msn);
        $this->page_construct('guides/index', $this->data, $meta);
    }


    function get_guides($type = null){
 
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;
        
        // $urlGuide = "registerguide";
        $urlGuide='warehouseguide?type='.$type;
                            
        $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)
            )
        ));
                    
        $url = $this->config->item('api_almacen');
        //$url = "http://192.168.0.35/api_almacen/public/api/v1/";
       
        $columnas = array(
            0 => 'id',
            1 => 'guide_type',
            2 => 'date',
            3 => 'warehouse_id'
        );

        $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"];

     
        $rows = array();
        
        if ($filtro != "") {
            $values = "&search=" . $filtro . "&orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length;
            $urlGuide = $urlGuide.$values;
        } else {
            $values = "&orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length;
            $urlGuide = $urlGuide.$values;                  
        }

        
        $response = file_get_contents($url . $urlGuide, false, $context);
        
        $guides = json_decode($response, true);
        //ACA HAY QUE MODIFICAR PARA TRAER EL TOTAL DE LA BASE DE DATOS
        $contador_total = $guides['data']['total'];
        $rows['draw'] = $draw;
        $rows['recordsFiltered'] = $contador_total;
        
        $temporal = array();

        if($guides['result']=='ok'){
            foreach ($guides['data']['list'] as $item) {
                if(($item['id'] != '') || ($item['id'] != null)){
                    $id = $item['id'];
                    if($item['customer_id']>0){
                        $namePC=$item['customer_name'];
                        $titlePC="Cliente";
                    }elseif($item['supplier_id']>0){
                        $namePC=$item['supplier_name'];
                        $titlePC="Proveedor";
                    }
                    $datos = (array('item'=>$item,'namePC'=>$namePC,'titlePC'=>$titlePC));
                    array_push($temporal,$datos);
                }
            }
        }else{
            // $id = '';
            // $warehouse_name = '';
            // $date = '';
            // $docreference_number='';
            // $guide_number='';
            // $option="<a href='". site_url("guide/edit/" . $id) ."' title='" . lang('edit_guia') . "'  class='tip btn btn-warning btn-xs'><i class='fa fa-edit'></i></a> &nbsp; <a href='" . site_url("guide/delete/" . $id) . "' onClick='return confirm(&#39;Desea eliminar la guía ".$id."? &#39;)' title='" . lang('delete') . "'class='btn-edit tip btn btn-danger btn-xs'><i class='fa fa-trash-o'></i></a> &nbsp;";
            // $option.= "<a  data-toggle='modal' data-target='#exampleModal' class='btn-edit tip btn btn-secondary btn-xs'><i class='fa fa-unlock'></i></a>"; 
            // $datos = (array('id' => $id, 'warehouse_name' => $warehouse_name,'guide_number'=>$guide_number,'docreference_number'=>$docreference_number,'docreference_number'=>$docreference_number, 'date' => $date, 'option' => $option));
            // array_push($temporal,$datos);
            $temporal=[];
        }
        
       
        $rows['data'] = $temporal;
        echo json_encode($rows);
    }

    function addEntrance($idReg = null,$msn=null){     
          // Almacen => http://api.almacen.actecperu.com/api/v1/warehouses
        // Tipo de Movimiento => http://api.almacen.actecperu.com/api/v1/types_movement
        // Marcas => http://api.almacen.actecperu.com/api/v1/brands
        // Modelos => http://api.almacen.actecperu.com/api/v1/models
        // Productos => http://api.almacen.actecperu.com/api/v1/products
        // Formas de Pago => http://api.general.actecperu.com/api/v1/payment_methods
        // Tipo de Pago => http://actecperu.com/api/api_generalbeta/public/api/v1/paymenttypes
        
              
        $guide_type=  $this->input->get('guide_type');
      
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;
                       
        $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)
            )
        ));
        
        //Consultas locales  
        $igv = $this->Settings->default_tax_rate;

      

        
        // http://api.ventas.actecperu.com/api/v1/customer?business_information[ruc_number]=20601177511
        // http://api.compras.actecperu.com/api/v1/supplier?business_information[ruc_number]=10033699315
        //Consultas api ventas
        $url = $this->config->item('api_ventas');
        $urlcustomer="customer";
        $response = file_get_contents($url . $urlcustomer, false, $context);
        $customers = json_decode($response, true);
        if($customers['result']=='ok'){
            $customers=$customers['data'];
        }else{
            $customers=[];
        }
        //Consultas api compras
        $url = $this->config->item('api_compras');
        $urlsupplier="supplier";
        $response = file_get_contents($url . $urlsupplier, false, $context);
        $suppliers = json_decode($response, true);
        if($suppliers['result']=='ok'){
            $suppliers=$suppliers['data'];
        }else{
            $suppliers=[];
        }

        //Fin dustomer y supplier
        //Consultas api almacen
        $url = $this->config->item('api_almacen');
        $urlwarehouse="warehouses";
        $response = file_get_contents($url . $urlwarehouse, false, $context);
        $warehouses = json_decode($response, true);
        if($warehouses['result']=='ok'){
            $warehouses=$warehouses['data'];
        }else{
            $warehouses=[];
        }
        
        $urltypes_movement="types_movement";
        $response = file_get_contents($url . $urltypes_movement, false, $context);
        $types_movement = json_decode($response, true);
        if($types_movement['result']=='ok'){
            $types_movement=$types_movement['data'];
        }else{
            $types_movement=[];
        }
     
        $urlproducts="products";
        $response = file_get_contents($url . $urlproducts, false, $context);
        $products = json_decode($response, true);
        if($products['result']=='ok'){
            $products=$products['data'];
        }else{
            $products=[];
        }

        //Consultas api general
        $urlapi_general = $this->config->item('api_general');
        $urlpayment_methods="payment_methods";
        $response = file_get_contents($urlapi_general . $urlpayment_methods, false, $context);
        $payment_methods = json_decode($response, true);
        if($payment_methods['result']=='ok'){
            $payment_methods=$payment_methods['data'];
        }else{
            $payment_methods=[];
        }
       
        $urlpaymenttypes="paymenttypes";
        $response = file_get_contents($urlapi_general . $urlpaymenttypes, false, $context);
        $paymenttypes = json_decode($response, true);
        if($paymenttypes['result']=='ok'){
            $paymenttypes=$paymenttypes['data'];
        }else{
            $paymenttypes=[];
        }

        $prov_cli='';
       
        $exchange=$this->site->getExchange(date("Y-m-d"));

        $local_id = $this->session->userdata('local');
        $uCrea = $this->session->userdata('user_id');
        
        $this->data['local_id']= $local_id;
        $this->data['userguide_id']= $uCrea;
        $this->data['prov_cli']=$prov_cli;
        $this->data['guide_type']= $guide_type;
        $this->data['suppliers']= $suppliers;
        $this->data['customers']= $customers;
        $this->data['exchangenow']= $exchange;
        $this->data['igv']= $igv;
        $this->data['paymenttypes']= $paymenttypes;
        $this->data['warehouses']= $warehouses;
        $this->data['types_movement']= $types_movement;
        $this->data['payment_methods']= $payment_methods;
        $this->data['products']= $products;
        $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
        // $this->data['customers'] = $this->site->getAllCustomers();
        if($guide_type == "S"){
            $title="add_guide_departure";
        }else{
            $title="add_guide_entrance";
        }
       
        $this->data['page_title'] = lang($title);
        $bc = array(array('link' => site_url('guide'), 'page' => lang('guide')), array('link' => '#', 'page' => lang($title)));
        $meta = array('page_title' => lang($title), 'bc' => $bc);
        $this->page_construct('guides/add', $this->data, $meta);
        
    }

    function delete($id = null){
        if($id == null){
            $this->index();
        }

        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;

        $urlGuide = "warehouseguide/" . $id;
                            
        $context = stream_context_create(array(
            'http' => array(
                'method' => 'DELETE',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));
                                
        $url = $this->config->item('api_almacen');
        //$url = "http://192.168.0.35/api_almacen/public/api/v1/";
        $response = file_get_contents($url . $urlGuide, false, $context);
        $guide = json_decode($response, true);
        $msn=null;
        if($guide != null){
            if($guide['result']=='ok'){
                $msn= $guide['message'];
                // $this->session->set_flashdata( 'message', $msn);
            }
            if($guide['result']=='failed'){
                if(is_array($guide['message'])){
                    $msn = 'error';
                } else{
                    $msn = $guide['message'];
                } 
                // $this->session->set_flashdata( 'error', $msn);
            }
        }else{
            $msn= 'Error al ejecutar la transacción (Verifique su conexión a internet)';
        };  
        // if($guideType=="I"){
        //     redirect('guides_entrance/i',$guide);
        // }elseif($guideType=="S"){
        //     redirect('guides_departure/s',$guide);
        // }else{
        //     $this->index;
        // }
        echo $msn;
    }

    function edit($id = null, $msn = null){
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;
        $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)
            )
        ));
            //Consultas locales  
                    
            $igv = $this->Settings->default_tax_rate;

            //Falta las url de customer y supplier
            $url = $this->config->item('api_ventas');
            $urlcustomer="customer";
            $response = file_get_contents($url . $urlcustomer, false, $context);
            $customers = json_decode($response, true);
            if($customers['result']=='ok'){
                $customers=$customers['data'];
            }else{
                $customers=[];
            }
            //Consultas api compras
            $url = $this->config->item('api_compras');
            $urlsupplier="supplier";
            $response = file_get_contents($url . $urlsupplier, false, $context);
            $suppliers = json_decode($response, true);
            if($suppliers['result']=='ok'){
                $suppliers=$suppliers['data'];
            }else{
                $suppliers=[];
            }

            //Fin dustomer y supplier
            //Consultas api almacen
            $urlAlmacen = $this->config->item('api_almacen');
            $urlwarehouse="warehouses";
            $response = file_get_contents($urlAlmacen . $urlwarehouse, false, $context);
            $warehouses = json_decode($response, true);
            if($warehouses['result']=='ok'){
                $warehouses=$warehouses['data'];
            }else{
                $warehouses=[];
            }

            $urlproducts="products";
            $response = file_get_contents($urlAlmacen . $urlproducts, false, $context);
            $products = json_decode($response, true);
            if($products['result']=='ok'){
                $products=$products['data'];
            }else{
                $products=[];
            }

            //Busco el detalle de guia
            //$urlguide="registerguide/".$id;
            $urlguide="warehouseguide/".$id;
            $url = $this->config->item('api_almacen');     
            //$url = "http://192.168.0.35/api_almacen/public/api/v1/";
            $response = file_get_contents($url . $urlguide, false, $context);
            $guide = json_decode($response, true);
            if($guide['result']=='ok'){
                $guide=$guide['data'];
            }else{
                $guide=[];
            }

            $urltypes_movement="types_movement";
            $response = file_get_contents($urlAlmacen . $urltypes_movement, false, $context);
            $types_movement = json_decode($response, true);
            if($types_movement['result']=='ok'){
                foreach($types_movement['data'] as $type_mov){
                    
                }
                $types_movement=$types_movement['data'];
            }else{
                $types_movement=[];
            }

            //Consultas api general
            $urlapi_general = $this->config->item('api_general');
            $urlpayment_methods="payment_methods";
            $response = file_get_contents($urlapi_general . $urlpayment_methods, false, $context);
            $payment_methods = json_decode($response, true);
            if($payment_methods['result']=='ok'){
                $payment_methods=$payment_methods['data'];
            }else{
                $payment_methods=[];
            }

            $urlpaymenttypes="paymenttypes";
            $response = file_get_contents($urlapi_general . $urlpaymenttypes, false, $context);
            $paymenttypes = json_decode($response, true);
            if($paymenttypes['result']=='ok'){
                $paymenttypes=$paymenttypes['data'];
            }else{
                $paymenttypes=[];
            }

            if(($guide['supplier_id'] == '' || $guide['supplier_id'] == 0 ) && ($guide['customer_id'] != '' && $guide['customer_id'] > 0 )){
                $prov_cli=2;
            }elseif(($guide['customer_id'] == '' || $guide['customer_id'] == 0) && ($guide['supplier_id'] != '' && $guide['supplier_id'] > 0 ) ){
                $prov_cli=1;
            }else{
                $prov_cli='';
            }

            $this->data['id']=$guide['id'];
            $this->data['prov_cli']=$prov_cli;
            $this->data['guide_type']=$guide['guide_type'];
            $this->data['warehouse_id']=$guide['warehouse_id'];

            $fecha=$guide['date'];
            $findme   = '-0001';
            $pos = strpos($fecha, $findme);
            if ($pos !== false) {
                $fecha="";
            }
            $this->data['date']=$fecha;

            $fechaTras=$guide['date_tras'];
            $pos2 = strpos($fechaTras, $findme);
            if ($pos2 !== false) {
                $fechaTras="";
            }

            $local_id = $this->session->userdata('local');
            $uCrea = $this->session->userdata('user_id');
            
            $this->data['local_id']= $local_id;
            $this->data['userguide_id']= $uCrea;
            $this->data['date_tras']= $fechaTras;
            $this->data['supplier_id']=$guide['supplier_id'];
            $this->data['customer_id']=$guide['customer_id'];
            $this->data['payment_method_id']=$guide['payment_method_id'];
            $this->data['order_number']=$guide['order_number'];
            $this->data['docreference_number']=$guide['docreference_number'];
            $this->data['guide_number']=$guide['guide_number'];
            $this->data['movement_type_id']=$guide['movement_type_id'];
            $this->data['counter']=$guide['counter'];
            $this->data['currency']=$guide['currency'];
            $this->data['exchange']=$guide['exchange'];
            $this->data['details']=json_encode($guide['details'], true);
            $this->data['observation']=$guide['observation'];
            $this->data['warehouse_name']=$guide['warehouse_name'];
            
            $exchange=$this->site->getExchange(date("Y-m-d"));
            $this->data['prov_cli']=$prov_cli;
            $this->data['suppliers']= $suppliers;
            $this->data['customers']= $customers;
            $this->data['exchangenow']= $exchange;
            $this->data['igv']= $igv;
            $this->data['paymenttypes']= $paymenttypes;
            $this->data['warehouses']= $warehouses;
            $this->data['types_movement']= $types_movement;
            $this->data['payment_methods']= $payment_methods;
            $this->data['products']= $products;
            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            if($guide['guide_type']=="S"){
                $title=lang("edit_guide")." ".lang("departure");
            }else{
                $title=lang("edit_guide")." ".lang("entrance");
            }
            $this->data['msn'] = $msn;
            $this->data['page_title'] = lang( $title);
            $bc = array(array('link' => site_url('guide'), 'page' => lang('guide')), array('link' => '#', 'page' => lang($title)));
            $meta = array('page_title' => lang($title), 'bc' => $bc);
            $this->page_construct('guides/add', $this->data, $meta);
    }

    function store_guide(){
        $guideType=(string)$this->input->post('guide_type');
        $context_data = array(
            'warehouseguide_detail' => (string)$this->input->post('warehouseguide_detail'),
            'customer_name' => (string)$this->input->post('customer_name'),
            'supplier_name' => (string)$this->input->post('supplier_name'),
            'guide_type' => (string)$this->input->post('guide_type'),
            'warehouse_id' => (string)$this->input->post('warehouse_id'),
            'date' => (string)$this->input->post('date'),
            'date_tras' => (string)$this->input->post('date_tras'),
            'supplier_id' => (string)$this->input->post('supplier_id'),
            'customer_id' => (string)$this->input->post('customer_id'),
            'payment_method_id' => (string)$this->input->post('payment_method_id'),
            'order_number' => (string)$this->input->post('order_number'),
            'docreference_number' => (string)$this->input->post('docreference_number'),
            'observation' => (string)$this->input->post('observation'),
            'guide_number' => (string)$this->input->post('guide_number'),
            'movement_type_id' => (string)$this->input->post('movement_type_id'),
            'counter' => (string)$this->input->post('counter'),
            'currency' => (string)$this->input->post('currency'),
            'exchange' => (string)$this->input->post('exchange'),
            'warehouse_name' => (string)$this->input->post('warehouse_name')
        );
        
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;
        
                           
        $context = stream_context_create(array(
            'http' => array(
                'method' => 'POST',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));
        //$urlGuide='registerguide';
        $urlGuide='warehouseguide';
        //Guardo guide header
        $url = $this->config->item('api_almacen');
        //$url = "http://192.168.0.35/api_almacen/public/api/v1/";
        // echo $context_data['warehouseguide_detail'];
        // var_dump($context_data);
        // var_dump(json_decode($context_data['warehouseguide_detail']),true);
        // var_dump($url . $urlGuide);
        // exit();
        $response = file_get_contents($url . $urlGuide, false, $context);
        $guide = json_decode($response, true);
        $msn=null;
        if($guide != null){
            if($guide['result']=='ok'){
                $msn= $guide['message'];
                $this->session->set_flashdata( 'message', $msn);
            }
            if($guide['result']=='failed'){
                if(is_array($guide['message'])){
                    $m =$guide['message'];
                    $msn.= '<div class="alert a alert-danger alert-dismissible" role="alert">';
                    $msn.= ' <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><ul>';
                    
                    foreach($m as $item => $valor){
                        foreach ($valor as $cont){
                            $msn.= '<li>'.$cont.'</ul>';
                        }
                    }
                    $msn.='</ul></div>';
                } else{
                    $msn.= '<div class="alert a alert-danger alert-dismissible" role="alert">';
                    $msn.= ' <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
                    $msn.= $guide['message'];
                    $msn.= '</div>';
                } 
                $this->session->set_flashdata( 'error', $msn);
            }
        }else{
            $this->session->set_flashdata( 'error', 'Error al ejecutar la transacción (Verifique su conexión a internet)');
        };  
        if($guideType=="I"){
            redirect('guides_entrance/i',$guide);
        }elseif($guideType=="S"){
            redirect('guides_departure/s',$guide);
        }else{
            $this->index;
        }
    }

    function update($id=null){
        $guideType=(string)$this->input->post('guide_type');
        $context_data = array(
            'warehouseguide_detail' => (string)$this->input->post('warehouseguide_detail'),
            'customer_name' => (string)$this->input->post('customer_name'),
            'supplier_name' => (string)$this->input->post('supplier_name'),
            'guide_type' => (string)$this->input->post('guide_type'),
            'warehouse_id' => (string)$this->input->post('warehouse_id'),
            'date' => (string)$this->input->post('date'),
            'date_tras' => (string)$this->input->post('date_tras'),
            'supplier_id' => (string)$this->input->post('supplier_id'),
            'customer_id' => (string)$this->input->post('customer_id'),
            'payment_method_id' => (string)$this->input->post('payment_method_id'),
            'order_number' => (string)$this->input->post('order_number'),
            'docreference_number' => (string)$this->input->post('docreference_number'),
            'observation' => (string)$this->input->post('observation'),
            'guide_number' => (string)$this->input->post('guide_number'),
            'movement_type_id' => (string)$this->input->post('movement_type_id'),
            'counter' => (string)$this->input->post('counter'),
            'currency' => (string)$this->input->post('currency'),
            'exchange' => (string)$this->input->post('exchange'),
            'warehouse_name' => (string)$this->input->post('warehouse_name')
        );
       
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;
        
                           
        $context = stream_context_create(array(
            'http' => array(
                'method' => 'PUT',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));
        if($id == null){
            return;
        }else{
            $urlGuide='warehouseguide/'.$id;
            //$urlGuide='registerguide/'.$id;
            //Guardo guide header
            $url = $this->config->item('api_almacen');
            //$url = "http://192.168.0.35/api_almacen/public/api/v1/";
            $response = file_get_contents($url . $urlGuide, false, $context);
            $guide = json_decode($response, true);
            $guide = json_decode($response, true);
            $msn=null;
            if($guide != null){
                if($guide['result']=='ok'){
                    $msn = $guide['message'];
                    $this->session->set_flashdata( 'message', $msn);
                }
                if($guide['result']=='failed'){
                    if(is_array($guide['message'])){
                        $m =$guide['message'];
                        $msn.= '<div class="alert a alert-danger alert-dismissible" role="alert">';
                        $msn.= ' <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><ul>';
                        
                        foreach($m as $item => $valor){
                            foreach ($valor as $cont){
                                $msn.= '<li>'.$cont.'</ul>';
                            }
                        }
                        $msn.='</ul></div>';
                    } else{
                        $msn.= '<div class="alert a alert-danger alert-dismissible" role="alert">';
                        $msn.= ' <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
                        $msn.= $guide['message'];
                        $msn.= '</div>';
                    } 
                    $this->session->set_flashdata( 'error', $msn);
                }
            }else{
                $this->session->set_flashdata( 'error', 'Error al ejecutar la transacción (Verifique su conexión a internet)');
            };  
            if($guideType=="I"){
                redirect('guides_entrance/i',$guide);
            }elseif($guideType=="S"){
                redirect('guides_departure/s',$guide);
            }else{
                $this->index;
            }
        }
    }

    function addReg_guide(){
        $context_data = array(
            'data' => $this->input->post('data')
        );
        $idGuide =  $this->input->post('idGuide');

        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;      
        $urlGuide = "guides";          
        $context = stream_context_create(array(
            'http' => array(
                'method' => 'POST',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));
                    
        $url = $this->config->item('api_general');
        $response = file_get_contents($url . $urlGuide, false, $context);
        
        $guide = json_decode($response, true);
        $msn=$guide;
        $this->index($idGuide,$msn);  
    }

    function get_exchange(){
        $day = $this->input->get('data2');
        $date = str_replace('/', '-', $day);
        $newDate = date("Y/m/d", strtotime($date));
        $exchange=$this->site->getExchange($newDate);
        //$exchange=$this->Exchange->sel;
        
        echo json_encode($exchange , true);
        
    }

    function loadPage(){

        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;
        $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)
            )
        ));
            //Consultas locales  
                    
            $igv = $this->Settings->default_tax_rate;

            //Falta las url de customer y supplier
            $url = $this->config->item('api_almacen');          
            $urlcustomer="customers";
            $response = file_get_contents($url . $urlcustomer, false, $context);
            $customers = json_decode($response, true);
            if($customers['result']=='ok'){
                $customers=$customers['data'];
            }else{
                $customers=[];
            }
            $urlsupplier="suppliers";
            $response = file_get_contents($url . $urlsupplier, false, $context);
            $suppliers = json_decode($response, true);
            if($suppliers['result']=='ok'){
                $suppliers=$suppliers['data'];
            }else{
                $suppliers=[];
            }

            //Fin customer y supplier
            
            $urlwarehouse="warehouses";
            $response = file_get_contents($url . $urlwarehouse, false, $context);
            $warehouses = json_decode($response, true);
            if($warehouses['result']=='ok'){
                $warehouses=$warehouses['data'];
            }else{
                $warehouses=[];
            }
            
            $urltypes_movement="types_movement";
            $response = file_get_contents($url . $urltypes_movement, false, $context);
            $types_movement = json_decode($response, true);
            if($types_movement['result']=='ok'){
                $types_movement=$types_movement['data'];
            }else{
                $types_movement=[];
            }

            $urlproducts="products";
            $response = file_get_contents($url . $urlproducts, false, $context);
            $products = json_decode($response, true);
            if($products['result']=='ok'){
                $products=$products['data'];
            }else{
                $products=[];
            }

            //Consultas api general
            $urlapi_general = $this->config->item('api_general');
            $urlpayment_methods="payment_methods";
            $response = file_get_contents($urlapi_general . $urlpayment_methods, false, $context);
            $payment_methods = json_decode($response, true);
            if($payment_methods['result']=='ok'){
                $payment_methods=$payment_methods['data'];
            }else{
                $payment_methods=[];
            }

            $urlpaymenttypes="paymenttypes";
            $response = file_get_contents($urlapi_general . $urlpaymenttypes, false, $context);
            $paymenttypes = json_decode($response, true);
            if($paymenttypes['result']=='ok'){
                $paymenttypes=$paymenttypes['data'];
            }else{
                $paymenttypes=[];
            }
                

            $this->data['guide_type']=$context_data['guide_type'];
            $this->data['warehouse_id']=$context_data['warehouse_id'];
            $this->data['date']=$context_data['date'];
            $this->data['date_tras']=$context_data['date_tras'];
            $this->data['supplier_id']=$context_data['supplier_id'];
            $this->data['customer_id']=$context_data['customer_id'];
            $this->data['payment_method_id']=$context_data['payment_method_id'];
            $this->data['order_number']=$context_data['order_number'];
            $this->data['docreference_number']=$context_data['docreference_number'];
            $this->data['guide_number']=$context_data['guide_number'];
            $this->data['movement_type_id']=$context_data['movement_type_id'];
            $this->data['counter']=$context_data['counter'];
            $this->data['currency']=$context_data['currency'];
            $this->data['exchange']=$context_data['exchange'];
            $this->data['observation']=$context_data['observation'];

            $exchange=$this->site->getExchange(date("Y-m-d"));

            $this->data['suppliers']= $suppliers;
            $this->data['customers']= $customers;
            $this->data['exchangenow']= $exchange;
            $this->data['igv']= $igv;
            $this->data['paymenttypes']= $paymenttypes;
            $this->data['warehouses']= $warehouses;
            $this->data['types_movement']= $types_movement;
            $this->data['payment_methods']= $payment_methods;
            $this->data['products']= $products;
            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            if($context_data['guide_type'] == "S"){
                $title="add_guide_departure";
            }else{
                $title="add_guide_entrance";
            }
            $this->data['page_title'] = lang($title);
            $bc = array(array('link' => site_url('guide'), 'page' => lang('guide')), array('link' => '#', 'page' => lang($title)));
            $meta = array('page_title' => lang($title), 'bc' => $bc);
            $this->page_construct('guides/add', $this->data, $meta);
    }

    function deleteReg( $id = null){
        $data = $this->input->get('data');

        $context_data = array(
            'data' => $data,
        );
 
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;
                           
        $context = stream_context_create(array(
            'http' => array(
                'method' => 'DELETE',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));
     
        $urlGuide='warehouseguide_detail/'.$id;
        //$urlGuide='registerguide_detail/'.$id;
        //Guardo guide header
        $url = $this->config->item('api_almacen');
        //$url = "http://192.168.0.35/api_almacen/public/api/v1/";
        $response = file_get_contents($url . $urlGuide, false, $context);
        $msn = json_encode($response, true);
        echo $msn;
    }

    function updateReg( $id = null){
        $series = $this->input->get('series');
        if( $series == null){
            $series=[];
        }
        $context_data = array(
            'warehouseguide_id' => (string)$this->input->get('warehouseguide_id'),
            'userguide_id' => (string)$this->input->get('userguide_id'),
            'local_id' => (string)$this->input->get('local_id'),
            'product_id' => (string)$this->input->get('product_id'),
            // 'lote' => (string)$this->input->get('lote'),
            'lote' => 'acataellote',
            'production_date' => (string)$this->input->get('production_date'),
            'expiration_date' => (string)$this->input->get('expiration_date'),
            'price' => (string)$this->input->get('price'),
            'name' => (string)$this->input->get('name'),
            'price_inc' => (string)$this->input->get('price_inc'),
            'avgdiscount' => (string)$this->input->get('avgdiscount'),
            'total' => (string)$this->input->get('total'),
            'quantity' => (string)$this->input->get('quantity'),
            'series' => $series,
            'observation' => (string)$this->input->get('observation')
        );

        // $ver= json_encode($context_data);
        // echo $ver. ", ID+ ".$id;
        // exit();
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );
        $context_data["business_information"] = $biz;
                         
        $context = stream_context_create(array(
            'http' => array(
                'method' => 'PUT',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));
     
        $urlGuide='warehouseguide_detail/'.$id;
        //$urlGuide='registerguide_detail/'.$id;
        //Guardo guide header
        $url = $this->config->item('api_almacen');
        //$url = "http://192.168.0.35/api_almacen/public/api/v1/";
        $response = file_get_contents($url . $urlGuide, false, $context);
        $msn = json_encode($response, true);
        echo $msn;
    }

    function createReg(){
       
        $context_data = array(
            'warehouseguide_id' => (string)$this->input->get('warehouseguide_id'),
            'userguide_id' => (string)$this->input->get('userguide_id'),
            'local_id' => (string)$this->input->get('local_id'),
            'product_id' => (string)$this->input->get('guide_type'),
            'lote' => (string)$this->input->get('lote'),
            'production_date' => (string)$this->input->get('production_date'),
            'expiration_date' => (string)$this->input->get('expiration_date'),
            'price' => (string)$this->input->get('price'),
            'name' => (string)$this->input->get('name'),
            'price_inc' => (string)$this->input->get('price_inc'),
            'avgdiscount' => (string)$this->input->get('avgdiscount'),
            'total' => (string)$this->input->get('total'),
            'quantity' => (string)$this->input->get('quantity'),
            'series' => $this->input->get('series'),
            'observation' => (string)$this->input->get('observation')
        );
        //$context_data = json_encode($context_data);

        
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );
        $context_data["business_information"] = $biz;
                         
        $context = stream_context_create(array(
            'http' => array(
                'method' => 'POST',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));
     
        $urlGuide='warehouseguide_detail';

        // var_dump($context_data);
        // var_dump($context);
        // exit();
        //$urlGuide='registerguide_detail/'.$id;
        //Guardo guide header
        $url = $this->config->item('api_almacen');
        //$url = "http://192.168.0.35/api_almacen/public/api/v1/";
        $response = file_get_contents($url . $urlGuide, false, $context);
        $msn = json_encode($response, true);
        echo $msn;
    }

}
