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

class Users 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');
		define('API_ACCESS_KEY1', 'AAAAIpWpd14:APA91bGWyzOEV8wFb5j4gmvNsessh_Ce4BFvxt41dG8n1I3EuCv5i60YT3E-eY6HiRsjshjmyn5v5EX4uwF9UNnVRyRp1q2RHRBRxsZ0ye3BhfVUuof5b_50SoFI_SX1GsEwRrFRZ26k');
	}


	public function index()
	{
		$data['userlist'] = $this->user_model->getall_user();
		$this->template->template_render('user_management', $data);
	}
	public function adduser()
	{
		$this->template->template_render('user_add');
	}
	public function insertuser()
	{
		if (isset($_POST)) {
			$response = $this->user_model->add_user($this->input->post());
			if ($response) {
				$this->session->set_flashdata('successmessage', 'New user added successfully..');
			} else {
				$this->session->set_flashdata('warningmessage', 'Error in creating new user..');
			}
			redirect('users');
		} else {
			$this->session->set_flashdata('warningmessage', 'Error! Your input are not allowed.Please try again');
			redirect('users');
		}
	}
	public function edituser()
	{
		$u_id = $this->uri->segment(3);
		$data['userdetails'] = $this->user_model->get_userdetails($u_id);
		$this->template->template_render('user_add', $data);
	}

	public function updateuser()
	{
		if (isset($_POST)) {
			$response = $this->user_model->update_user($this->input->post());
			if ($response) {
				$this->session->set_flashdata('successmessage', 'user updated successfully..');
				redirect('users');
			} else {
				$this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
				redirect('users');
			}
		} else {
			$this->session->set_flashdata('warningmessage', 'Error! Your input are not allowed.Please try again');
			redirect('users');
		}
	}

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

	// public function updateProfile()
	// {
	// 	$adminId = $this->session->userdata['session_data']['userId'];

	// 	if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	// 		$data = [
	// 			'firstName' => trim($this->input->post('firstName')),
	// 			'lastName' => trim($this->input->post('lastName')),
	// 			'email' => trim($this->input->post('email')),
	// 			'phone' => trim($this->input->post('phone')),
	// 			'dob' => trim($this->input->post('dob')),
	// 			'address' => trim($this->input->post('address')),
	// 		];
	// 		$data['name'] = $data['firstName'] . ' ' . $data['lastName'];
	// 		$resp = $this->common->updatedatamodel('Users', $adminId, $data);

	// 		if ($resp) {
	// 			$sessionData = $this->session->userdata('session_data');
	// 			$sessionData['firstName'] = $data['firstName'];
	// 			$sessionData['lastName'] = $data['lastName'];
	// 			$sessionData['email'] = $data['email'];
	// 			$sessionData['phone'] = $data['phone'];
	// 			$sessionData['address'] = $data['address'];
	// 			$this->session->set_userdata('session_data', $sessionData);

	// 			$this->session->set_flashdata('successmessage', 'Profile updated successfully.');
	// 			redirect(base_url() . 'users/profile');
	// 		} else {
	// 			$this->session->set_flashdata('warningmessage', 'Error updating profile. Please try again.');
	// 			redirect(base_url() . 'users/profile');
	// 		}
	// 	} else {
	// 		$this->session->set_flashdata('warningmessage', 'Invalid request method.');
	// 		redirect(base_url() . 'users/profile');
	// 	}
	// }

	public function updateProfile()
	{
		$adminId = $this->session->userdata['session_data']['userId'];

		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			// Get the input values
			$firstName = trim($this->input->post('firstName'));
			$lastName = trim($this->input->post('lastName'));
			$name = trim($this->input->post('name'));  // The full name input

			// If firstName or lastName is empty, parse the 'name' field to extract them
			if (empty($firstName) && empty($lastName) && !empty($name)) {
				$nameParts = explode(' ', $name);
				$firstName = $nameParts[0];  // The first part will be firstName
				$lastName = isset($nameParts[1]) ? $nameParts[1] : '';  // The second part will be lastName if available
			}

			// Concatenate firstName and lastName to get the final name
			$finalName = $firstName . ' ' . $lastName;

			// Prepare the data for updating the profile
			$data = [
				'firstName' => $firstName,
				'lastName' => $lastName,
				'name' => $finalName,  // Update the name in the database
				'email' => trim($this->input->post('email')),
				'phone' => trim($this->input->post('phone')),
				'dob' => trim($this->input->post('dob')),
				'address' => trim($this->input->post('address')),
			];

			// Update user data in the database
			$resp = $this->common->updatedatamodel('Users', $adminId, $data);

			if ($resp) {
				// Update session data
				$sessionData = $this->session->userdata('session_data');
				$sessionData['firstName'] = $data['firstName'];
				$sessionData['lastName'] = $data['lastName'];
				$sessionData['name'] = $data['name'];  // Update name in session
				$sessionData['email'] = $data['email'];
				$sessionData['phone'] = $data['phone'];
				$sessionData['address'] = $data['address'];
				$this->session->set_userdata('session_data', $sessionData);

				$this->session->set_flashdata('successmessage', 'Profile updated successfully.');
				redirect(base_url() . 'users/profile');
			} else {
				$this->session->set_flashdata('warningmessage', 'Error updating profile. Please try again.');
				redirect(base_url() . 'users/profile');
			}
		} else {
			$this->session->set_flashdata('warningmessage', 'Invalid request method.');
			redirect(base_url() . 'users/profile');
		}
	}


	public function uploadProfileImage()
	{
		$config['upload_path'] = './uploads/profile_images/';
		$config['allowed_types'] = 'jpg|jpeg|png';
		$config['max_size'] = 2048; // 2 MB
		$config['file_name'] = 'profile_' . $this->session->userdata['session_data']['userId'];

		$this->load->library('upload', $config);

		if ($this->upload->do_upload('user_image')) {
			$uploadData = $this->upload->data();
			$imagePath = base_url('uploads/profile_images/' . $uploadData['file_name']);

			// Update the user's profile image in the database
			$this->common->updatedatamodel('Users', $this->session->userdata['session_data']['userId'], ['u_image' => $imagePath]);

			// Update the session data
			$sessionData = $this->session->userdata('session_data');
			$sessionData['u_image'] = $imagePath;
			$this->session->set_userdata('session_data', $sessionData);

			// Return success response with the new image URL
			echo json_encode(['status' => 'success', 'image_url' => $imagePath]);
		} else {
			// Log and return the error message for debugging
			log_message('error', 'Image upload failed: ' . $this->upload->display_errors());
			echo json_encode(['status' => 'error', 'message' => $this->upload->display_errors()]);
		}
	}


	public function resetpasswordsave()
	{
		$adminId = $this->session->userdata['session_data']['userId'];

		$password = $this->input->post('password');
		$cnfpassword = $this->input->post('cnfpassword');

		if (strlen($password) < 6) {
			$this->session->set_flashdata('warningmessage', 'Error: Please enter a password with 6 or more characters.');
			redirect(base_url() . 'resetpassword');
		}

		if ($password != $cnfpassword) {
			$this->session->set_flashdata('warningmessage', 'Error: Both password fields should match.');
			redirect(base_url() . 'resetpassword');
		}

		$firebase = $this->firebase->init();
		$atuh = $firebase->createAuth();


		try {
			$updatedUser  = $atuh->changeUserPassword($adminId, $password);
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Error: ' . $e->getMessage());
			redirect(base_url() . 'resetpassword');
		}

		$data = [
			'password' => trim($this->input->post('password')),
		];

		$resp = $this->common->updatedatamodel('Users', $adminId, $data);

		if ($resp) {
			$this->session->set_flashdata('successmessage', 'Password updated successfully!.');
			redirect(base_url() . 'Users/profile');
		} else {
			$this->session->set_flashdata('warningmessage', 'Error in resetting password.');
			redirect(base_url() . 'Users/profile');
		}
	}
}
