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

class Customer extends CI_Controller
{

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

		$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 index()
	{
		// Get unapproved customers
		$customerlist = $this->customer_model->getallunapprovied_customer();
		$data['customerlist'] = $customerlist;
		$data['filterType'] = 'pending'; // For UI indication
		
		// Get all cities for filtering
		$allCities = $this->common->readdatafromcollectionwhereclause('Cities');
		$data['cities'] = $allCities;
		
		// Calculate statistics
		$stats = array(
			'totalCustomers' => count($customerlist),
			'withLoyaltyPoints' => 0,
			'withIdVerification' => 0,
			'totalLoyaltyPoints' => 0
		);
		
		foreach ($customerlist as $customer) {
			if (isset($customer['points']) && $customer['points'] > 0) {
				$stats['withLoyaltyPoints']++;
				$stats['totalLoyaltyPoints'] += isset($customer['points']) ? intval($customer['points']) : 0;
			}
			if ((isset($customer['idFront']) && $customer['idFront'] != '') || 
			    (isset($customer['idBack']) && $customer['idBack'] != '')) {
				$stats['withIdVerification']++;
			}
		}
		
		$data['stats'] = $stats;
		
		// Enhance customer data with city names
		$enhancedCustomers = array();
		foreach ($customerlist as $id => $customer) {
			$customer['cityName'] = 'Not Assigned';
			if (isset($customer['cityId']) && !empty($customer['cityId']) && isset($allCities[$customer['cityId']])) {
				$customer['cityName'] = isset($allCities[$customer['cityId']]['cityName']) ? 
					$allCities[$customer['cityId']]['cityName'] : 'Unknown';
			}
			$enhancedCustomers[$id] = $customer;
		}
		$data['customerlist'] = $enhancedCustomers;
		
		$this->template->template_render('customer_management', $data);
	}
	
	public function approvedcustomer()
	{
		// Get approved customers
		$customerlist = $this->customer_model->getallapprovied_customer();
		$data['customerlist'] = $customerlist;
		$data['filterType'] = 'approved'; // For UI indication
		
		// Get all cities for filtering
		$allCities = $this->common->readdatafromcollectionwhereclause('Cities');
		$data['cities'] = $allCities;
		
		// Calculate statistics
		$stats = array(
			'totalCustomers' => count($customerlist),
			'withLoyaltyPoints' => 0,
			'withIdVerification' => 0,
			'totalLoyaltyPoints' => 0
		);
		
		foreach ($customerlist as $customer) {
			if (isset($customer['points']) && $customer['points'] > 0) {
				$stats['withLoyaltyPoints']++;
				$stats['totalLoyaltyPoints'] += isset($customer['points']) ? intval($customer['points']) : 0;
			}
			if ((isset($customer['idFront']) && $customer['idFront'] != '') || 
			    (isset($customer['idBack']) && $customer['idBack'] != '')) {
				$stats['withIdVerification']++;
			}
		}
		
		$data['stats'] = $stats;
		
		// Enhance customer data with city names
		$enhancedCustomers = array();
		foreach ($customerlist as $id => $customer) {
			$customer['cityName'] = 'Not Assigned';
			if (isset($customer['cityId']) && !empty($customer['cityId']) && isset($allCities[$customer['cityId']])) {
				$customer['cityName'] = isset($allCities[$customer['cityId']]['cityName']) ? 
					$allCities[$customer['cityId']]['cityName'] : 'Unknown';
			}
			$enhancedCustomers[$id] = $customer;
		}
		$data['customerlist'] = $enhancedCustomers;
		
		$this->template->template_render('customer_management', $data);
	}

	public function suspendCustomer($id)
	{
		$data["isApproved"] = false;
		$response = $this->common->updatedatamodel("Users", $id, $data);

		$this->session->set_flashdata('successmessage', 'User Suspended');
		redirect('customer');
	}

