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

class Traders extends MY_Controller
{

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

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

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

    function index()
    {

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

    function get_traders()
    {
		$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. "traders";
		$response = file_get_contents($url, false, $context);
		$res = json_decode($response, true);
		$traders =[];
		if($res['result'] == 'ok'){
			foreach($res['data']['list'] as $trader){
				$traderCode = $trader['cod_vend'];
				$documentNumber = $trader['document'];
				$nameComplete = $trader['name']. " ". $trader['last_name_1']." ".$trader['last_name_2'];
				// tipo de genero
				if($trader['gender'] == "M"){
					$gender = lang('male');
				}
				if($trader['gender'] == "F"){
					$gender = lang('female');
				}
				if($trader['gender'] == "O"){
					$gender = lang('other');
				}
				// informacion de numeros de contacto
				if($trader['movil'] != "" && $trader['movil_2'] != ""){
					$phone = $trader['movil'] ." / ".$trader['movil_2'];
				}else if($trader['movil'] != ""){
					$phone = $trader['movil'];
				}else if ($trader['movil_2'] != ""){
					$phone = $trader['movil_2'];
				}
				$email =$trader['email'];
				$editar = "
					<div class = 'col-xs-2'>
						<a href='" . site_url('traders/edit/'.$trader['id']) . "'  title='" . lang("edit_trader") . "' 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('traders/delete/'.$trader['id']) . "' onClick=\"return confirm('" . lang('remove_trader') . "')\" title='" . lang("remove_trader") . "' 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>";

				$traderItem =array(
					"traderCode"=>$traderCode ,
					"documentNumber"=>$documentNumber ,
					"names"=>$nameComplete ,
					"phone"=>$phone ,
					"email"=>$email ,
					"gender"=>$gender ,
					// ""=>$ ,
					// ""=>$ ,
					// ""=>$ ,
					// ""=>$ ,
					"action"=>$html_action ,
				);
				array_push($traders,$traderItem);
			}
		}
		
		
		$results = array(
			"sEcho" => 1,
			"iTotalRecords" => $res['data']['total'],
			"iTotalDisplayRecords" => $res['data']['total'],
			"aaData"=>$traders);
			//log_message('error',json_encode($results));
			echo json_encode($results);

    }

	function add()
	{
		$this->form_validation->set_rules('traderCode', $this->lang->line("trader_code"), 'required|max_length[10]|alpha_numeric');
		$this->form_validation->set_rules('documentType', $this->lang->line("document_type"), 'required');
		$this->form_validation->set_rules('documentNumber', $this->lang->line("document_number"), 'trim|required|alpha_numeric|max_length[15]');
		$this->form_validation->set_rules('name', $this->lang->line("name"), 'required');
		$this->form_validation->set_rules('fathersLastName', $this->lang->line("fathers_lastname"), 'required');
		$this->form_validation->set_rules('MotherLastName', $this->lang->line("mothers_lastname"), 'required');
		$this->form_validation->set_rules('birthDate', $this->lang->line("birth_date"), 'required');
		$this->form_validation->set_rules('gender', $this->lang->line("gender"), 'required');
		$this->form_validation->set_rules('phone1', $this->lang->line("phone")." 1", 'numeric');
		$this->form_validation->set_rules('phone2', $this->lang->line("phone")." 2", 'numeric|differs[phone1]');
		$this->form_validation->set_rules('email', $this->lang->line("email_address"), 'valid_email');
		if ($this->form_validation->run() == true) {
			$data = array(
				"business_information"=>array(
					"ruc_number"=>$this->session->userdata('ruc')
				),
				'cod_vend' => $this->input->post('traderCode'),
				'type_document' => $this->input->post('documentType'),
				'document' => $this->input->post('documentNumber'),
				'name' => $this->input->post('name'),
				'last_name_1' => $this->input->post('fathersLastName'),
				'last_name_2' => $this->input->post('MotherLastName'),
				'birth_date' => $this->input->post('birthDate'),
				'gender' => $this->input->post('gender'),
				'address' => $this->input->post('address'),
				'ubigeo' => $this->input->post('district'),
				'movil' => $this->input->post('phone1'),
				'movil_2' => $this->input->post('phone2'),
				'email' => $this->input->post('email'),
				'type_commission' => "",
				'valor_commission' =>0,
				'observation' => "",//$this->input->post('observation'),
				'image' =>"",// $this->input->post('email'),
				'user_id' =>0,// $this->input->post('email'),
				'created_by' =>$this->session->userdata('user_id')// $this->input->post('email'),
			);

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

			$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)) {
			if ($res['result'] == "failed") {
				$this->session->set_flashdata('error', $res['message']);
				redirect("traders/add");
			}
			if ($res['result'] == 'ok') {
				$this->session->set_flashdata('message', $res['message']);
            redirect("traders");
			}
            
		

		} else {
			$context = stream_context_create(array(
				'http' => array(
				'method' => 'GET',
				'header' => "Authorization: application/json\r\n" .
				"Content-Type: application/json\r\n"
				)
			));
									
			$urlDoc = "public/api/v1/catalogo06/tipoDocumento";
			$url_NC = $this->config->item('ws_general');
			$response = file_get_contents($url_NC . $urlDoc, false, $context);
			$res = json_decode($response, true);

			$document_type =$res;
			// obtenemos Los departamentos
			$endPoint = "ubigeo/departamentos";
			$url = $this->config->item('api_general').$endPoint;
			//log_message('error',$url);
			$response = file_get_contents($url, false, $context);
			$res = json_decode($response);
			//log_message('error',json_encode($res));
			
			$i = 0;
			foreach($res->data as $item){
				$departamentList[$i]['id']=$item->codDepa;
				$departamentList[$i]['description']=$item->departamento;
				$i++;
			}
			
			$this->data['departamentList']= $departamentList;
			$this->data['documents_type'] = $document_type;

            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['page_title'] = lang('add_trader');
    		$bc = array(array('link' => site_url('traders'), 'page' => lang('traders')), array('link' => '#', 'page' => lang('add_trader')));
    		$meta = array('page_title' => lang('add_trader'), 'bc' => $bc);
    		$this->page_construct('traders/form', $this->data, $meta);

		}
	}

