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

class series extends MY_Controller
{

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

        if (!$this->loggedIn) {
            redirect('login');
        }
    }

    function index($idDoc = null,$msn=null)
    {
        //Busco documentos para crear el select
        $context = stream_context_create(array(
            'http' => array(
                'method' => 'GET',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' =>''
            )
        ));
        $url=$this->config->item('api_general');
        $urlSerie='doc';
        $response = file_get_contents($url . $urlSerie, false, $context);
        $documents = json_decode($response, true);
        // $documents=null;

        if( $msn['result'] == "failed" ){
            if( is_array($msn['message']) ){
                $m =$msn['message'];
                $msj_error = "";
                foreach($m as $item => $valor){
                    foreach ($valor as $cont){
                        $msj_error .= $cont.'\n';
                    }
                }
            } else {
                $msj_error = $msn['message'];
            }
            $this->data['error'] = $msj_error; //validation_errors() ? validation_errors() : $this->session->flashdata('error');    
        } elseif( $msn['result'] == "ok" ){
            $this->data['message'] = $msn['message'];
        } else {

        }

        $this->data['documents'] = $documents['data']['list'];
        //$this->data['error'] = ""; //validation_errors() ? validation_errors() : $this->session->flashdata('error');
        $this->data['page_title'] = lang('Series');
        $this->data['idDoc'] = $idDoc;
        $bc = array(array('link' => '#', 'page' => lang('series')));
        $meta = array('page_title' => lang('Series de documentos'), 'bc' => $bc, 'msn'=> $msn);
        $this->page_construct('series/index', $this->data, $meta);
    }
    
    function get_series($idDoc = null){

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

        $context_data["business_information"] = $biz;
        
        $urlSerie = "doc/".$idDoc.'/series';
                            
        $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');
       
        $columnas = array(
            0 => 'id',
            1 => 'serie',
            2 => 'correlative',
            3 => 'correlative'
        );

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

     
        $documentid=$idDoc;

        $rows = array();
        $temporal = array();
        
        if ($filtro != "") {
            $values = "?search=" . $filtro . "&orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length.'&documentid='.$documentid;
            $urlSerie = $urlSerie . $values;
        } else {
            $values = "?orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length.'&documentid='.$documentid;
            $urlSerie = $urlSerie . $values;                  
        }

        $response = file_get_contents($url . $urlSerie, false, $context);
        
        $documents = json_decode($response, true);
        
        
        $contador_total = $documents['data']['total'];
        $contador_filtrado = $documents['data']['total'];
        $rows['draw'] = $draw;

        $rows['recordsFiltered'] = $contador_total;
        
        if($documents['result']=='ok'){
            foreach ($documents['data']['list'] as $item) {
            
                $id = $item['id'];
                $code = $item['serie'];
                $correlative = $item['correlative'];
                $description = $item['description'];
                $flg_started=$item['flg_started'];
                $edit = '<span class="btn"><a href="#" title="' . lang("edit_description") . '" data-toggle="modal" data-target="#myModal" data-id="'.$id.'" class="btn-edit"><i class="fa fa-edit"></i></a></span>';
               
                $show = '<span class="btn"><a href="' . site_url('series/show/' . $id) . '" title="' . lang("show") . '"><i class="fa fa-barcode"></i></a></span>';
                $delete = '<span class="btn"><a href="' . site_url('series/delete/' . $id .'?iddoc='.$idDoc) . '" onClick="return confirm(&#39;Desea eliminar la serie '.$id.'&#39;)" title="' . lang("delete") . '"><i class="fa fa-trash-o"></i></a></span>';
                //evaluo si la serie se inicio no se puede editar ni eliminar
                if($flg_started==0){
                    $option="<a href='' title='" . lang('edit_serie') . "' data-toggle='modal' data-target='#myModal' data-id='".$id."'  class='btn-edit tip btn btn-warning btn-xs'><i class='fa fa-edit'></i></a> <a href='" . site_url("series/delete/" . $id ."?iddoc=".$idDoc) . "' onClick='return confirm(&#39;Desea eliminar la serie ".$id."? &#39;)' title='" . lang('delete') . "'class='tip btn btn-danger btn-xs'><i class='fa fa-trash-o'></i></a>";
                }else{
                    $option="<a href='' title='" . lang('edit_serie') . "' data-id='".$id."'  class='btn btn-warning btn-xs' disabled><i class='fa fa-edit'></i></a> <a href=''  title='" . lang('delete') . "'class='tip btn btn-danger btn-xs' disabled><i class='fa fa-trash-o'></i></a>";
                }
    
                $datos = (array('id' => $id, 'serie' => $code, 'correlative' => $correlative,'description' => $description, 'edit' => $edit, 'show' => $show, 'delete' => $delete, 'option' => $option));
                array_push($temporal,$datos);
            }
        }else{
            $id = '';
            $code = '';
            $correlative = '';
            $description = '';

            $edit = '<span class="btn"><a href="#" title="' . lang("edit_description") . '" data-toggle="modal" data-target="#myModal" data-id="'.$id.'" class="btn-edit" disabled><i class="fa fa-edit"></i></a></span>';
           
            $show = '<span class="btn"><a href="' . site_url('series/show/' . $id) . '" title="' . lang("show") . '"><i class="fa fa-barcode"></i></a></span>';
            $delete = '<span class="btn"><a href="' . site_url('series/delete/' . $id .'?iddoc='.$idDoc) . '" onClick="return confirm(&#39;Desea eliminar la serie '.$id.'&#39;)" title="' . lang("delete") . '"><i class="fa fa-trash-o"></i></a></span>';
            $option="<a href='' title='" . lang('edit_description') . "' data-toggle='modal' data-target='#myModal' data-id='".$id."'  class='btn-edit tip btn btn-warning btn-xs' disabled><i class='fa fa-edit'></i></a> <a href='" . site_url("series/delete/" . $id ."?iddoc=".$idDoc) . "' onClick='return confirm(&#39;Desea eliminar la serie ".$id."? &#39;)' title='" . lang('delete') . "'class='tip btn btn-danger btn-xs' disabled><i class='fa fa-trash-o'></i></a></div></div>";

            $datos = (array('id' => $id, 'serie' => $code, 'correlative' => $correlative,'description' => $description, 'edit' => $edit, 'show' => $show, 'delete' => $delete, 'option' => $option));
            array_push($temporal,$datos);

        }
        

        $rows['data'] = $temporal;

        echo json_encode($rows);
    }
    


    function edit()
    {
        $id =  $this->input->post('idSerie');
        $correlativeEdit =  $this->input->post('correlativeEdit') ;
        $document_type_id =  $this->input->post('document_type_id') ;
        $descriptionEdit = $this->input->post('descriptionEdit');
        $flg_started = $this->input->post('flg_started');
        $serieEdit = $this->input->post('serieEdit');

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

        $context_data["business_information"] = $biz;

        $context_data["correlative"] = $correlativeEdit;
        $context_data["document_type_id"] = $document_type_id;
        $context_data["description"] = $descriptionEdit;
        if($flg_started === null){
            $flg_started=0;
        }
        $context_data["flg_started"] = $flg_started;
        $context_data["serie"] = $serieEdit;
        
        $urlSerie = "serie/".$id;
                            
        $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)
            )
        ));
                    
        $url = $this->config->item('api_general');
        $response = file_get_contents($url . $urlSerie, false, $context);
        $documents = json_decode($response, true);
        $msn=$documents;
        $this->index($document_type_id,$msn);
    }
    
    function store()
    {
        $id =  $this->input->post('idSerie');
        $correlativeEdit =  $this->input->post('correlativeEdit') ;
        $document_type_id =  $this->input->post('document_type_id') ;
        $descriptionEdit = $this->input->post('descriptionEdit');
        // $flg_started = $this->input->post('flg_started');
        $serieEdit = $this->input->post('serieEdit');

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

        $context_data["business_information"] = $biz;

        $context_data["correlative"] = $correlativeEdit;
        $context_data["document_type_id"] = $document_type_id;
        $context_data["description"] = $descriptionEdit;
        // $context_data["flg_started"] = $flg_started;
        $context_data["serie"] = $serieEdit;
        
        $urlSerie = "serie";
        
                 
        $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');
        // echo 'url:'.$url;
        // echo '<br>UrlSerie: '.$urlSerie;
        // var_dump($context_data);
        
        $rows = array();
        $response = file_get_contents($url . $urlSerie, false, $context);
        
        $documents = json_decode($response, true);
        // var_dump($documents);
        // exit();
        $msn=$documents;
        $this->index($document_type_id,$msn);
    }



    function delete($id = NULL)
    {
        $idDoc=$_GET['iddoc'];
        $document_type_id =  $this->input->post('document_type_id') ;

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

        $context_data["business_information"] = $biz;

        $context_data["document_type_id"] = $document_type_id;
        
        $urlSerie = "serie/".$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_general');
        // echo 'url:'.$url;
        // echo '<br>UrlSerie: '.$urlSerie;
        // var_dump($context_data);
        
        $rows = array();
        $response = file_get_contents($url . $urlSerie, false, $context);
        
        $documents = json_decode($response, true);
        // var_dump($documents);
        // exit();
        $msn=$documents;
        
        $this->index($idDoc,$msn);
    }

  

    function get_serie_by_serie($id) {

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

        $context_data["business_information"] = $biz;
        
        $urlSerie = "serie/".$id;
                            
        $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');

        $rows = array();
        $response = file_get_contents($url . $urlSerie, false, $context);
        
        $documents = json_decode($response, true);

        $rows['data'] = $documents;

        echo json_encode($rows);

    }

  

}