	public function unSuspendCustomer($id)
	{
		$data["isApproved"] = true;
		$response = $this->common->updatedatamodel("Users", $id, $data);
		

		$this->session->set_flashdata('successmessage', 'User UnSuspended');
		redirect('customer');
	}

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

	public function addcustomer()
	{
		// Get all cities for dropdown
		$allCities = $this->common->readdatafromcollectionwhereclause('Cities');
		$data['cities'] = $allCities;
		$data['customerdetails'] = null;
		
		$this->template->template_render('customer_add', $data);
	}
	
	public function editcustomers($id)
	{
		$data['id'] = $id;
		$data["customerdetails"] = $this->common->readdatadocument("Users", $id);
		
		// Get all cities for dropdown
		$allCities = $this->common->readdatafromcollectionwhereclause('Cities');
		$data['cities'] = $allCities;
		
		$this->template->template_render('customer_add', $data);
	}
	public function userreset()
	{
		$this->template->template_render('user_reset_credentials');
	}

	public function insertcustomer()
	{
		$data = $this->input->post();
		$isAjax = $this->input->is_ajax_request();
		
		// Validation
		if (empty($data['firstName']) || empty($data['email']) || empty($data['password'])) {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'First Name, Email, and Password are required.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'First Name, Email, and Password are required.');
				redirect('customer/addcustomer');
				return;
			}
		}
		
		// Check for duplicate email
		$allUsers = $this->common->readdatafromcollectionwhereclause("Users");
		foreach ($allUsers as $userId => $user) {
			if (isset($user['email']) && strtolower($user['email']) === strtolower(trim($data['email']))) {
				if ($isAjax) {
					echo json_encode(array('success' => false, 'message' => 'Customer with this email already exists.'));
					return;
				} else {
					$this->session->set_flashdata('warningmessage', 'Customer with this email already exists.');
					redirect('customer/addcustomer');
					return;
				}
			}
		}
		
		// Prepare customer data
		$customerData = array(
			"userRole" => "user",
			"firstName" => trim($data['firstName']),
			"lastName" => isset($data['lastName']) ? trim($data['lastName']) : '',
			"email" => trim($data['email']),
			"phoneNumber" => isset($data['phoneNumber']) ? trim($data['phoneNumber']) : '',
			"password" => trim($data['password']),
			"cityId" => isset($data['cityId']) && !empty($data['cityId']) ? trim($data['cityId']) : null,
			"points" => isset($data['points']) ? intval($data['points']) : 0,
			"isApproved" => isset($data['isApproved']) ? (bool)$data['isApproved'] : true,
			"isActive" => isset($data['isActive']) ? (bool)$data['isActive'] : true,
			"token" => null,
			"image" => null,
			"idFront" => null,
			"idBack" => null
		);
		
		// Handle file uploads if provided
		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();
		