	function edit($id = NULL)
	{
		$this->form_validation->set_rules('traderCode', $this->lang->line("trader_code"), 'required|max_length[10]|alpha_numeric');
		$this->form_validation->set_rules('documentType', $this->lang->line("document_type"), 'required');
		$this->form_validation->set_rules('documentNumber', $this->lang->line("document_number"), 'trim|required|alpha_numeric|max_length[15]');
		$this->form_validation->set_rules('name', $this->lang->line("name"), 'required');
		$this->form_validation->set_rules('fathersLastName', $this->lang->line("fathers_lastname"), 'required');
		$this->form_validation->set_rules('MotherLastName', $this->lang->line("mothers_lastname"), 'required');
		$this->form_validation->set_rules('birthDate', $this->lang->line("birth_date"), 'required');
		$this->form_validation->set_rules('gender', $this->lang->line("gender"), 'required');
		$this->form_validation->set_rules('phone1', $this->lang->line("phone")." 1", 'numeric');
		$this->form_validation->set_rules('phone2', $this->lang->line("phone")." 2", 'numeric|differs[phone1]');
		$this->form_validation->set_rules('email', $this->lang->line("email_address"), 'valid_email');
		if ($this->form_validation->run() == true) {
			$data = array(
				"business_information"=>array(
					"ruc_number"=>$this->session->userdata('ruc')
				),
				'cod_vend' => $this->input->post('traderCode'),
				'type_document' => $this->input->post('documentType'),
				'document' => $this->input->post('documentNumber'),
				'name' => $this->input->post('name'),
				'last_name_1' => $this->input->post('fathersLastName'),
				'last_name_2' => $this->input->post('MotherLastName'),
				'birth_date' => $this->input->post('birthDate'),
				'gender' => $this->input->post('gender'),
				'address' => $this->input->post('address'),
				'ubigeo' => $this->input->post('district'),
				'movil' => $this->input->post('phone1'),
				'movil_2' => $this->input->post('phone2'),
				'email' => $this->input->post('email'),
				'type_commission' => "",
				'valor_commission' =>0,
				'observation' => "prueba",//$this->input->post('observation'),
				'image' =>"",// $this->input->post('email'),
				'user_id' =>1,// $this->input->post('email'),
				'updated_by' =>$this->session->userdata('user_id')// $this->input->post('email'),
			);
				
			$url = $this->config->item('api_ventas');
			$url =$url. "traders/".$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);
			//log_message('error',json_encode($res));
		}
		
