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

class Brands extends MY_Controller
{

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

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

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


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

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

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

        $urlBrands = "brands";
        $values = "?orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length;
        if ($filtro != "") {
            $values = $values . "&search=" . $filtro;
        }
        $urlBrands = $urlBrands . $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 . $urlBrands, 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'];
                $brand = $item['brand'];

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


                $datos = (array('id' => $id, 'code' => $code, 'brand' => $brand, '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('brand_code', lang("brand_code"), 'required');
        $this->form_validation->set_rules('brand_name', lang("brand_name"), 'required');

        if ($this->form_validation->run() == true) {
            $context_data = array(
                'code' => (string)$this->input->post('brand_code'),
                'brand' => (string)$this->input->post('brand_name')
            );

            $biz = array(
                "ruc_number"=> (string)($this->session->userdata('ruc'))
            );
            $context_data["business_information"] = $biz;
            $urlBrands = "brands";
            $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 . $urlBrands, false, $context);
            $response = json_decode($response, true);
            $response_api = $response['result'];
        } elseif ($this->input->post('add_brand')) {
            $this->session->set_flashdata('error', validation_errors());
            redirect("brands/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("brands/add");
            }
            if ($response['result'] == "ok") {
            $this->session->set_flashdata('message', lang("brand_added"));
            redirect("brands");
            }
        } 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_brand');
            $bc = array(array('link' => site_url('brands'), 'page' => lang('brands')), array('link' => '#', 'page' => lang('new_brand')));
            $meta = array('page_title' => lang('new_brand'), 'bc' => $bc);
            $this->page_construct('brands/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('brand_code', lang("brand_code"), 'required');
        $this->form_validation->set_rules('brand_name', lang("brand_name"), 'required');

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

        if ($this->form_validation->run() == true) {
            $context_data = array(
                'code' => (string)$this->input->post('brand_code'),
                'brand' => (string)$this->input->post('brand_name')
            );

            $biz = array(
                "ruc_number"=> (string)($this->session->userdata('ruc'))
            );
            $context_data["business_information"] = $biz;
            $urlBrands = "brands/" . $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 . $urlBrands, false, $context);
            $response = json_decode($response, true);
            $response_api = $response['result'];
        } elseif ($this->input->post('brands')) {
            $this->session->set_flashdata('error', validation_errors());
            redirect("brands/edit/");
        }

        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("brands/edit/" . $id);
            }
            if ($response['result'] == "ok") {
            $this->session->set_flashdata('message', lang("brand_added"));
            redirect("brands");
            }
        }else {
            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['form_data'] = $this->session->flashdata('form_data');
            $this->session->set_flashdata('form_data','');
            $this->data['brand'] = $brand;
            $this->data['form_data'] = $this->session->flashdata('form_data');
            $this->session->set_flashdata('form_data','');
            $this->data['page_title'] = lang('brand'). ": ".$brand->code;
            $bc = array(array('link' => site_url('brands'), 'page' => lang('brands')),array('link' => '#', 'page' => lang('edit_brand')));
            $meta = array('page_title' => ( lang('brand'). ": ".$brand->code), 'bc' => $bc);
            $this->page_construct('brands/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;
        $urlBrands = "brands/" . $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 . $urlBrands, false, $context);
        $res = json_decode($response, true);
        $brand = (object) $res['data'];

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

}
