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

class Makers extends MY_Controller
{

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

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

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


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

    }

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

        $columnas = array(
            0 => 'id',
            1 => 'maker',
            2 => '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"];

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

        $urlMakers = $urlMakers . $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 . $urlMakers, 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'];
                $maker = $item['maker'];
                $actions = "<div class='text-right'>";
                $actions .= '<a class="btn-edit tip btn btn-warning btn-xs" href="' . site_url('makers/edit/' . $id) . '" title="' . lang("edit_maker") . '"><i class="fa fa-edit"></i></a>';
                $actions .=  '<a class="tip btn btn-danger btn-xs" href="' . site_url('makers/delete/' . $id) . '" onClick="return confirm(&#39;' . lang("delete_maker") . '&#39;)" title="' . lang("delete") . '"><i class="fa fa-trash-o"></i></a>';
                $actions .= '</div>';
                $datos = (array('id' => $id, 'maker' => $maker, '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('maker', lang("maker_name"), 'required');

        if ($this->form_validation->run() == true) {
            $context_data = array(
                'maker' => $this->input->post('maker')
            );

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

            $context_data["business_information"] = $biz;
            $urlMakers = "makers";
            $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 . $urlMakers, false, $context);
            $response = json_decode($response, true);
            $response_api = $response['result'];

        }elseif ($this->input->post('add_maker')) {
            $this->session->set_flashdata('error', validation_errors());
            redirect("makers/add");
        }

        if ($response_api == "failed") {
            $this->session->set_flashdata('error', lang("maker_added_error"));
            redirect("makers/add");
        }

        if ($this->form_validation->run() == true && $response_api == "ok") {
            $this->session->set_flashdata('message', lang("maker_added"));
            redirect("makers");
        } else {
            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['page_title'] = lang('new_maker');
            $bc = array(array('link' => site_url('makers'), 'page' => lang('makers')), array('link' => '#', 'page' => lang('new_maker')));
            $meta = array('page_title' => lang('new_maker'), 'bc' => $bc);
            $this->page_construct('makers/add', $this->data, $meta);
        }

    }

    function edit($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');
        }

        $response_api = "";

        $this->form_validation->set_rules('maker', lang("maker_name"), 'required');

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

        $context_data["business_information"] = $biz;
        $urlMakers = "makers/" . $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 . $urlMakers, false, $context);
        $res = json_decode($response, true);
        $maker = (object) $res['data'];

        if ($this->form_validation->run() == true) {
            $context_data = array(
                'maker' => $this->input->post('maker')
            );

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

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

        } elseif ($this->input->post('makers')) {
            $this->session->set_flashdata('error', validation_errors());
            redirect("makers/edit/" . $id);
        }

        if ($response_api == "failed") {
            $this->session->set_flashdata('error', lang("makers_updated_error"));
            redirect("makers/edit/" . $id);
        }

        if ($this->form_validation->run() == true && $response_api == "ok") {
            $this->session->set_flashdata('message', lang("maker_updated"));
            redirect("makers");
        } else {
            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['maker'] = $maker;
            $this->data['page_title'] = lang('edit_maker');
            $bc = array(array('link' => site_url('makers'), 'page' => lang('makers')), array('link' => '#', 'page' => lang('edit_maker')));
            $meta = array('page_title' => lang('edit_maker'), 'bc' => $bc);
            $this->page_construct('makers/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;
        $urlMakers = "makers/" .$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 . $urlMakers, false, $context);
        $res = json_decode($response, true);
        $maker = (object) $res['data'];

        $this->session->set_flashdata('success_message', lang("maker_deleted"));
        redirect('makers', 'refresh');

    }


}