		if ( $this->form_validation->run()  && isset($res)) {
			if ($res['result'] == "failed") {
				$this->session->set_flashdata('error', $res['message']);
				redirect("traders/edit/".$id);
			}
			if($res['result'] == "ok") {
				$this->session->set_flashdata('message', $this->lang->line("trader_added"));
            	redirect("traders");
			}

		} else {
			$context = stream_context_create(array(
				'http' => array(
				'method' => 'GET',
				'header' => "Authorization: application/json\r\n" .
				"Content-Type: application/json\r\n"
				)
			));
			$urlDoc = "public/api/v1/catalogo06/tipoDocumento";
			$url_NC = $this->config->item('ws_general');
			$response = file_get_contents($url_NC . $urlDoc, false, $context);
			$res = json_decode($response, true);

			$document_type =$res;
			// obtenemos Los departamentos
			$endPoint = "ubigeo/departamentos";
			$url = $this->config->item('api_general').$endPoint;
			$response = file_get_contents($url, false, $context);
			$res = json_decode($response);
			//log_message('error',$res);
			$i = 0;
			foreach($res->data as $item){
				$departamentList[$i]['id']=$item->codDepa;
				$departamentList[$i]['description']=$item->departamento;
				$i++;
			}
			$this->data['departamentList']= $departamentList;
			$this->data['documents_type'] = $document_type;

			//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' => '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. "traders/".$id;
			$response = file_get_contents($url, false, $context);
			$res = json_decode($response, true);
			//log_message('error',json_encode($res['data']));
			$this->data['trader'] = $res['data'];
			if($res['data']['ubigeo'] != 0 && $res['data']['ubigeo']  != ""){
				//log_message('error','entrando');
				$this->data['trader']['codDepa'] = substr( $res['data']['ubigeo'], 0, 2 );
				$this->data['trader']['codProv'] = substr( $res['data']['ubigeo'], 0, 4 );
			}
			$this->data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
    		$this->data['page_title'] = lang('edit_trades');
    		$bc = array(array('link' => site_url('traders'), 'page' => lang('traders')), array('link' => '#', 'page' => lang('edit_trader')));
    		$meta = array('page_title' => lang('edit_trader'), 'bc' => $bc);
    		$this->page_construct('traders/form', $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. "traders/".$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("traders");
		}

	}
	function search_province($depa){
		$dpr = $depa;
		$postData["codDepartamento"] = $dpr;
		$context = stream_context_create(array(
			'http' => array(
			'method' => 'GET',
			'header' => "Authorization: application/json\r\n" .
			"Content-Type: application/json\r\n",
			'content' => json_encode($postData)
			)
		));
		$endPoint = "ubigeo/provincias";
		$url = $this->config->item('api_general').$endPoint;
		$response = file_get_contents($url, false, $context);
		echo $response;
	}
	function search_District($provincia, $depa){
		$codProv = $provincia;
		$postData["codProvincia"] = $codProv;
		$context = stream_context_create(array(
			'http' => array(
			'method' => 'GET',
			'header' => "Authorization: application/json\r\n" .
			"Content-Type: application/json\r\n",
			'content' => json_encode($postData)
			)
		));
		$endpoint = "ubigeo/distritos";
		$url = $this->config->item('api_general').$endpoint;
		$response = file_get_contents($url, false, $context);
		echo $response;
	}


}
