<?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 index()
	{

		$data['customerlist'] = $this->customer_model->getallunapprovied_customer();
		
		$this->template->template_render('customer_management', $data);
	}
	//
	public function approvedcustomer()
	{

		$data['customerlist'] = $this->customer_model->getallapprovied_customer();
		
		$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()
	{
		$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"] = 0;

		$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 updateuserdata($id = '')
	{
		if (strtoupper((string) $this->input->server('REQUEST_METHOD')) !== 'POST') {
			redirect('Customer/editprofile');
			return;
		}
		if (!isset($this->session->userdata['session_data'])) {
			redirect('login');
			return;
		}

		$session = $this->session->userdata['session_data'];
		$sessionUid = isset($session['userId']) ? (string) $session['userId'] : '';
		$id = trim((string) $id);
		if ($id === '' || $sessionUid === '' || $id !== $sessionUid) {
			$this->session->set_flashdata('errormessage', 'You can only update your own profile.');
			redirect('Customer/editprofile');
			return;
		}

		$loaded = $this->_load_current_profile($id);
		if ($loaded === null) {
			$this->session->set_flashdata('errormessage', 'Profile not found.');
			redirect('Customer/editprofile');
			return;
		}
		$col = $loaded['_collection'];
		$current = $loaded['data'];

		$userName = trim((string) $this->input->post('userName'));
		$email = strtolower(trim((string) $this->input->post('email')));
		$password = (string) $this->input->post('newpassword');

		if ($userName === '') {
			$this->session->set_flashdata('errormessage', 'Name is required.');
			redirect('Customer/editprofile');
			return;
		}
		if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
			$this->session->set_flashdata('errormessage', 'Enter a valid email address.');
			redirect('Customer/editprofile');
			return;
		}
		if ($password !== '' && strlen($password) < 6) {
			$this->session->set_flashdata('errormessage', 'Password must be at least 6 characters.');
			redirect('Customer/editprofile');
			return;
		}

		$payload = array(
			'userName' => $userName,
			'name' => $userName,
			'email' => $email,
			'updatedAt' => (int) round(microtime(true) * 1000),
		);

		if (!empty($_FILES['profile_image']['tmp_name']) && is_uploaded_file($_FILES['profile_image']['tmp_name'])) {
			try {
				$firebase = $this->firebase->init();
				$storage = $firebase->createStorage();
				$defaultBucket = $storage->getBucket();
				$safeName = preg_replace('/[^a-zA-Z0-9._-]/', '_', (string) $_FILES['profile_image']['name']);
				$uploadedFile = $defaultBucket->upload(
					file_get_contents($_FILES['profile_image']['tmp_name']),
					array('name' => 'profileImage_' . $id . '_' . time() . '_' . $safeName)
				);
				$payload['image'] = $uploadedFile->info()['mediaLink'];
			} catch (\Throwable $e) {
				$this->session->set_flashdata('errormessage', 'Image upload failed: ' . $e->getMessage());
				redirect('Customer/editprofile');
				return;
			}
		}

		$authNotes = array();
		try {
			$auth = $this->firebase->init()->createAuth();
			$props = array('displayName' => $userName);
			$currentEmail = isset($current['email']) ? strtolower((string) $current['email']) : '';
			if ($currentEmail !== $email) {
				$props['email'] = $email;
			}
			if ($password !== '') {
				$props['password'] = $password;
			}
			$auth->updateUser($id, $props);
		} catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
			$authNotes[] = 'Firebase Auth user was not found; Firestore was still updated.';
		} catch (\Throwable $e) {
			$this->session->set_flashdata('errormessage', 'Auth update failed: ' . $e->getMessage());
			redirect('Customer/editprofile');
			return;
		}

		if ($password !== '') {
			$payload['password'] = $password;
		}

		try {
			$this->common->updatedatamodel($col, $id, $payload);
		} catch (\Throwable $e) {
			$this->session->set_flashdata('errormessage', 'Profile update failed: ' . $e->getMessage());
			redirect('Customer/editprofile');
			return;
		}

		$session['name'] = $userName;
		$session['email'] = $email;
		$this->session->set_userdata('session_data', $session);

		$msg = 'Profile updated.';
		if (!empty($authNotes)) {
			$msg .= ' ' . implode(' ', $authNotes);
		}
		$this->session->set_flashdata('successmessage', $msg);
		redirect('Customer/editprofile');
	}


	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', '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/editcustomer/' . $id);
	}

	
	public function editprofile()
	{
		if (!isset($this->session->userdata['session_data'])) {
			redirect('login');
			return;
		}

		$sessiondata = $this->session->userdata['session_data'];
		$userid = isset($sessiondata['userId']) ? (string) $sessiondata['userId'] : '';
		if ($userid === '') {
			redirect('login');
			return;
		}

		$loaded = $this->_load_current_profile($userid);
		if ($loaded === null) {
			$this->session->set_flashdata('errormessage', 'Profile not found.');
			redirect('admin');
			return;
		}

		$data['id'] = $userid;
		$data['user'] = $loaded['data'];
		$data['collection'] = $loaded['_collection'];
		$data['page_title'] = 'My profile';
		$this->template->template_render('editprofile', $data);
	}

	private function _load_current_profile($uid)
	{
		$uid = trim((string) $uid);
		foreach (array('users', 'user') as $col) {
			try {
				$row = $this->common->readdatadocument($col, $uid);
			} catch (\Throwable $e) {
				$row = '';
			}
			if (is_array($row) && !empty($row)) {
				if (empty($row['userName']) && !empty($row['name'])) {
					$row['userName'] = $row['name'];
				}
				if (empty($row['name']) && !empty($row['userName'])) {
					$row['name'] = $row['userName'];
				}
				return array('data' => $row, '_collection' => $col);
			}
		}
		return null;
	}

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