<?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 all customers with userRole = 'user'
		$allCustomers = $this->customer_model->getallunapprovied_customer();
		
		// Filter inactive/pending customers (isActive = false or not set)
		$customerlist = array();
		foreach ($allCustomers as $id => $customer) {
			// Check if customer is not active (pending)
			if (!isset($customer['isActive']) || !$customer['isActive']) {
				$customerlist[$id] = $customer;
			}
		}
		
		$data['customerlist'] = $customerlist;
		$data['filterType'] = 'pending'; // For UI indication
		
		// Calculate statistics
		$stats = array(
			'totalCustomers' => count($customerlist),
			'withBalance' => 0,
			'totalBalance' => 0,
			'onlineUsers' => 0,
			'withRatings' => 0,
			'avgRating' => 0,
			'totalRatings' => 0
		);
		
		$totalRatingSum = 0;
		$ratingCount = 0;
		
		foreach ($customerlist as $customer) {
			// Count users with balance
			if (isset($customer['balance']) && floatval($customer['balance']) > 0) {
				$stats['withBalance']++;
				$stats['totalBalance'] += floatval($customer['balance']);
			}
			
			// Count online users
			if (isset($customer['isOnline']) && $customer['isOnline']) {
				$stats['onlineUsers']++;
			}
			
			// Calculate ratings
			if (isset($customer['totalRating']) && intval($customer['totalRating']) > 0) {
				$stats['withRatings']++;
				$stats['totalRatings'] += intval($customer['totalRating']);
				
				if (isset($customer['avgRating']) && floatval($customer['avgRating']) > 0) {
					$totalRatingSum += floatval($customer['avgRating']);
					$ratingCount++;
				}
			}
		}
		
		// Calculate average rating
		if ($ratingCount > 0) {
			$stats['avgRating'] = round($totalRatingSum / $ratingCount, 2);
		}
		
		$data['stats'] = $stats;
		
		$this->template->template_render('customer_management', $data);
	}
	
	public function approvedcustomer()
	{
		// Get all customers with userRole = 'user'
		$allCustomers = $this->customer_model->getallapprovied_customer();
		
		// Filter active/approved customers (isActive = true)
		$customerlist = array();
		foreach ($allCustomers as $id => $customer) {
			// Check if customer is active (approved)
			if (isset($customer['isActive']) && $customer['isActive']) {
				$customerlist[$id] = $customer;
			}
		}
		
		$data['customerlist'] = $customerlist;
		$data['filterType'] = 'approved'; // For UI indication
		
		// Calculate statistics
		$stats = array(
			'totalCustomers' => count($customerlist),
			'withBalance' => 0,
			'totalBalance' => 0,
			'onlineUsers' => 0,
			'withRatings' => 0,
			'avgRating' => 0,
			'totalRatings' => 0
		);
		
		$totalRatingSum = 0;
		$ratingCount = 0;
		
		foreach ($customerlist as $customer) {
			// Count users with balance
			if (isset($customer['balance']) && floatval($customer['balance']) > 0) {
				$stats['withBalance']++;
				$stats['totalBalance'] += floatval($customer['balance']);
			}
			
			// Count online users
			if (isset($customer['isOnline']) && $customer['isOnline']) {
				$stats['onlineUsers']++;
			}
			
			// Calculate ratings
			if (isset($customer['totalRating']) && intval($customer['totalRating']) > 0) {
				$stats['withRatings']++;
				$stats['totalRatings'] += intval($customer['totalRating']);
				
				if (isset($customer['avgRating']) && floatval($customer['avgRating']) > 0) {
					$totalRatingSum += floatval($customer['avgRating']);
					$ratingCount++;
				}
			}
		}
		
		// Calculate average rating
		if ($ratingCount > 0) {
			$stats['avgRating'] = round($totalRatingSum / $ratingCount, 2);
		}
		
		$data['stats'] = $stats;
		
		$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');
		}
	}
}
