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

class Products extends CI_Controller
{

	function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->load->model('drivers_model');
		$this->load->model('vehicle_model');
		$this->load->model('common');
		$this->load->model('customer_model');
		$this->load->helper(array('form', 'url', 'string'));
		$this->load->library('form_validation');
		$this->load->library('session');
	}

	public function index()
	{
		//$data['driverslist'] = $this->drivers_model->getall_drivers();
		$data['orderlist'] = $this->common->readdatafromcollectionwhereclause("Products");
	
		$this->template->template_render('products_management', $data);
	}
	public function adddrivers()
	{
		$this->template->template_render('drivers_add');
	}
	public function per_kmm()
	{
		$this->template->template_render('per_km');
	}

	public function driverratings()
	{
		$this->template->template_render('driver_ratings');
	}

	public function detail($id)
	{
		$data['productdetail'] = $this->common->readdatadocument("Products",$id);
		// echo "<pre>";
		// print_r($data);
		// echo "</pre>";
		// exit;
		$data['userinfo'] = $this->common->readdatadocument("Users",$data['productdetail']['userId']);
		$data['categories'] = $this->common->readdatadocument("Categories",$data['productdetail']['categoryId']);
		if(isset($data['productdetail']['subcategoryId'])){
		$data['subcategories'] = $this->common->readdatadocument("Subcategories",$data['productdetail']['subcategoryId']);
		}else{
		$data['subcategories']=array();
		}
		
		$review=$this->common->readdatacollection("Products","Reviews",$id);
		$noofreview=0;
		$rating=0;
		if(count($review)>0){
			foreach($review as $r=>$v){
				$noofreview=$noofreview+1;
				$rating=$rating+$v['rating'];

				
			}
		}

		$data['totalreview']=$noofreview;
		$data['totalrating']=$rating/$noofreview;
		
		$data["id"] = $id;
				$this->template->template_render('productdetail', $data);
	}

	public function edit_driver_info($id)
	{
		$this->data['driverdetails'] = $this->drivers_model->get_driverdetails($id);
		$this->data['vehicledetails'] = $this->vehicle_model->get_vehicleByDriver($id);
		$this->data['vehicleId'] = $this->vehicle_model->get_vehicleIdByDriver($id);
		$this->data['driverId'] = $id;
		$this->template->template_render('edit_driver', $this->data);
	}

	public function approveDriver($id)
	{
		$driverdetails = $this->drivers_model->get_driverdetails($id);
		$data["id"] = $id;
		$data["isVerified"] = "pending";
		$data["isApproved"] = TRUE;
		$data["stripeStatus"] = "approved";
		$response = $this->common->updatedatamodel("Users", $data["id"], $data);
		$this->session->set_flashdata('successmessage', 'Driver Approved');	
		// if($driverdetails["stripeStatus"] == "approved"){
		
		// } else {
		// 	$this->session->set_flashdata('warningmessage', 'Driver Stripe Status is not approved yet.');				
		// }
		redirect('drivers');
	}

	public function rejectDriver($id)
	{
		$data["id"] = $id;
		$data["isVerified"] = "notApproved";
		$response = $this->common->updatedatamodel("Users", $data["id"], $data);
		$this->session->set_flashdata('successmessage', 'Driver Rejected');
		redirect('drivers');
	}

	public function suspendDriver($id)
	{
		$data["id"] = $id;
		$data["isVerified"] = "suspended";
		$data["isApproved"] = FALSE;
		$response = $this->common->updatedatamodel("Users", $data["id"], $data);
		$this->session->set_flashdata('successmessage', 'Driver Suspended');
		redirect('drivers');
	}

	public function deleteproduct($id)
	{
		$response = $this->common->deletedatamodel("Products", $id);
		$this->session->set_flashdata('successmessage', 'Products Deleted');
		redirect('products');
	}

	public function Driveraccountinfo()
	{
		$this->template->template_render('driveraccountinformation');
	}



	public function insertdriver()
	{
		$this->form_validation->set_rules('licenseno', 'License Number', 'required|trim|is_unique[vehicles.v_registration_no]');
		$this->form_validation->set_message('is_unique', '%s is already exist');
		$this->form_validation->set_rules('name', 'Name', 'required|trim');
		$this->form_validation->set_rules('mobile', 'Mobile', 'required|trim');
		$this->form_validation->set_rules('address', 'Address', 'required|trim');
		$this->form_validation->set_rules('age', 'Age', 'required|trim');
		$this->form_validation->set_rules('licenseno', 'License Number', 'required|trim');
		$this->form_validation->set_rules('license_expdate', 'License Exp Date', 'required|trim');
		$this->form_validation->set_rules('total_exp', 'Total Experiance', 'required|trim');
		$this->form_validation->set_rules('doj', 'Date of Joining', 'required|trim');
		$testxss = xssclean($_POST);
		// print_r($_POST);
		// exit;

		foreach ($_POST as $key => $val) {
			if (strpos($key, "d_") === 0) {
				$name = substr($key, 2);
				$data["driver"][$name] = $val;
			}
		}

		$data["driver"]['carType']=$this->input->post('v_carType');

		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();

		if ($_FILES['v_proofOfInsurance']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_proofOfInsurance']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_proofOfInsurance']['name'],
				]
			);

			$data["vehicle"]['insuranceUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_proofOfRegistration']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_proofOfRegistration']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_proofOfRegistration']['name'],
				]
			);

			$data["vehicle"]['registrationUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_frontPicture']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_frontPicture']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_frontPicture']['name'],
				]
			);

			$data["vehicle"]['frontCarUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_leftPicture']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_leftPicture']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_leftPicture']['name'],
				]
			);

			$data["vehicle"]['leftCarUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_license']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_license']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_license']['name'],
				]
			);

			$data["vehicle"]['licenseUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_rightPicture']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_rightPicture']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_rightPicture']['name'],
				]
			);

			$data["vehicle"]['rightCarUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_rearPicture']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_rearPicture']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_rearPicture']['name'],
				]
			);

			$data["vehicle"]['rearCarUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_frontInterior']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_frontInterior']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_frontInterior']['name'],
				]
			);

			$data["vehicle"]['frontInCarUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_backInterior']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_backInterior']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_backInterior']['name'],
				]
			);

			$data["vehicle"]['backInCarUrl'] = $uploadedFile->info()['mediaLink'];
		}

		foreach ($_POST as $key => $val) {
			if (strpos($key, "v_") === 0) {
				$name = substr($key, 2);
				$data["vehicle"][$name] = $val;
			}
		}

		$data["driver"]["userRole"] = "driver";

		$response = $this->drivers_model->add_drivers($data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'New driver added successfully..');
			redirect('drivers');
		} else {
			$errormsg = 'Error! User Already Exists.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect('drivers/adddrivers');
		}
	}
	public function editdriver()
	{
		$d_id = $this->uri->segment(3);
		$data['driverdetails'] = $this->drivers_model->get_driverdetails($d_id);
		$this->template->template_render('edit_driver', $data);
	}


	public function updateprice($id)
	{
	$data['displayPrice']=(double)$this->input->post('displayPrice');
	$flag=$this->common->updatedatamodel("Products",$id,$data);
	if($flag){
		$this->session->set_flashdata('successmessage', 'Price has been updated successfully..');
		redirect('products/detail/'.$id);		
	}else{
		$this->session->set_flashdata('warningmessage', 'Usome thing error Please try later');
		redirect('products/detail/'.$id);
	}

	}
	//updatestatus
	public function updatestatus($id,$flag)
	{
		if($flag=="approved"){
			$data['isVerified']=true;
		}else{
			$data['isVerified']=false;
		}
	
	$flag=$this->common->updatedatamodel("Products",$id,$data);
	if($flag){
		$this->session->set_flashdata('successmessage', 'Price has been updated successfully..');
		redirect('products/detail/'.$id);		
	}else{
		$this->session->set_flashdata('warningmessage', 'Usome thing error Please try later');
		redirect('products/detail/'.$id);
	}

	}
}
