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

class Models extends MY_Controller
{

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

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

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


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

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

        $columnas = array(
            0 => 'id',
            1 => 'id_brand',
            2 => 'code',
            3 => 'model',
            4 => '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"];

        $urlModels = "models";
        $values = "?orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length;
        if ($filtro != "") {
            $values = $values . "&search=" . $filtro;
        }
        $urlModels = $urlModels . $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 . $urlModels, 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'];
                $brand_id = $item['id_brand'];
                $brand = (!is_null($item['brand']) ? $item['brand']['brand'] : "");
                $code = $item['code'];
                $model = $item['model'];

                $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("question_remove_model") . '&#39;)" title="' . lang("delete") . '"><i class="fa fa-trash-o"></i></a>';


                $datos = (array('id' => $id, 'brand_id' => $brand_id, 'brand' => $brand, 'code' => $code, 'model' => $model, '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()
    {
        $response_api = "";

        $this->form_validation->set_rules('model_brand', lang("model_brand"), 'required');
        $this->form_validation->set_rules('model_code', lang("model_code"), 'required');
        $this->form_validation->set_rules('model_name', lang("model_name"), 'required');

        if ($this->form_validation->run() == true) {
            $context_data = array(
                'id_brand' => (string)$this->input->post('model_brand'),
                'code' => (string)$this->input->post('model_code'),
                'model' => (string)$this->input->post('model_name')
            );

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

            $response_api = $response['result'];
        } elseif ($this->input->post('add_model')) {
            $this->session->set_flashdata('error', validation_errors());
            redirect("models/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("models/add");
            }
            if ($response['result'] == "ok") {
            $this->session->set_flashdata('message', lang("model_added"));
            redirect("models");
            }
        } else {
            $this->data['form_data'] = $this->session->flashdata('form_data');
            $this->session->set_flashdata('form_data','');
            $biz = array(
                "ruc_number"=> (string)($this->session->userdata('ruc'))
            );
            $context_data["business_information"] = $biz;
            $urlBrands = "brands";
            $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 . $urlBrands, false, $context);
            $res = json_decode($response, true);

            $brand_list = array();
            $brand_list[0] = lang('select_brand', 'select_brand');
            if($res['result']=='ok') {
                foreach($res['data']['list'] as $item) {
                    $brand_list[$item['id']] = $item['brand'];
                }
            }

            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['brands'] = $brand_list;
            $this->data['page_title'] = lang('new_model');
            $bc = array(array('link' => site_url('models'), 'page' => lang('models')), array('link' => '#', 'page' => lang('new_model')));
            $meta = array('page_title' => lang('new_model'), 'bc' => $bc);
            $this->page_construct('models/add', $this->data, $meta);
        }
    }

    function edit($id = NULL)
    {
        $response_api = "";

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

        $this->form_validation->set_rules('model_brand', lang("model_brand"), 'required');
        $this->form_validation->set_rules('model_code', lang("model_code"), 'required');
        $this->form_validation->set_rules('model_name', lang("model_name"), 'required');

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

        if ($this->form_validation->run() == true) {
            $context_data = array(
                'id_brand' => (string)$this->input->post('model_brand'),
                'code' => (string)$this->input->post('model_code'),
                'model' => (string)$this->input->post('model_name')
            );

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

            $response_api = $response['result'];
        } elseif ($this->input->post('models')) {
            $this->session->set_flashdata('error', validation_errors());
            redirect("models/edit/");
        }

        if ($response_api == "failed") {
            //$this->session->set_flashdata('error', lang("model_updated_error"));
            $this->session->set_flashdata('error', $response['message']);
            redirect("models/edit/" . $id);
        }

        if ($this->form_validation->run() == true && $response_api == "ok") {
            $this->session->set_flashdata('message', lang("model_updated"));
            redirect("models");
        }
        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("models/edit/" . $id);
            }
            if ($response['result'] == "ok") {
            $this->session->set_flashdata('message', lang("model_added"));
            redirect("models");
            }
        } else {
            $this->data['form_data'] = $this->session->flashdata('form_data');
            $this->session->set_flashdata('form_data','');
            $biz = array(
                "ruc_number"=> (string)($this->session->userdata('ruc'))
            );
            $context_data["business_information"] = $biz;
            $urlBrands = "brands";
            $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 . $urlBrands, false, $context);
            $res = json_decode($response, true);

            $brand_list = array();
            $brand_list[0] = lang('select_brand', 'select_brand');
            if($res['result']=='ok') {
                foreach($res['data']['list'] as $item) {
                    $brand_list[$item['id']] = $item['brand'];
                }
            }

            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['brands'] = $brand_list;
            $this->data['model'] = $model;
            $this->data['page_title'] = lang('edit_model');
            $bc = array(array('link' => site_url('models'), 'page' => lang('models')),array('link' => '#', 'page' => lang('edit_model')));
            $meta = array('page_title' => ( lang('model'). ": ".$model->code), 'bc' => $bc);
            $this->page_construct('models/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;
        $urlModels = "models/" . $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 . $urlModels, false, $context);
        $res = json_decode($response, true);
        $model = (object) $res['data'];

        //if ($this->Warehouses_model->deleteWarehouse($id)) {
        $this->session->set_flashdata('success_message', lang("model_deleted"));
        redirect('models', 'refresh');
    }

}
