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

class Resetpassword extends CI_Controller
{
	function __construct()
	{
		parent::__construct();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->library('session');
		$this->load->model('common');
		$this->load->model('user_model');
		$this->load->library(array('form_validation', 'template'));
	}
	public function index()
	{
		$sessionData = $this->session->userdata('session_data');
		// $this->load->view('resetpassword', ['userdetails' => $sessionData]);
		$this->template->template_render('resetpassword', ['userdetails' => $sessionData]);
	}

	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() . 'dashboard');
		} else {
			$this->session->set_flashdata('warningmessage', 'Error in resetting password.');
			redirect(base_url() . 'resetpassword');
		}
	}

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

		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			// Load Firebase
			$this->load->library('firebase');
			$firebase = $this->firebase->init();
			$storage = $firebase->createStorage();
			$bucket = $storage->getBucket();

			if (!empty($_FILES['user_image']['name'])) {
				try {
					$filename = 'Users/' . uniqid() . '_' . $_FILES['user_image']['name'];

					$uploadedFile = $bucket->upload(
						file_get_contents($_FILES['user_image']['tmp_name']),
						[
							'name' => $filename,
							'predefinedAcl' => 'publicRead'
						]
					);
					$imageUrl = 'https://storage.googleapis.com/' . $bucket->name() . '/' . $filename;
				} catch (Exception $e) {
					log_message('error', 'Firebase image upload failed: ' . $e->getMessage());
					$this->session->set_flashdata('warningmessage', 'Image upload failed: ' . $e->getMessage());
					redirect(base_url() . 'resetpassword');
				}
			} else {
				$this->session->set_flashdata('warningmessage', 'No image selected.');
				redirect(base_url() . 'resetpassword');
			}

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

			if ($resp) {
				$sessionData = $this->session->userdata('session_data');
				$sessionData['u_image'] = $imageUrl; 
				$this->session->set_userdata('session_data', $sessionData);

				$this->session->set_flashdata('successmessage', 'Profile picture updated successfully.');
				redirect(base_url() . 'dashboard');
			} else {
				$this->session->set_flashdata('warningmessage', 'Something went wrong. Try again.');
				redirect(base_url() . 'resetpassword');
			}
		} else {
			$this->session->set_flashdata('warningmessage', 'Error! Your input is not allowed. Please try again.');
			redirect(base_url() . 'resetpassword');
		}
	}
}