		if (isset($_FILES['profile_image']['tmp_name']) && $_FILES['profile_image']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['profile_image']['tmp_name']),
				[
					'name' => "customerImage" . rand() . time() . $_FILES['profile_image']['name'],
				]
			);
			$customerData["image"] = $uploadedFile->info()['mediaLink'];
		}
		
		if (isset($_FILES['idFront']['tmp_name']) && $_FILES['idFront']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['idFront']['tmp_name']),
				[
					'name' => "idFront" . rand() . time() . $_FILES['idFront']['name'],
				]
			);
			$customerData["idFront"] = $uploadedFile->info()['mediaLink'];
		}
		
		if (isset($_FILES['idBack']['tmp_name']) && $_FILES['idBack']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['idBack']['tmp_name']),
				[
					'name' => "idBack" . rand() . time() . $_FILES['idBack']['name'],
				]
			);
			$customerData["idBack"] = $uploadedFile->info()['mediaLink'];
		}
		
		// Add customer via model (creates Firebase Auth user first)
		$response = $this->customer_model->add_customer($customerData);
		
		if ($response) {
			if ($isAjax) {
				echo json_encode(array('success' => true, 'message' => 'Customer added successfully!'));
				return;
			} else {
				$this->session->set_flashdata('successmessage', 'New customer added successfully');
			}
		} else {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'Error! Customer with this email already exists.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Error! Customer with this email already exists.');
			}
		}
		
		if (!$isAjax) {
			redirect('customer');
		}
	}

	public function updateuserdata($id)
	{
		$da = $this->input->post();
		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();

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

			$da["image"] = $uploadedFile->info()['mediaLink'];
		}

		//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', 'Users has been updated successfully');
			} else {
				$this->session->set_flashdata('warningmessage', 'Usome thing error Please try later');

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



		redirect('Customer/editprofile');
	}


	public function updatecustomerdata($id)
	{
		$da = $this->input->post();
		$isAjax = $this->input->is_ajax_request();
		
		// Validation
		if (empty($da['firstName'])) {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'First Name is required.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'First Name is required.');
				redirect('customer/editcustomers/' . $id);
				return;
			}
		}
		
		// Handle password update if provided
		if (!empty($da['newpassword'])) {
			$newPassword = trim($da['newpassword']);
			if (strlen($newPassword) < 6) {
				if ($isAjax) {
					echo json_encode(array('success' => false, 'message' => 'Password must be at least 6 characters.'));
					return;
				} else {
					$this->session->set_flashdata('warningmessage', 'Password must be at least 6 characters.');
					redirect('customer/editcustomers/' . $id);
					return;
				}
			}
			
			$flag = $this->customer_model->update_customerpassword($id, $newPassword);
			if (!$flag) {
				if ($isAjax) {
					echo json_encode(array('success' => false, 'message' => 'Failed to update password.'));
					return;
				} else {
					$this->session->set_flashdata('warningmessage', 'Failed to update password.');
					redirect('customer/editcustomers/' . $id);
					return;
				}
			}
			unset($da['newpassword']);
		}
		
		// Handle file uploads
		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();
		
		if (isset($_FILES['profile_image']['tmp_name']) && $_FILES['profile_image']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['profile_image']['tmp_name']),
				[
					'name' => "customerImage" . rand() . time() . $_FILES['profile_image']['name'],
				]
			);
			$da["image"] = $uploadedFile->info()['mediaLink'];
		}
		
		if (isset($_FILES['idFront']['tmp_name']) && $_FILES['idFront']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['idFront']['tmp_name']),
				[
					'name' => "idFront" . rand() . time() . $_FILES['idFront']['name'],
				]
			);
			$da["idFront"] = $uploadedFile->info()['mediaLink'];
		}
		
		if (isset($_FILES['idBack']['tmp_name']) && $_FILES['idBack']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['idBack']['tmp_name']),
				[
					'name' => "idBack" . rand() . time() . $_FILES['idBack']['name'],
				]
			);
			$da["idBack"] = $uploadedFile->info()['mediaLink'];
		}
		
		// Clean up data
		unset($da['password']); // Don't update password field directly
		
		// Update customer data
		$response = $this->common->updatedatamodel("Users", $id, $da);
		
		if ($response) {
			if ($isAjax) {
				echo json_encode(array('success' => true, 'message' => 'Customer updated successfully!'));
				return;
			} else {
				$this->session->set_flashdata('successmessage', 'Customer updated successfully');
			}
		} else {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'Failed to update customer.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Failed to update customer.');
			}
		}
		
		if (!$isAjax) {
			redirect('customer/editcustomers/' . $id);
		}
	}

	
	public function editprofile()
	{

		$sessiondata=$this->session->userdata['session_data'];
		$userid=$sessiondata['userId'];
		
		$c_id = $userid;
		$data['id'] = $c_id;
		$data['customerdetails'] = $this->customer_model->get_customerdetails($c_id);
		// echo "<pre>";
		// print_r($data);
		// echo "</pre>";


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

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


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