<?php

use PhpParser\Node\Expr\AssignOp\Mod;

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Categories extends MY_Controller
{

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

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

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

        require("funciones.php");
    }

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

    }

    function get_categories() {

        $rows = array();
        $temporal = array();

        $columnas = array(
            0 => 'id',
            1 => 'image',
            2 => 'code',
            3 => 'name',
            4 => 'actions',
            5 => 'view_image'
        );

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

        $urlCategories = "categories";
        $values = "?orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length;
        if ($filtro != "") {
            $values = $values . "&search=" . $filtro;
        }
        $urlCategories = $urlCategories . $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 . $urlCategories, false, $context);
        $response = json_decode($response, true);
        $categories = $response['data'];

        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) {
                $image = "";
                $id = $item['id'];
                $image = $item['image'];
                $code = $item['code'];
                $name = $item['name'];

                if ($image == "no_image.png") {
                    $view_image = '<a href="' . base_url() . 'uploads/thumbs/' . $image . '" class="image-modal tip image btn btn-primary btn-xs" data-title="' . $name . ' (' . $code . ')" title="' . lang("view_image") . '"><i class="fa fa-picture-o"></i></a>';
                    $image = '<a href="' . base_url() . 'uploads/thumbs/' . $image . '" class="image-modal" data-title="' . $name . ' (' . $code . ')"><img src="' . base_url() . 'uploads/thumbs/' . $image . '" class="img-responsive" width="32" style="margin: auto;" /></a>';
                } else {
                    $view_image = '<a href="' . base_url() . 'uploads/' . $image . '" class="image-modal tip image btn btn-primary btn-xs" data-title="' . $name . ' (' . $code . ')" title="' . lang("view_image") . '"><i class="fa fa-picture-o"></i></a>';
                    $image = '<a href="' . base_url() . 'uploads/' . $image . '" class="image-modal" data-title="' . $name . ' (' . $code . ')"><img src="' . base_url() . 'uploads/' . $image . '" class="img-responsive" width="32" style="margin: auto;" /></a>';
                }

                $actions = '<a class="btn-edit tip btn btn-warning btn-xs" href="' .site_url('categories/edit/' . $id) . '" title="' . lang("edit_category") . '"><i class="fa fa-edit"></i></a>';
                $actions = $actions . '<a class="tip btn btn-danger btn-xs" href="' . site_url('categories/delete/' . $id) . '" onClick="return confirm(&#39;' . lang("question_remove_category") . '&#39;)" title="' . lang("delete") . '"><i class="fa fa-trash-o"></i></a>';
                $actions .= $view_image;
                $datos = (array('id' => $id, 'image' => $image, 'code' => $code, 'name' => $name, '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("category_code"), 'trim|min_length[2]|required|alpha_numeric');
        $this->form_validation->set_rules('name', lang("category_name"), 'required');

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

        
            if ($_FILES['userfile']['size'] > 0) {
                $this->load->library('upload');

                $config['upload_path'] = 'uploads/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '500';
                $config['max_width'] = '800';
                $config['max_height'] = '800';
                $config['overwrite'] = FALSE;
                $config['encrypt_name'] = TRUE;
                $this->upload->initialize($config);

                if (!$this->upload->do_upload()) {
                    $error = $this->upload->display_errors();
                    $this->session->set_flashdata('error', $error);
                    $this->session->set_flashdata('form_data', $_POST);
                    redirect("categories/add", 'refresh');
                }

                $photo = $this->upload->file_name;
                $context_data['image'] = $photo;

                $this->load->library('image_lib');
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/' . $photo;
                $config['new_image'] = 'uploads/thumbs/' . $photo;
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 110;
                $config['height'] = 110;

                $this->image_lib->clear();
                $this->image_lib->initialize($config);

                if (!$this->image_lib->resize()) {
                    $this->session->set_flashdata('form_data', $_POST);
                    $this->session->set_flashdata('error', $this->image_lib->display_errors());
                    redirect("categories/add");
                }
            } else {
                $photo = "category.png";
            }

            $context_data['image'] = $photo;

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

            $context_data["business_information"] = $biz;
        
            $urlCategories = "categories";

            $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 . $urlCategories, false, $context);
            $response = json_decode($response, true);
            $response_api = $response['result'];
            
        // } elseif ($this->input->post('add_category')) {
        //     $this->session->set_flashdata('error', validation_errors());
        //     redirect("categories/add");
        // }
        }
        if ($this->form_validation->run() && isset($response)) { //NO TOQUES

            if (empty($response)) {
                $this->session->set_flashdata('form_data', $_POST);
                $this->session->set_flashdata('error', 'No se pudo agregar la categoria, consulte con su admistrador.');
                redirect("categories/add");
            } else {
                if ($response['result'] == 'ok') {
                    $this->session->set_flashdata('message', $response['message']);
                    redirect("categories");
                } else {
                    $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("categories/add");
                }
            }
        } 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['page_title'] = lang('add_category');
            $bc = array(array('link' => site_url('categories'), 'page' => lang('categories')), array('link' => '#', 'page' => lang('new_category')));
            $meta = array('page_title' => lang('add_category'), 'bc' => $bc);
            $this->page_construct('categories/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('code', lang("category_code"), 'required');
        $this->form_validation->set_rules('name', lang("category_name"), 'required');


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

            if ($_FILES['userfile']['size'] > 0) {
                $this->load->library('upload');

                $config['upload_path'] = 'uploads/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '500';
                $config['max_width'] = '800';
                $config['max_height'] = '800';
                $config['overwrite'] = FALSE;
                $config['encrypt_name'] = TRUE;
                $this->upload->initialize($config);

                if (!$this->upload->do_upload()) {
                    $error = $this->upload->display_errors();
                    $this->session->set_flashdata('error', $error);
                    $this->session->set_flashdata('form_data', $_POST);
                    redirect("categories/edit/" . $id);
                }

                $photo = $this->upload->file_name;
                $context_data['image'] = $photo;

                $this->load->library('image_lib');
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/' . $photo;
                $config['new_image'] = 'uploads/thumbs/' . $photo;
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 110;
                $config['height'] = 110;

                $this->image_lib->clear();
                $this->image_lib->initialize($config);

                if (!$this->image_lib->resize()) {
                    $this->session->set_flashdata('error', $this->image_lib->display_errors());
                    $this->session->set_flashdata('form_data', $_POST);
                    redirect("categories/edit/" . $id);
                }

            } else {
                $photo = "category.png";
            }

            $context_data["image"] = $photo;

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

        
        if ($this->form_validation->run() && isset($response)) { //NO TOQUES

            if (empty($response)) {
                $this->session->set_flashdata('form_data', $_POST);
                $this->session->set_flashdata('error', 'No se pudo editar la categoria, consulte con su admistrador.');
                redirect("categories/edit/" . $id);
            } else {
                if ($response['result'] == 'ok') {
                    $this->session->set_flashdata('message', $response['message']);
                    redirect("categories");
                } else {
                    $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("categories/edit/" . $id);
                }
            }
        } else {   
            
            $biz = array(
                "ruc_number"=> (string)($this->session->userdata('ruc'))
            );   
            $context_data["business_information"] = $biz;
            $urlCategories = "categories/" . $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 . $urlCategories, false, $context);
            $res = json_decode($response, true);
            $categories = (object) $res['data'];      
            $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['categories'] = $categories;
            $this->data['page_title'] = lang('edit_category');
            $bc = array(array('link' => site_url('categories'), 'page' => lang('categories')),array('link' => '#', 'page' => lang('edit_category')));
            $meta = array('page_title' => lang('category').": ". $categories->code, 'bc' => $bc);
            $this->page_construct('categories/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;
        $urlCategories = "categories/" . $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 . $urlCategories, false, $context);
        $res = json_decode($response, true);
        $categories = (object) $res['data'];

        $this->session->set_flashdata('success_message', lang("category_deleted"));
        redirect('categories', 'refresh');
    }

    function import() {
        // if (!$this->Admin) {
        //     $this->session->set_flashdata('error', lang('access_denied'));
        //     redirect('pos');
        // }
        $this->load->helper('security');
        $this->form_validation->set_rules('userfile', lang("upload_file"), 'xss_clean');

        if ($this->form_validation->run() == true) {
            if (DEMO) {
                $this->session->set_flashdata('warning', lang("disabled_in_demo"));
                redirect('pos');
            }

            if (isset($_FILES["userfile"])) {

                $this->load->library('upload');

                $config['upload_path'] = 'uploads/';
                $config['allowed_types'] = 'csv';
                $config['max_size'] = '500';
                $config['overwrite'] = TRUE;

                $this->upload->initialize($config);

                if (!$this->upload->do_upload()) {
                    $error = $this->upload->display_errors();
                    $this->session->set_flashdata('error', $error);
                    redirect("categories/import");
                }


                $csv = $this->upload->file_name;

                $arrResult = array();
                $handle = fopen("uploads/" . $csv, "r");
                if ($handle) {
                    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
                        $arrResult[] = $row;
                    }
                    fclose($handle);
                }
                array_shift($arrResult);

                $keys = array('code', 'name', 'parent');

                $final = array();
                foreach ($arrResult as $key => $value) {
                    $final[] = array_combine($keys, $value);
                }

                if (sizeof($final) > 1001) {
                    $this->session->set_flashdata('error', lang("more_than_allowed"));
                    redirect("categories/import");
                }

                foreach ($final as $csv_pr) {
                    if($this->site->getCategoryByCode($csv_pr['code'])) {
                        $this->session->set_flashdata('error', lang("check_category") . " (" . $csv_pr['code'] . "). " . lang("category_already_exist"));
                        redirect("categories/import");
                    }
                    if(!empty($csv_pr['parent']))
                    {
                        if(! ($category = $this->site->getCategoryByCode($csv_pr['parent']))) {
                            $this->session->set_flashdata('error', lang("check_category") . " (" . $csv_pr['category'] . "). " . lang("category_x_exist"));
                            redirect("products/import");
                        }
                    }

                    $data[] = array('code' => $csv_pr['code'], 'name' => $csv_pr['name'], 'parent_category_id' => !empty($csv_pr['parent']) ? $category->id : '0',);
                }
            }

        }

        if ($this->form_validation->run() == true && $this->categories_model->add_categories($data)) {

            $this->session->set_flashdata('message', lang("categories_added"));
            redirect('categories');

        } else {

            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['page_title'] = lang('import_categories');
            $bc = array(array('link' => site_url('products'), 'page' => lang('products')), array('link' => site_url('categories'), 'page' => lang('categories')), array('link' => '#', 'page' => lang('import_categories')));
            $meta = array('page_title' => lang('import_categories'), 'bc' => $bc);
            $this->page_construct('categories/import', $this->data, $meta);

        }
    }

}
