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

class Customer extends CI_Controller
{

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

	public function getDetail($id='2BtLSx35cxZah9w6EMGumhxHTmX2'){
		
			$data['user'] = $this->common->readdatadocument("Users",$id);
				// echo "<pre>";
				// print_r($data);
				// echo "</pre>";
				$this->load->view('vehicle_view',$data);

	}	

	public function index()
	{
		if ($this->input->get('month') && $this->input->get('year')) {
			$month = $this->input->get('month');
			$year = $this->input->get('year');
			$data['selectmonth']=$month;
			$data['selectyear']=$year;
		} else {
			// Get current month and year if not provided
			$month = date('m'); 
			$year = date('Y'); 
			$data['selectmonth']=$month;
			$data['selectyear']=$year;
		}
		
		// Create start date (First day of the month)
		$startdate = "$year-$month-01";
		
		// Create end date (Today's date if current month, else last day of the month)
		if ($month == date('m') && $year == date('Y')) {
			$enddate = date('Y-m-d'); // Current date
		} else {
			$enddate = date("Y-m-t", strtotime($startdate)); // Last day of the selected month
		}
		
		$data['startdate']=$startdate;
		$data['enddate']=$enddate;
		$j1=strtotime($startdate)*1000;
		$j2=strtotime($enddate)*1000;
		$data['customerlist']=$this->common->readdatafromcollectionbetween2where("Users","userDate",">=",$j1,"userDate","<=",$j2);


// 		echo "<pre>";
// print_r($data);
// echo "</pre>";
// exit;



// 		$data['customerlist'] = $this->customer_model->getall_customer();
	//	$data['reminderlist'] = $this->common->readdatafromcollectionwhereclause("Reminders");
		
		
		$this->template->template_render('customer_management', $data);
	}
	public function lettscusyomer()
	{
		if ($this->input->get('month') && $this->input->get('year')) {
    $month = $this->input->get('month');
    $year = $this->input->get('year');
	$data['selectmonth']=$month;
	$data['selectyear']=$year;
} else {
    // Get current month and year if not provided
    $month = date('m'); 
    $year = date('Y'); 
	$data['selectmonth']=$month;
	$data['selectyear']=$year;
}

// Create start date (First day of the month)
$startdate = "$year-$month-01";

// Create end date (Today's date if current month, else last day of the month)
if ($month == date('m') && $year == date('Y')) {
    $enddate = date('Y-m-d'); // Current date
} else {
    $enddate = date("Y-m-t", strtotime($startdate)); // Last day of the selected month
}

$data['startdate']=$startdate;
$data['enddate']=$enddate;

	
	$url="https://us-central1-letts-of-london.cloudfunctions.net/widgets/getuserlistupdated";
	if($startdate !="" && $enddate !=""){
		$url="https://us-central1-letts-of-london.cloudfunctions.net/widgets/getuserlistupdated?startDate=".$startdate."&endDate=".$enddate;
	}	

		$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 => 'GET',
	
	));
	
	$response = curl_exec($curl);
	
	curl_close($curl);
	$res=json_decode($response,true);
		$data['customerlist'] = $res;
	/*
		$curl = curl_init();
	
		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'https://us-central1-letts-of-london.cloudfunctions.net/widgets/getreminderlist',
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => '',
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 0,
		  CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => 'GET',
		
		));
		
		$response = curl_exec($curl);
		
		curl_close($curl);
		$res=json_decode($response,true);
	
		$data['reminderlist'] = $res;
		*/
		$data['reminderlist']=array();
		$this->template->template_render('customer_managementnew', $data);
	}
	public function makecsv(){		
	
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://us-central1-filofax-96375.cloudfunctions.net/widgets/getuserlist',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',

));

$response = curl_exec($curl);

curl_close($curl);
$res=json_decode($response,true);
$curl = curl_init();
curl_setopt_array($curl, array(
		  CURLOPT_URL => 'https://us-central1-filofax-96375.cloudfunctions.net/widgets/getreminderlist',
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => '',
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 0,
		  CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => 'GET',
		
		));
		$response = curl_exec($curl);		
		curl_close($curl);
		$reminderlist=json_decode($response,true);

// Set headers to force file download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=products.csv');

// Open output stream
$output = fopen('php://output', 'w');

// Add CSV header
fputcsv($output, ['Full Name', 'UserName','Phone', 'Total Reminder','Archived Reminder', 'Email', 'Country', 'Login']);

