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

class Customers_type extends MY_Controller
{

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

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

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


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


	function get_customers_type()
	{		
		$rows = array();
		$temporal = array();
		$columnas = array(
			0 => 'customers_type',
			1 => 'action'
		);
		$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"];
		//DEFINIR URL
		$urlCusType = "customer_type";
		$values = "?orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length;
		//USAR EL BUSCADOR
		if ($filtro != "") {
			$values = $values . "&search=" . $filtro;
		}
		$urlCusType = $urlCusType . $values;
		//CONSUMO DEL SERVICIO
		$rucNumber = array(
			"ruc_number" => (string) ($this->session->userdata('ruc'))
		);
		$context_data["business_information"] = $rucNumber;
		$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_ventas');
		$response = file_get_contents($url . $urlCusType, 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;
			//ITERACION DE LOS VALORES
			foreach ($response['data']['list'] as $tipo_cus) {
				$custo_type = $tipo_cus['customers_type'];

				$editar = "
					<div class = 'col-xs-2'>
						<a href='" . site_url('customers_type/edit/' . $tipo_cus['id']) . "'  title='" . lang("edit_customers_type") . "' class='tip btn btn-warning btn-xs ' >
							<i class='fa fa-edit'></i>
						</a>
					</div>";
				$eliminar = "
					<div class = 'col-xs-2'>
						<a href='" . site_url('customers_type/delete/' . $tipo_cus['id']) . "' onClick=\"return confirm('" . lang('question_remove_customers_type') . "')\" title='" . lang("remove_customers_type") . "' class='tip btn btn-danger btn-xs' >
						<i class='fa fa-trash-o'></i>
						</a>					
					</div>";

				$html_action = "<div class='text-center'>";
				$html_action .= "<div class='btn-group'>";
				$html_action .= $editar;
				$html_action .= $eliminar;
				$html_action .= "</div>";
				$html_action .= "</div>";

				$datos = (array(
					"customers_type" => $custo_type,
					// ""=>$ ,
					// ""=>$ ,
					// ""=>$ ,
					// ""=>$ ,
					"action" => $html_action,
				));	
				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(){
		//VALIDACION DEL VALOR NAME DEL INPUT
		$this->form_validation->set_rules('tipoCustomer', $this->lang->line("customers_type"), 'required|min_length[1]|max_length[80]');
		if ($this->form_validation->run() == true) {
			//CONSUMO DEL SERVICIO
			$data = array(
				"business_information"=>array(
					"ruc_number"=>$this->session->userdata('ruc')
				),
				'customers_type' => $this->input->post('tipoCustomer'),
                'user_id' =>0,
				'created_by' =>$this->session->userdata('user_id')
			);

			$url = $this->config->item('api_ventas');
			$url =$url. "customer_type";

			$headers = array(
				'Content-Type:application/json',
				'Accept: application/json'
			);
			$curl  =curl_init($url);
			curl_setopt($curl, CURLOPT_POST,true);
			curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
			$response = curl_exec($curl);
			$res = json_decode($response,true);

		}
		//SI SE VALIDA LO ANTERIOR
		if ($this->form_validation->run()  && isset($res)) {
			if ($res['result'] == "failed") {
				$this->session->set_flashdata('error', $res['message']);
				$this->session->set_flashdata('form_data', $data);
				redirect("customers_type/add");
			}
			if ($res['result'] == 'ok') {
				$this->session->set_flashdata('form_data',null);
				$this->session->set_flashdata('message', $res['message']);
            redirect("customers_type");
			}
            
		

		} else {
            if($this->input->is_ajax_request()) {
                echo json_encode(array('status' => 'failed', 'msg' => validation_errors())); die();
            }
			$this->data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
			$this->data['form_data'] = $this->session->flashdata('form_data');
    		$this->data['page_title'] = lang('add_customers_type');
    		$bc = array(array('link' => site_url('customers_type'), 'page' => lang('customers_type')), array('link' => '#', 'page' => lang('add_customers_type')));
    		$meta = array('page_title' => lang('new_customers_type'), 'bc' => $bc);
    		$this->page_construct('customers_type/add_edit', $this->data, $meta);

		}
    }

    function edit($id = NULL){
		//VALIDACION DEL VALOR NAME DEL INPUT
        $this->form_validation->set_rules('tipoCustomer', $this->lang->line("customers_type"),'required');
        if ($this->form_validation->run() == true) {
			//CONSUMO DEL SERVICIO
            $data = array(
				"business_information"=>array(
					"ruc_number"=>$this->session->userdata('ruc')
				),
                'customers_type'=> $this->input->post('tipoCustomer'),
                'user_id' =>0,
				'updated_by' =>$this->session->userdata('user_id')
            );

            $url = $this->config->item('api_ventas');
			$url =$url. "customer_type/".$id;
			
			$curl = curl_init();

			curl_setopt_array($curl, array(
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_ENCODING => '',
				CURLOPT_MAXREDIRS => 10,
				CURLOPT_TIMEOUT => 0,
				CURLOPT_FOLLOWLOCATION => true,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST => 'PUT',
				CURLOPT_POSTFIELDS =>json_encode($data),
				CURLOPT_HTTPHEADER => array(
					'Content-Type: application/json'
				),
			));

			$response = curl_exec($curl);

			curl_close($curl);
			//DECODIFICACION DEL JSON
			$res = json_decode($response,true);
        }
		//SI SE VALIDA LO ANTERIOR
        if ($this->form_validation->run()  && isset($res)) {
			if ($res['result'] == "failed") {
				$this->session->set_flashdata('error', $res['message']);
				$this->session->set_flashdata('form_data', $data);
				redirect("customers_type/edit/".$id);
			}
			if($res['result'] == "ok") {
				$this->session->set_flashdata('message', $res['message']);
				$this->session->set_flashdata('form_data', null);
            	redirect("customers_type/");
			}
            
		}else{
			//CONSUMO DEL SERVICIO
            $data = array(
				"business_information"=>array(
					"ruc_number"=>$this->session->userdata('ruc')
				),
                'customers_type'=> $this->input->post('tipoCustomer')
            );
            $context = stream_context_create(array(
				'http' => array(
				'method' => 'GET',
				'header' => "Authorization: application/json\r\n" .
				"Content-Type: application/json\r\n",
				"content"=>json_encode($data)
				)
			));
            $url = $this->config->item('api_ventas');
			$url =$url. "customer_type/".$id;
			$response = file_get_contents($url, false, $context);
			$res = json_decode($response, true);
            $this->data['customers_type'] = $res['data'];
            


            $this->data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
            $this->data['form_data'] = $this->session->flashdata('form_data');
    		$this->data['page_title'] = lang('update_customers_type');
            /**/
    		$bc = array(array('link' => site_url('customers_type'), 'page' => lang('customers_type')), array('link' => '#', 'page' => lang('update')));
    		$meta = array('page_title' => lang('customers_type')." - ".$id, 'bc' => $bc);
            $this->page_construct('customers_type/add_edit', $this->data, $meta);
        }
    }


    function delete($id = NULL)
	{
		if($this->input->get('id')) 
        { 
            $id = $this->input->get('id', TRUE); 
        }
		//obtener el numero del registro a editar
		$data = array(
			"business_information"=>array(
				"ruc_number"=>$this->session->userdata('ruc')
			)
		);
		//CONSUMO DEL SERVICIO
		$context = stream_context_create(array(
			'http' => array(
			'method' => 'DELETE',
			'header' => "Authorization: application/json\r\n" .
			"Content-Type: application/json\r\n",
			"content"=>json_encode($data)
			)
		));
		$url = $this->config->item('api_ventas');
		$url =$url. "customer_type/".$id;
		$response = file_get_contents($url, false, $context);
		$res = json_decode($response, true);

		if ($res['result']== 'ok')
		{
			$this->session->set_flashdata('message', $res['message']);
			redirect("customers_type");
		}
	}
}
