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

class Payment_methods extends MY_Controller
{

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

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

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

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

    function get_payment_methods() {

        $columnas = array(
            0 => 'id',
            1 => 'code',
            2 => 'description',
            3 => 'edit',
            4 => 'delete'
        );

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

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

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

        $context_data["business_information"] = $biz;

        $urlDoc = "payment_methods";
                            
        $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_general');
        $response = file_get_contents($url . $urlDoc, false, $context);
        $response = json_decode($response, true);

        $payment_methods = $response['data'];

        $contador_total = count($payment_methods);
        $contador_filtrado = count($payment_methods);

        if ($filtro != "") {
            $values = "?search=" . $filtro . "&orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length;
            $urlDoc = "payment_methods" . $values;
                                
            $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_general');
            $response = file_get_contents($url . $urlDoc, false, $context);
            $response = json_decode($response, true);
            $payment_methods = $response['data'];
        
            $contador_filtrado = count($payment_methods);
        } else {
            $values = "?orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length;
            $urlDoc = "payment_methods" . $values;
                                
            $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_general');
            $response = file_get_contents($url . $urlDoc, false, $context);
            $response = json_decode($response, true);
            $payment_methods = $response['data'];
        }

        $rows['draw'] = $draw;

        $rows['recordsTotal'] = $contador_total;
        $rows['recordsFiltered'] = $contador_filtrado;

        foreach ($payment_methods as $item) {
            $id = $item['id'];
            $code = $item['code'];
            $description = $item['description'];

            $edit = '<span class="btn"><a href="' . site_url('payment_methods/edit/' . $id) . '" title="' . lang("edit_payment_methods") . '"><i class="fa fa-edit"></i></a></span>';
            $delete = '<span class="btn"><a href="' . site_url('payment_methods/delete/' . $id) . '" onClick="return confirm(&#39;' . lang("delete_payment_methods") . '&#39;)" title="' . lang("delete") . '"><i class="fa fa-trash-o"></i></a></span>';

            $datos = (array('id' => $id, 'code' => $code, 'description' => $description, 'edit' => $edit, 'delete' => $delete));
            array_push($temporal,$datos);
        }

        $rows['listados'] = $temporal;

        echo json_encode($rows);
    }

    function add() {        
        $response_api = "";
        $value_type = (string)$this->input->post('payment_methods_type');
        $value_days = (string)$this->input->post('payment_methods_days');
        
        $this->form_validation->set_rules('payment_methods_code', lang("payment_methods_code"), 'required');
        $this->form_validation->set_rules('payment_methods_name', lang("payment_methods_name"), 'required');
        $this->form_validation->set_rules('payment_methods_type', lang("payment_methods_type"), 'required');

        if( $value_type != "1" ){ //significa que es contado
            $this->form_validation->set_rules('payment_methods_days', lang("payment_methods_days"), 'required');
        }

        if ($this->form_validation->run() == true) {
            $context_data = array(
                'code' => (string)$this->input->post('payment_methods_code'),
                'description' => (string)$this->input->post('payment_methods_name'),
                'type' => $value_type=="" ? 0 : $value_type,
                'days' => $value_days=="" ? 0 : $value_days
            );

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

            $context_data["business_information"] = $biz;
            
            $urlDoc = "payment_methods";
                                
            $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_general');
            $response = file_get_contents($url . $urlDoc, false, $context);
            $response = json_decode($response, true);

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

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

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

    function edit($id = NULL) {
        $response_api = "";
        $value_type = (string)$this->input->post('payment_methods_type');
        $value_days = (string)$this->input->post('payment_methods_days');

        // 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('payment_methods_code', lang("payment_methods_code"), 'required');
        $this->form_validation->set_rules('payment_methods_name', lang("payment_methods_name"), 'required');
        $this->form_validation->set_rules('payment_methods_type', lang("payment_methods_type"), 'required');

        if( $value_type != "1" ){ //significa que es contado
            $this->form_validation->set_rules('payment_methods_days', lang("payment_methods_days"), 'required');
        }

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

        $context_data["business_information"] = $biz;

        $urlDoc = "payment_methods/" . $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_general');
        $response = file_get_contents($url . $urlDoc, false, $context);
        $res = json_decode($response, true);
        $payment_method = (object) $res['data'];

        if ($this->form_validation->run() == true) {
            $context_data = array(
                'code' => (string)$this->input->post('payment_methods_code'),
                'description' => (string)$this->input->post('payment_methods_name'),
                'type' => $value_type=="" ? 0 : $value_type,
                'days' => $value_days=="" ? 0 : $value_days
            );

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

            $context_data["business_information"] = $biz;

            $urlDoc = "payment_methods/" . $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_general');
            $response = file_get_contents($url . $urlDoc, false, $context);
            $response = json_decode($response, true);

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

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

        if ($this->form_validation->run() == true && $response_api == "ok") {
            $this->session->set_flashdata('message', lang("payment_methods_updated"));
            redirect("payment_methods");
        } else {
            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['payment_method'] = $payment_method;
            $this->data['customers'] = $this->site->getAllCustomers();
            $this->data['page_title'] = lang('edit_payment_methods');
            $bc = array(array('link' => site_url('payment_methods'), 'page' => lang('payment_methods')),array('link' => '#', 'page' => lang('edit_payment_methods')));
            $meta = array('page_title' => lang('edit_payment_methods'), 'bc' => $bc);
            $this->page_construct('payment_methods/edit', $this->data, $meta);
        }
    }

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

        if(DEMO) {
            $this->session->set_flashdata('error', lang('disabled_in_demo'));
            redirect(isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : 'welcome');
        }
        // 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;

        $urlDoc = "payment_methods/" . $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_general');
        $response = file_get_contents($url . $urlDoc, false, $context);
        $res = json_decode($response, true);
        $payment_method = (object) $res['data'];
        
        //if ($this->Warehouses_model->deleteWarehouse($id)) {
            $this->session->set_flashdata('success_message', lang("payment_methods_deleted"));
            redirect('payment_methods', 'refresh');
        //}
    }
}