// Add data rows
foreach ($res as $customerlists) {
	$totalreminder=0;
	$archiver=0;
	if(isset($customerlists['id'])){
		foreach($reminderlist as $r){
			if($r !=""){
			if(isset($r['userId'])){
				
				 
				if($customerlists['id']== $r['userId']){
					$totalreminder=$totalreminder+1;
			   
					if(isset($r['isArchive'])){
						if($r['isArchive']==true){
						$archiver=$archiver+1;
						} 
					}						
				}
					
			}
				
		  }
	}
}
    fputcsv($output, [
        output($customerlists['firstName']." ".$customerlists['lastName']),
        output($customerlists['userName']),
        output($customerlists['phoneNumber']),
		$totalreminder,
		$archiver,	
        output($customerlists['email']),
        output($customerlists['country']),
        output($customerlists['deviceType'])
    ]);
}

// Close the output stream
fclose($output);


	}
	public function makenewcsv() {		

		// Your API calls
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL => 'https://us-central1-filofax-96375.cloudfunctions.net/widgets/getuserlist',
			CURLOPT_RETURNTRANSFER => true,
		));
		$response = curl_exec($curl);
		curl_close($curl);
		$res = json_decode($response, true);
	
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL => 'https://us-central1-filofax-96375.cloudfunctions.net/widgets/getreminderlist',
			CURLOPT_RETURNTRANSFER => true,
		));
		$response = curl_exec($curl);		
		curl_close($curl);
		$reminderlist = json_decode($response, true);
	
		// File path to temporarily store CSV
		$fileName = 'user_report_' . time() . '.csv';
		$filePath = "uploads/".$fileName;
	
		// Open file stream to save the CSV
		$output = fopen($filePath, 'w');
	
		// Add CSV header
		fputcsv($output, ['Full Name', 'UserName','Phone', 'Total Reminder','Archived Reminder', 'Email', 'Country', 'Login']);
	
		// Add data rows
		foreach ($res as $customerlists) {
			$totalreminder = 0;
			$archiver = 0;
	
			if(isset($customerlists['id'])) {
				foreach($reminderlist as $r) {
					if ($r != "") {
						if (isset($r['userId']) && $customerlists['id'] == $r['userId']) {
							$totalreminder++;
							if (isset($r['isArchive']) && $r['isArchive'] == true) {
								$archiver++;
							}
						}
					}
				}
			}
	
			fputcsv($output, [
				htmlspecialchars($customerlists['firstName'] . " " . $customerlists['lastName']),
				htmlspecialchars($customerlists['userName']),
				htmlspecialchars($customerlists['phoneNumber']),
				$totalreminder,
				$archiver,	
				htmlspecialchars($customerlists['email']),
				htmlspecialchars($customerlists['country']),
				htmlspecialchars($customerlists['deviceType'])
			]);
		}
	
		fclose($output);
	
		// Return file URL
		echo json_encode([
			'status' => 'success',
			'file_url' => base_url()."uploads/".$fileName
		]);
		exit();
	}
	

	public function filofaxcusyomer()
	{
		/*
	if($this->input->get('month')){
		$data=$this->input->get();
		echo "<pre>";
		print_r($data);
		$month=$this->input->get('month');
		$year=$this->input->get('year');
		$start_date = "$year-$month-01";

		// Create end date (Last day of the month)
		$end_date = date("Y-m-t", strtotime($start_date));
		echo "Start Date: " . $start_date . "<br>";
		echo "End Date: " . $end_date . "<br>";

		echo "</pre>";
		exit;
	}	
*/
if ($this->input->get('month') && $this->input->get('year')) {
    $month = $this->input->get('month');
    $year = $this->input->get('year');
	$data['selectmonth']=$month;
	$data['selectyear']=$year;
} else {
    // Get current month and year if not provided
    $month = date('m'); 
    $year = date('Y'); 
	$data['selectmonth']=$month;
	$data['selectyear']=$year;
}

// Create start date (First day of the month)
$startdate = "$year-$month-01";

// Create end date (Today's date if current month, else last day of the month)
if ($month == date('m') && $year == date('Y')) {
    $enddate = date('Y-m-d'); // Current date
} else {
    $enddate = date("Y-m-t", strtotime($startdate)); // Last day of the selected month
}

$data['startdate']=$startdate;
$data['enddate']=$enddate;


/*
	$startdate=$this->input->get('startDate');
	if($startdate !=""){
		$data['startdate']=$start_date;
	}else{
		$data['startdate']=date("Y-m-d");
	}	
	$enddate=$this->input->get('endDate');
	if($enddate !=""){
		$data['enddate']=$enddate;
	}else{
		$data['enddate']='';
	}
		*/
	$url="https://us-central1-filofax-96375.cloudfunctions.net/widgets/getuserlistupdated";
	if($startdate !="" && $enddate !=""){
		$url="https://us-central1-filofax-96375.cloudfunctions.net/widgets/getuserlistupdated?startDate=".$startdate."&endDate=".$enddate;
	}	

			
		$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 => 'GET',
	
	));
	
	$response = curl_exec($curl);
	
	curl_close($curl);
	$res=json_decode($response,true);
