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

class Measure_units extends MY_Controller
{

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

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

        $this->load->library('form_validation');
        //$this->load->model('Measure_unit_model');
    }


    function index()
    {
        $this->data['error'] = validation_errors() ? validation_errors() : $this->session->flashdata('error');
        $this->data['page_title'] = lang('measure_units');
        $bc = array(array('link' => '#', 'page' => lang('measure_units')));
        $meta = array(
            'page_title' => lang('measure_units'),
            'bc' => $bc);
        $this->page_construct('measure_units/index', $this->data, $meta);
    }

    function get_measure_units(){
        $rows = array();
        $temporal = array();

        $columnas = array(
            0 => 'id',
            1 => 'code',
            2 => 'description',
            3 => 'code_sunat',
            4 => 'description_fe',
            5 => 'actions'
        );

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

        $urlMeasureUnits = "unitmeasure";
        $values = "?orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length;
        if ($filtro != "") {
            $values = $values . "&search=" . $filtro;
        }
        $urlMeasureUnits = $urlMeasureUnits . $values;

        $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_almacen');
        $response = file_get_contents($url . $urlMeasureUnits, false, $context);
        $response = json_decode($response, true);

        if($response['result']=='ok'){
            $contador_total = $response['data']['total'];
            $contador_filtrado = $response['data']['total'];
            $rows['draw'] = $draw;
            $rows['recordsFiltered'] = $contador_total;

            foreach ($response['data']['list'] as $item) {

                $id = $item['id'];
                $code = $item['code'];
                $description = $item['description'];
                $code_sunat = $item['code_sunat'];
                $description_fe = $item['description_fe'];

                $actions = '<a class="btn-edit tip btn btn-warning btn-xs" href="' .site_url('measure_units/edit/' . $id) . '" title="' . lang("edit_measure_units") . '"><i class="fa fa-edit"></i></a>';
                $actions = $actions . '<a class="tip btn btn-danger btn-xs" href="' . site_url('measure_units/delete/' . $id) . '" onClick="return confirm(&#39;' . lang("delete_measure_units") . '&#39;)" title="' . lang("delete") . '"><i class="fa fa-trash-o"></i></a>';                //$actions = '<a class="btn-edit tip btn btn-warning btn-xs" href="' . site_url('models/edit/' . $id) . '" title="' . lang("edit_model") . '"><i class="fa fa-edit"></i></a>';
                //$actions = $actions . '&nbsp;<a class="tip btn btn-danger btn-xs" href="' . site_url('models/delete/' . $id) . '" onClick="return confirm(&#39;' . lang("delete_model") . '&#39;)" title="' . lang("delete") . '"><i class="fa fa-trash-o"></i></a>';

                $datos = (array('id' => $id, 'code' => $code, 'description' => $description, 'code_sunat' => $code_sunat, 'description_fe' => $description_fe, 'actions' => $actions));
                array_push($temporal,$datos);
            }
        } else {
            $contador_total = 0;
            $contador_filtrado = 0;
            $rows['draw'] = $draw;
            $rows['recordsFiltered'] = $contador_total;
        }

        $rows['data'] = $temporal;

        echo json_encode($rows);
    }

    function add()
    {
        if (!$this->Admin) {
            $this->session->set_flashdata('error', lang('access_denied'));
            redirect('pos');
        }
        $response_api = "";

        $this->form_validation->set_rules('code', lang("code"), 'required');
        $this->form_validation->set_rules('description', lang("description"), 'required');
        $this->form_validation->set_rules('code_sunat', lang("code_sunat"), 'required');
        $this->form_validation->set_rules('description_fe', lang("description_fe"), 'required');

        if($this->form_validation->run() ==true) {
            $context_data = array(
                'code' => $this->input->post('code'),
                'description' => $this->input->post('description'),
                'code_sunat' => $this->input->post('code_sunat'),
                'description_fe' => $this->input->post('description_fe')

            );
        
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );
        
        $context_data["business_information"] = $biz;
        $urlMeasureUnits = "unitmeasure";
        $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_almacen');
        $response = file_get_contents($url . $urlMeasureUnits, false, $context);
        $response = json_decode($response, true);

        $response_api = $response['result'];
            
        } elseif ($this->input->post('add_measureunits')) {
            $this->session->set_flashdata('error', validation_errors());
            redirect("measure_units/add");
        }
 
        if ($this->form_validation->run() == true && isset($response)) {
            if ($response['result'] == "failed") {
                $dataError = [];
                if (is_array($response['message'])) {
                    foreach ($response['message'] as $key => $value) {
                        for ($i = 0; $i < count($response['message'][$key]); $i++) {
                            array_push($dataError, $response['message'][$key][$i]);
                        }
                    }
                } else {
                    array_push($dataError, $response['message']);
                }
                $this->session->set_flashdata('error', str_replace(',', '<br/>', implode(',', $dataError)));
                $this->session->set_flashdata('form_data', $_POST);
                redirect("measure_units/add");
            }
            if ($response['result'] == "ok") {
            $this->session->set_flashdata('message', lang("measureunits_added"));
            redirect("measure_units");
            }
        } else {
            $this->data['form_data'] = $this->session->flashdata('form_data');
            $this->session->set_flashdata('form_data','');
            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['page_title'] = lang('new_measure_unit');
            $bc = array(array('link' => site_url('measure_units'), 'page' => lang('measure_units')), array('link' => '#', 'page' => lang('new_measure_unit')));
            $meta = array('page_title' => lang('new_measure_unit'), 'bc' => $bc);
            $this->page_construct('measure_units/add', $this->data, $meta);
        }
    }

    function edit($id = NULL)
    {

        $response_api = "";

        if (!$this->Admin) {
            $this->session->get_flashdata('error', lang('access_denied'));
            redirect('pos');
        }

        if ($this->input->get('id')) {
            $id = $this->input->get('id');
        }
        
        $this->form_validation->set_rules('code', lang("code"), 'required');
        $this->form_validation->set_rules('description', lang("description"), 'required');
        $this->form_validation->set_rules('code_sunat', lang("code_sunat"), 'required');
        $this->form_validation->set_rules('description_fe', lang("description_fe"), 'required');

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

        $context_data["business_information"] = $biz;

        $urlMeasureUnits = "unitmeasure/" . $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_almacen');
        $response = file_get_contents($url . $urlMeasureUnits, false, $context);
        $res = json_decode($response, true);
        $urlMeasureUnit = (object) $res['data'];

        if($this->form_validation->run() == true) {
            $context_data = array(
                'code' => $this->input->post('code'),
                'description' => $this->post('description'),
                'code_sunat' => $this->post('code_sunat'),
                'description_fe' => $this->post('description_fe')
        );

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

        $context_data["business_information"] = $biz;
        $urlMeasureUnits = "unitmeasure/" . $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_almacen');
        $response = file_get_contents($url . $urlMeasureUnits, false, $context);
        $response = json_decode($response, true);
        $response_api = $response['result'];

        }

        
        if ($this->form_validation->run() == true && isset($response)) {
            if ($response['result'] == "failed") {
                $dataError = [];
                if (is_array($response['message'])) {
                    foreach ($response['message'] as $key => $value) {
                        for ($i = 0; $i < count($response['message'][$key]); $i++) {
                            array_push($dataError, $response['message'][$key][$i]);
                        }
                    }
                } else {
                    array_push($dataError, $response['message']);
                }
                $this->session->set_flashdata('error', str_replace(',', '<br/>', implode(',', $dataError)));
                $this->session->set_flashdata('form_data', $_POST);
                redirect("measure_units/edit/" . $id);
            }
            if ($response['result'] == "ok") {
                $this->session->set_flashdata('message', lang("unitmesure_updated"));
                redirect("measure_units");
            }
        } else {
            $this->data['form_data'] = $this->session->flashdata('form_data');
            $this->session->set_flashdata('form_data','');
            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['page_title'] = lang('edit_measure_units');
            $bc = array(array('link' => site_url('measure_units'), 'page' => lang('measure_units')), array('link' => '#', 'page' => lang('edit_measure_units')));
            $meta = array('page_title' => lang('edit_measure_units'), 'bc' => $bc);
            $this->page_construct('measure_units/edit', $this->data, $meta);
        }

    }

    function delete($id = NULL)
    {

        if (!$this->Admin) {
            $this->session->set_flashdata('error', lang('access_denied'));
            redirect('pos');
        }
        if ($this->input->get('id')) {
            $id = $this->input->get('id');
        }

        $biz = array(
            "ruc_number" => (string)($this->session->userdata('ruc'))
        );
        $context_data["business_information"] = $biz;
        $urlMeasureUnits = "unitmeasure/" . $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');
        $response = file_get_contents($url . $urlMeasureUnits, false, $context);
        $res = json_decode($response, true);
        $urlMeasureUnit = (object) $res['data'];

        $this->session->set_flashdata('success_message', lang('unite_deleted'));
        redirect('unitmeasure', 'refresh');

    }

}
