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

class Customers extends MY_Controller
{
	function __construct()
	{
		parent::__construct();
		if (!$this->loggedIn) {
			redirect('login');
		}
		$this->load->library('form_validation');
		$this->load->model('customers_model');
	}

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

		//Obtener listado de Customers Type

		$customer_type_list = [];
		$get_customers_type = $this->get_customers_type();
		$this->data['list_customer_type'] = $get_customers_type;
		//Final
		$this->page_construct('customers/index', $this->data, $meta);
	}



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

		$columnas = array(
			0 => 'name',
			1 => 'person_type',
			2 => 'document_type_id',
			3 => 'phone',
			4 => 'email',
			5 => 'cf1',
			6 => 'cf2',
			7 => 'customers_type_id',
			8 => '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"];
		$person_type = $_GET["person_type"];
		$document_type = $_GET["document_type"];
		$customer_type = $_GET["customer_type"];


		$urlModels = "customer";
		$values = "?orderby=" . $orderby . "&orderdir=" . $orderdir . "&start=" . $start . "&length=" . $length;
		if ($filtro != "") {
			$values = $values . "&search=" . $filtro;
		}
		$urlModels = $urlModels . $values;


		$business_information = array(
			"ruc_number" => (string) ($this->session->userdata('ruc'))
		);
		$context_data["business_information"] = $business_information;
		$context_data["filters"] = array(
			"person_type" => $person_type,
			"document_type_id" => $document_type,
			"customers_type_id" => $customer_type
		);
		$context_data["tipo_listado"] = 1;
		$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 . $urlModels, false, $context);
		$response = json_decode($response, true);


		if ($response['result'] == 'ok') {

			$contador_total = $response['data']['total'];

			$contador_filtrado = count($response['data']);
			$rows['draw'] = $draw;
			$rows['recordsFiltered'] = $contador_total;

			foreach ($response['data']['list'] as $customer) {

					$name = $customer['name'];
					// $personType = $customer['person_type'];
					if ($customer['person_type'] == "1") {
						$personType = lang('Natural');
					}
					if ($customer['person_type'] == "2") {
						$personType = lang('Juridica');
					}
					// $documentType = $customer['document_type_id'];

					if ($customer['document_type_id'] == "1") {
						$documentType = lang('Documento Nacional de Identidad');
					}
					if ($customer['document_type_id'] == "4") {
						$documentType = lang('Carnet de Extranjeria');
					}
					if ($customer['document_type_id'] == "6") {
						$documentType = lang('RUC');
					}
					if ($customer['document_type_id'] == "7") {
						$documentType = lang('Pasaporte');
					}



					$phone = (empty($customer['phone']) ? "" : "+51 ") . ($customer['phone']);
					$email = $customer['email'];
					$document_number = $customer['cf1'];
					$ruc = $customer['cf2'];
					//
					$data = array(
						"business_information" => array(
							"ruc_number" => $this->session->userdata('ruc')
						),
					);
					$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/" . $customer['customers_type_id'];
					$response = file_get_contents($url, false, $context);
					$res = json_decode($response, true);


					$customerType = $res['data']["customers_type"];



					$editar = "
					<div class = 'col-xs-2'>
						<a href='" . site_url('customers/edit/' . $customer['id']) . "'  title='" . lang("edit_customer") . "' 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/delete/' . $customer['id']) . "' onClick=\"return confirm('" . lang('remove_customer') . "')\" title='" . lang("remove_customer") . "' 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(
						"name" => $name,
						"person_type" => $personType,
						"document_type_id" => $documentType,
						"phone" => $phone,
						"email" => $email,
						"cf1" => $document_number,
						"cf2" => $ruc,
						"customers_type_id" => $customerType,
						// ""=>$ ,
						// ""=>$ ,
						// ""=>$ ,
						// ""=>$ ,
						"action" => $html_action,
					));
					array_push($temporal, $datos);
				
			} //foreach_final

		} else {
			$contador_total = 0;
			$contador_filtrado = 0;
			$rows['draw'] = $draw;
			$rows['recordsFiltered'] = $contador_total;
		}
		$rows['data'] = $temporal;
		echo json_encode($rows);
	}

	function get_customers_byid($id = NULL)
	{
		$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_ventas');

		$urlcustomer = "customer/" . $id;
		$response = file_get_contents($url . $urlcustomer, false, $context);
		$customer = json_decode($response, true);
		if ($customer['result'] == 'ok') {
			$customer = $customer['data'];
		} else {
			$customer = [];
		}

		$this->data['customer_type'] = $this->get_customers_type();

		if ($this->input->is_ajax_request()) {
			echo json_encode($customer);
		}
		return ($customer);
	}

	function add()
	{
		//validando que el campo persona no este vacio
		$this->form_validation->set_rules('person', $this->lang->line("person"), 'required');

		$this->form_validation->set_rules('cf1', $this->lang->line("ccf1"), 'trim|required|numeric');



		//Verificamos si el campo persona es igual a 2 = juridica
		if (!empty($this->input->post('person')) && $this->input->post('person') == 2) {
			//validamos que el campo cf2 no este vacio, que sea numerico y que tenga 11 caracteres
			$this->form_validation->set_rules('cf1', $this->lang->line("ccf1"), 'trim|required|numeric|exact_length[11]', [
				'exact_length' => "Se ha seleccionado persona jurídica. El campo Número Documento debe ser un ruc de 11 dígitos."
			]);
			$this->form_validation->set_rules('direccion', $this->lang->line("address"), 'required');
			$docNumber = "";
			$docType = 6;
		} else if (!empty($this->input->post('person')) && $this->input->post('person') == 1) {
			$this->form_validation->set_rules('document_type', $this->lang->line("document_type"), 'required');
			$this->form_validation->set_rules('cf2', $this->lang->line("ccf2"), 'trim|numeric|exact_length[11]');
			if ($this->input->post('document_type') == 1) { // documento nacional de identidad
				$this->form_validation->set_rules('cf1', $this->lang->line("ccf1"), 'trim|numeric|required|exact_length[8]', [
					'exact_length' => "El campo Número Documento debe ser un DNI de 8 dígitos."
				]);
			} else {
				$this->form_validation->set_rules('cf1', $this->lang->line("ccf1"), 'trim|required|alpha_numeric|max_length[15]');
			}
			$docType = $this->input->post('document_type');
			if ($docType == "") {
				if ($this->input->post('cf2') != "") {
					$docType = 6;
				}
			}
			$docNumber = $this->input->post('cf1');
			if ($docNumber == '') {
				$docNumber = '';
			}
		}

		if ($this->input->post('is_retainer')) {
			$this->form_validation->set_rules('retainer_percentage', $this->lang->line("retainer_percentage"), 'required|greater_than[0]');
		}

		$this->form_validation->set_rules('name', $this->lang->line("name"), 'required');

		$this->form_validation->set_rules('phone', $this->lang->line("phone"), 'integer');
		$this->form_validation->set_message('integer', 'El campo {field} debe contener solo números.');

		$this->form_validation->set_rules('email', $this->lang->line("email_address"), 'valid_email');

		//

		if ($this->form_validation->run() == true) {
			if ($this->session->userdata('retencion') == 1) {
				$is_retainer = ($this->input->post('is_retainer') == true) ? $this->input->post('is_retainer') : 0;
				$retainer_percentage = $this->input->post('is_retainer') ? $this->input->post('retainer_percentage') : null;
			} else {
				$is_retainer = 0;
				$retainer_percentage = null;
			}


			$person_type = trim($this->input->post('person'));
			if ($person_type == 1) {
				$document_number = $this->input->post('cf1');
				$ruc = $this->input->post('cf2');
			} else if ($person_type == 2) {
				$document_number = '';
				$ruc = $this->input->post('cf1');
			}

			$data = array(
				"business_information" => array(
					"ruc_number" => $this->session->userdata('ruc')
				),
				'name' => trim($this->input->post('name')),
				'document_number' => trim($document_number),
				'ruc' => trim($ruc),
				'phone' => trim($this->input->post('phone')),
				'email' => trim($this->input->post('email')),
				'direccion' => trim($this->input->post('direccion')),
				'customers_type_id' => ($this->input->post('customer_type')!=0)?$this->input->post('customer_type'):null,
				'created_by' => $this->session->userdata('user_id'),
				'person_type' => trim($this->input->post('person')),
				'document_type_id' => trim($docType),
				'is_retainer' => $is_retainer,
				'retainer_percentage' => $retainer_percentage,

				'status' => 1
			);


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

			$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);
		}

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

			if (empty($res)) {
				if ($this->input->is_ajax_request()) {
					echo json_encode(array('status' => 'failed', 'msg' => 'No se pudo agregar el cliente.', 'val' => $data['name'], 'data' => $res));

					die();
				}
				$this->session->set_flashdata('form_data', $_POST);
				$this->session->set_flashdata('error', 'No se pudo agregar el cliente.');
				redirect("customers/add");
			} else {
				if ($res['result'] == 'ok') {
					if ($this->input->is_ajax_request()) {
						echo json_encode(array('status' => 'success', 'msg' => $this->lang->line("customer_added"), 'id' => $res['data']['id'], 'val' => $data['name'], 'data' => $res));

						die();
					}
					$this->session->set_flashdata('message', $res['message']);
					redirect("customers");
				} else {
					$dataError = [];
					if (is_array($res['message'])) {
						foreach ($res['message'] as $key => $value) {
							for ($i = 0; $i < count($res['message'][$key]); $i++) {
								array_push($dataError, $res['message'][$key][$i]);
							}
						}
					} else {
						array_push($dataError, $res['message']);
					}
					if ($this->input->is_ajax_request()) {
						echo json_encode(array('status' => 'failed', 'msg' => str_replace(',', '<br/>', implode(',', $dataError)), 'val' => $data['name'], 'data' => $res));

						die();
					}

					$this->session->set_flashdata('error', str_replace(',', '<br/>', implode(',', $dataError)));
					$this->session->set_flashdata('form_data', $_POST);
					redirect("customers/add");
				}
			}
		} 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['customer_type'] = $this->get_customers_type();
			$this->data['document_type'] = $this->site->getAllDocumentType();
			$this->data['page_title'] = lang('new_customer');
			$bc = array(array('link' => site_url('customers'), 'page' => lang('customers')), array('link' => '#', 'page' => lang('new_customer')));
			$meta = array('page_title' => lang('new_customer'), 'bc' => $bc);
			$this->page_construct('customers/add', $this->data, $meta);
		}
	}

	function edit($id = NULL)
	{ // Registro del valor de $id

		if (!empty($this->input->post('person')) && $this->input->post('person') == 2) {
			$this->form_validation->set_rules('cf1', $this->lang->line("ccf1"), 'trim|numeric|exact_length[11]|required');
			$docNumber = "";
			$docType = 6;
		} else if (!empty($this->input->post('person')) && $this->input->post('person') == 1) {
			$this->form_validation->set_rules('document_type', $this->lang->line("document_type"), 'required');
			if ($this->input->post('document_type') == 1) { //documento nacional de identidad
				$this->form_validation->set_rules('cf1', $this->lang->line("ccf1"), 'trim|numeric|exact_length[8]|required');
			} else if ($this->input->post('document_type') == 0) { //docuemento tributario domiciliado sin ruc
				$this->form_validation->set_rules('cf1', $this->lang->line("ccf1"), 'trim|alpha_numeric|max_length[15]|required');
			} else if (($this->input->post('document_type') == 4) || ($this->input->post('document_type') == 7)) { //carnet de estranjeria y pasaporte
				$this->form_validation->set_rules('cf1', $this->lang->line("ccf1"), 'trim|alpha_numeric|max_length[12]|required');
			} else {
				$this->form_validation->set_rules('cf1', $this->lang->line("ccf1"), 'required');
			}
			$this->form_validation->set_rules('cf2', $this->lang->line("ccf2"), 'trim|numeric|exact_length[11]');

			$docType = $this->input->post('document_type');
			$docNumber = $this->input->post('cf1'); //numero de documento
		}

		//*****************************START TRJ143 - DANIEL PADILLA - 20/12/2022************************
		if ($this->input->post('is_retainer')) {
			$this->form_validation->set_rules('retainer_percentage', $this->lang->line("retainer_percentage"), 'required|greater_than[0]');
		}
		//*****************************END TRJ143 - DANIEL PADILLA - 20/12/2022************************

		$this->form_validation->set_rules('name', $this->lang->line("name"), 'required');
		$this->form_validation->set_rules('phone', $this->lang->line("phone"), 'integer');
		$this->form_validation->set_rules('email', $this->lang->line("email_address"), 'valid_email');

		if ($this->form_validation->run() == true) {
			if ($this->session->userdata('retencion') == 1) {
				$is_retainer = ($this->input->post('is_retainer') == true) ? $this->input->post('is_retainer') : 0;
				$retainer_percentage = $this->input->post('is_retainer') ? $this->input->post('retainer_percentage') : null;
			} else {
				$is_retainer = 0;
				$retainer_percentage = null;
			}

			$person_type = trim($this->input->post('person'));
			if ($person_type == 1) {
				$docNumber = $this->input->post('cf1');
				$ruc = $this->input->post('cf2');
			} else if ($person_type == 2) {
				$docNumber = '';
				$ruc = $this->input->post('cf1');
			}

			$data = array(
				"business_information" => array(
					"ruc_number" => $this->session->userdata('ruc')
				),
				'name' => trim($this->input->post('name')),
				'document_number' => trim($docNumber),
				'ruc' => trim($ruc),
				'phone' => trim($this->input->post('phone')),
				'email' => trim($this->input->post('email')),
				'direccion' => trim($this->input->post('direccion')),
				'customers_type_id' => ($this->input->post('customer_type')!=0)?$this->input->post('customer_type'):null,
				'user_id' => 1,
				'updated_by' => $this->session->userdata('user_id'),
				'person_type' => trim($this->input->post('person')),
				'document_type_id' => trim($docType),
				'is_retainer' => $is_retainer,
				'retainer_percentage' => $retainer_percentage,

				// 'status' => 1
			);


			$url = $this->config->item('api_ventas');
			$url = $url . "customer/" . $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);
			$res = json_decode($response, true);
		}



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

			if (empty($res)) {
				if ($this->input->is_ajax_request()) {
					echo json_encode(array('status' => 'failed', 'msg' => 'No se pudo actualizar el cliente.', 'val' => $data['name'], 'data' => $res));

					die();
				}
				$this->session->set_flashdata('form_data', $_POST);
				$this->session->set_flashdata('error', 'No se pudo actualizar el cliente.');
				redirect("customers/edit/$id");
			} else {
				if ($res['result'] == 'ok') {
					if ($this->input->is_ajax_request()) {
						echo json_encode(array('status' => 'success', 'msg' => $this->lang->line("customer_updated"), 'id' => $res['data']['id'], 'val' => $data['name'], 'data' => $res));

						die();
					}
					$this->session->set_flashdata('message', $res['message']);
					redirect("customers");
				} else {
					$dataError = [];
					if (is_array($res['message'])) {
						foreach ($res['message'] as $key => $value) {
							for ($i = 0; $i < count($res['message'][$key]); $i++) {
								array_push($dataError, $res['message'][$key][$i]);
							}
						}
					} else {
						array_push($dataError, $res['message']);
					}
					if ($this->input->is_ajax_request()) {
						echo json_encode(array('status' => 'failed', 'msg' => str_replace(',', '<br/>', implode(',', $dataError)), 'val' => $data['name'], 'data' => $res));

						die();
					}

					$this->session->set_flashdata('error', str_replace(',', '<br/>', implode(',', $dataError)));
					$this->session->set_flashdata('form_data', $_POST);
					redirect("customers/edit/$id");
				}
			}
		} 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->session->set_flashdata('form_data', "");
			$this->data['document_type'] = $this->site->getAllDocumentType();
			$this->data['customer_type'] = $this->get_customers_type();
			$this->data['customer'] = $this->get_customers_byid($id);
			$this->data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
			$this->data['page_title'] = lang('edit_customer');
			$bc = array(array('link' => site_url('customers'), 'page' => lang('customers')), array('link' => '#', 'page' => lang('edit_customer')));
			$meta = array('bc' => $bc);
			$this->page_construct('customers/edit', $this->data, $meta);
		}
	}

	function delete($id = NULL)
	{
		if ($this->input->get('id')) {
			$id = $this->input->get('id', TRUE);
		}
		//obtener el numero el registro a editar
		$data = array(
			"business_information" => array(
				"ruc_number" => $this->session->userdata('ruc')
			)
		);
		$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/" . $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");
		}
	}
	function get_customers_type()
	{
		$urlapi_venta = $this->config->item('api_ventas');
		$url_customer_type = $urlapi_venta . "customer_type";
		//$ruc = $this->session->userdata('ruc');
		$headers = array(
			'Content-Type:application/json',
			'Accept: application/json'
		);
		$payload = array(
			'business_information' => array(
				'ruc_number' => $this->session->userdata('ruc')
			),
		);
		$url = sprintf("%s?%s", $url_customer_type, http_build_query($payload));
		$process = curl_init($url); //your API url
		curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
		$return = curl_exec($process);
		curl_close($process);

		$customer_type = json_decode($return, true);
		return $customer_type["data"]["list"];
	}
}