///	$this->session->set_userdata('user_list_data', $res);
	

	
		$data['customerlist'] = $res;
	
	//$data['customerlist']=array();
		// echo "<pre>";
		// print_r($data);
		// echo "</pre>";
		// exit;
	
/*
		$curl = curl_init();
	
		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'https://us-central1-filofax-96375.cloudfunctions.net/widgets/getreminderlist',
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => '',
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 0,
		  CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => 'GET',
		
		));
		
		$response = curl_exec($curl);
		
		curl_close($curl);
		$res=json_decode($response,true);
	
		$data['reminderlist']=$res;
		*/

$data['reminderlist']=array();
		
		
		$this->template->template_render('customer_managementnew1', $data);
	}
	public function lettssuspendCustomers()
	{
		$id = $this->uri->segment(3);
		$curl = curl_init();
		
		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'https://us-central1-letts-of-london.cloudfunctions.net/widgets/changeusers/'.$id,
		  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 =>'{
			"isActive":false
		   
		}'

		));
		
		$response = curl_exec($curl);
		
		curl_close($curl);
	
		$this->session->set_flashdata('successmessage', 'User Suspended');
		redirect(base_url().'customer/lettscusyomer');
	}
	public function lettsunSuspendCustomer()
	{
		$id = $this->uri->segment(3);
		$curl = curl_init();
		
		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'https://us-central1-letts-of-london.cloudfunctions.net/widgets/changeusers/'.$id,
		  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 =>'{
			"isActive":true
		   
		}'

		));
		
		$response = curl_exec($curl);
		
		curl_close($curl);
		$this->session->set_flashdata('successmessage', 'User Activated');
		redirect(base_url().'customer/lettscusyomer');
	}
	


	public function lettdeleteCustomer()
	{
		$id = $this->uri->segment(3);
		$curl = curl_init();
		curl_setopt_array($curl, array(
		CURLOPT_URL => 'https://us-central1-letts-of-london.cloudfunctions.net/widgets/deleteusers/'.$id,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => '',
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 0,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => 'DELETE',
		));
		$response = curl_exec($curl);
		curl_close($curl);

		$this->session->set_flashdata('successmessage', 'Customer Deleted Successfully');
		redirect(base_url().'customer/lettscusyomer');
	}

	public function filosuspendCustomers()
	{
		$id = $this->uri->segment(3);
		$curl = curl_init();
		
		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'https://us-central1-filofax-96375.cloudfunctions.net/widgets/changeusers/'.$id,
		  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 =>'{
			"isActive":false
		   
		}'

		));
		
		$response = curl_exec($curl);
		
		curl_close($curl);
	
		$this->session->set_flashdata('successmessage', 'User Suspended');
		redirect(base_url().'customer/filofaxcusyomer');
	}
	public function filounSuspendCustomer()
	{
		$id = $this->uri->segment(3);
		$curl = curl_init();
		
		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'https://us-central1-filofax-96375.cloudfunctions.net/widgets/changeusers/'.$id,
		  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 =>'{
			"isActive":true
		   
		}'

		));
		
		$response = curl_exec($curl);
		
		curl_close($curl);
		$this->session->set_flashdata('successmessage', 'User Activated');
		redirect(base_url().'customer/filofaxcusyomer');
	}
	


	public function suspendCustomer()
	{
		$id = $this->uri->segment(3);
		$data["isActive"] = false;
		$this->common->updatedatamodel("Users", $id, $data);
		$this->session->set_flashdata('successmessage', 'User Suspended');
		redirect(base_url().'customer');
	}

	public function unSuspendCustomer()
	{
		$id = $this->uri->segment(3);
		
		$data["isActive"] = true;
		$this->common->updatedatamodel("Users", $id, $data);
		$this->session->set_flashdata('successmessage', 'User Activated');
		redirect(base_url().'customer');
	}


	public function adminvarify()
	{
		$id = $this->uri->segment(3);
		
		$data["isAdminVerify"] = true;
		$this->common->updatedatamodel("Users", $id, $data);
		$this->session->set_flashdata('successmessage', 'User Activated');
		redirect(base_url().'customer');
	}

	public function filodeleteCustomer()
	{
		$id = $this->uri->segment(3);
		$curl = curl_init();
		curl_setopt_array($curl, array(
		CURLOPT_URL => 'https://us-central1-filofax-96375.cloudfunctions.net/widgets/deleteusers/'.$id,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => '',
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 0,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => 'DELETE',
		));
		$response = curl_exec($curl);
		curl_close($curl);

		$this->session->set_flashdata('successmessage', 'Customer Deleted Successfully');
		redirect(base_url().'customer/filofaxcusyomer');
	}

	public function deleteCustomer()
	{
		$id = $this->uri->segment(3);
		
		$response = $this->customer_model->delete_customer($id);
		if (!$response) {
			$this->session->set_flashdata('warningmessage', 'Something went wrong while deleting customer.');
			redirect(base_url().'customer');
		}
		$response = $this->common->deletedatamodel("Users", $id);
		$this->session->set_flashdata('successmessage', 'Customer Deleted Successfully');
		redirect(base_url().'customer');
	}

	public function addcustomer()
	{
		$this->template->template_render('customer_add');
	}
	//editcustomer
	public function editcustomers($id)
	{


		$data['id'] = $id;

		$data["customerdetails"] = $this->common->readdatadocument("Users", $id);

		$this->template->template_render('editcustomer', $data);
	}
	public function userreset()
	{
		$this->template->template_render('user_reset_credentials');
	}

	public function insertcustomer()
	{
		$data = $this->input->post();
		$data["userRole"] = "user";
		$data["city"] = NULL;
		$data["state"] = NULL;
		$data["token"] = NULL;
		$data["workAddress"] = NULL;
		$data["zipcode"] = NULL;
		$data["lat"] = 0;
		$data["lng"] = 0;
		$data["image"] = NULL;
		$data["clientSecret"] = NULL;
		$data["cusId"] = NULL;
		$data["ratings"] = NULL;
		$data["isApproved"] = TRUE;
		$data["isActive"] = true;

		$response = $this->customer_model->add_customer($data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'New customer added successfully');
			redirect('customer');
		} else {
			$errormsg = 'Error! User already Exists.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect('customer/addcustomer');
		}
	}



	public function updatecustomerdata($id)
	{
		$da = $this->input->post();
		//print_r($da);
		if ($da['newpassword'] != "") {

			$da['password'] = $da['newpassword'];
			$da['newpassword'] = "";
			$flag = $this->customer_model->update_customerpassword($id, $da['password']);




			if ($flag) {
				$data["promotions"] = $this->common->updatedatamodel("Users", $id, $da);
				$this->session->set_flashdata('successmessage', 'User has been updated successfully');
			} else {
				$this->session->set_flashdata('warningmessage', 'Something wrong, Please try again later');

				redirect(base_url().'customer/editcustomer/'.$id);
			}
		} else {
			$data["promotions"] = $this->common->updatedatamodel("Users", $id, $da);
			$this->session->set_flashdata('successmessage', 'User has been updated successfully');
		}



		redirect(base_url().'customer');
	}

	public function editcustomer()
	{
		$c_id = $this->uri->segment(3);
		$data['id'] = $c_id;
		$data['customerdetails'] = $this->customer_model->get_customerdetails($c_id);
		

		$this->template->template_render('editcustomer', $data);
	}

	public function resetCustomer()
	{
		// $data = $this->input->post();
		foreach ($_POST as $key => $val) {
			if (strpos($key, "new") === 0) {
				$name = substr($key, 3);
				$data["new"][$name] = $val;
			}
		}
		foreach ($_POST as $key => $val) {
			if (strpos($key, "old") === 0) {
				$name = substr($key, 3);
				$data["old"][$name] = $val;
			}
		}
		// print_r($data);
		// exit;
		$response = $this->customer_model->update_customer($data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Customer updated successfully.');
			redirect('customer');
		} else {
			$errormsg = 'Error! Something went Wrong. Either the user does not exist or password does not match.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect('customer/userreset');
		}
	}

	public function updatecustomer()
	{
		$testxss = xssclean($_POST);
		if ($testxss) {
			$response = $this->customer_model->update_customer($this->input->post());
			if ($response) {
				$this->session->set_flashdata('successmessage', 'Customer updated successfully..');
				redirect('customer');
			} else {
				$this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
				redirect('customer');
			}
		} else {
			$this->session->set_flashdata('warningmessage', 'Error! Your input are not allowed.Please try again');
			redirect('customer');
		}
	}
}