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

use Kreait\Firebase\Exception\FirebaseException;

// use Kreait\Firebase\Factory;
// use Kreait\Firebase\ServiceAccount;
// use Kreait\Firebase\Storage;
// use Google\Cloud\Storage\StorageClient;


//use Throwable;

class Login extends CI_Controller
{
	//To load initial libraries, functions
	function __construct()
	{
		parent::__construct();
		$this->load->helper('url');
		// $this->load->database();
		$this->load->helper('directory');
		$this->load->helper('form');
		$this->load->library('form_validation');
		$this->load->model('common');
		$this->load->library('session');
	}


	public function index()
	{

		if (!empty($this->session->userdata('session_data'))) {
			$url = base_url('dashboard');
			header("location: $url");
		} else {
			$this->load->view('login');
		}
	}

	public function testUpload()
	{
		try {
			$firebase = $this->firebase->init();
			$storage = $firebase->createStorage();

			// ✅ Explicitly set the correct bucket
			$bucketName = "naseej-54d06.appspot.com";
			$defaultBucket = $storage->getBucket($bucketName);

			// ✅ Debug: Print bucket name
			echo "Using bucket: " . $defaultBucket->name() . "<br>";

			// ✅ Debug: Check if file exists
			if (empty($_FILES['file']['tmp_name'])) {
				die("No file uploaded.");
			}

			$file_name = "test/" . time() . "_" . $_FILES['file']['name'];

			// ✅ Debug: Print file details
			echo "Uploading: " . $_FILES['file']['name'] . "<br>";
			echo "Size: " . $_FILES['file']['size'] . " bytes<br>";

			// ✅ Upload file
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['file']['tmp_name']),
				[
					'name' => $file_name,
				]
			);

			// ✅ Print uploaded file URL
			echo "File uploaded successfully: " . $uploadedFile->info()['mediaLink'];
		} catch (\Exception $e) {
			die("Upload failed: " . $e->getMessage());
		}
	}



	// public function signup()
	// {

	// 	// $firebase = $this->firebase->init();
	// 	// 		$storage = $firebase->createStorage();
	// 	// 		$defaultBucket = $storage->getBucket();

	// 	// 		print_r($defaultBucket);
	// 	// 		die;
	// 	if (!empty($this->session->userdata('session_data'))) {
	// 		$url = base_url('dashboard');
	// 		header("location: $url");
	// 	} else {

	// 		  // Fetch all categories
	// 		  $categoriesQuery = $db->collection('Categories')->documents();
	// 		  $categories = [];
	// 		  foreach ($categoriesQuery as $category) {
	// 			$categories[] = [
	// 			  'id' => $category->id(),
	// 			  'data' => $category->data(),
	// 			];
	// 		  }

	// 		$this->load->view('user/signup');
	// 	}
	// }

	public function signup()
	{
		if (!empty($this->session->userdata('session_data'))) {
			redirect(base_url('dashboard'));
		} else {
			try {
				$firebase = $this->firebase->init();
				$firestore = $firebase->createFirestore();
				$db = $firestore->database();

				// Fetch all categories
				$categoriesQuery = $db->collection('Categories')->documents();
				$categories = [];
				foreach ($categoriesQuery as $category) {
					$categories[] = [
						'id' => $category->id(),
						'data' => $category->data(),
					];
				}

				// Pass categories to the view
				$this->load->view('user/signup', ['categories' => $categories]);
			} catch (Exception $e) {
				$this->session->set_flashdata('warningmessage', 'Error loading signup page: ' . $e->getMessage());
				redirect(base_url('login'));
			}
		}
	}



	public function login_action()
	{
		$email = $this->input->post("email");
		$password = $this->input->post("password");

		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();
		$firestore = $firebase->createFirestore();
		$db = $firestore->database();

		try {

			$signInResult = $auth->signInWithEmailAndPassword($email, $password);
		} catch (FirebaseException $e) {
			$this->session->set_flashdata('warningmessage', 'Invalid email and/or password!');
			$this->session->set_flashdata('email', $email);
			redirect(base_url('login'));
		}

		$my = $signInResult->data();
		$userId = $my['localId'];

		$admin = $this->common->readdatadocument("Users", $userId);

		if (isset($admin["userType"]) && $admin["userType"] !== 'tailor') {
			// Check user type is not admin
			$this->session->set_flashdata('warningmessage', 'You are not authorized to log in!');
			redirect(base_url('login'));
		}

		// 🔍 Check verification status in Tailers collection
		$tailerDoc = $db->collection('Tailers')->document($userId)->snapshot();

		if ($tailerDoc->exists()) {
			$tailerData = $tailerDoc->data();
			if (isset($tailerData['isVerified']) && $tailerData['isVerified'] === false) {
				$this->session->set_flashdata('warningmessage', 'We are reviewing your account. Please try again later. You will be notified once your account verification is complete.');
				redirect(base_url('login'));
			}
		} else {
			$this->session->set_flashdata('warningmessage', 'Tailor data not found! Please contact support.');
			redirect(base_url('login'));
		}

		if (!empty($my["idToken"])) {
			// Prepare session data
			$session_data = array(
				'userId' => $userId,
				'name' => $admin["name"],
				'email' => $admin["email"],
				'u_image' => $admin["u_image"],
				'firebaseToken' => $my["idToken"],
				'userType' => $admin["userType"],
				'tailorType' => $admin["tailorType"],
			);

			$this->session->set_userdata('session_data', $session_data);
			$this->session->set_userdata('authenthicate', true);

			redirect(base_url('dashboard'));
		} else {
			// Fallback in case of unexpected issues
			$this->session->set_flashdata('warningmessage', 'Something went wrong! Please try again.');
			$this->session->set_flashdata('email', $email);
			redirect(base_url('login'));
		}
	}




	public function signup_action()
	{
		$this->load->library('form_validation');

		// Set validation rules
		$this->form_validation->set_rules('name', 'Name', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
		// $this->form_validation->set_rules('start_date', 'Start Date', 'required');
		$this->form_validation->set_rules('shop_timing', 'Shop Timing', 'required');
		$this->form_validation->set_rules('shop_location', 'Shop Location', 'required');
		$this->form_validation->set_rules('opening_number', 'Opening Number', 'required');

		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('warningmessage', validation_errors());
			$this->session->set_flashdata('form_data', $this->input->post());
			redirect(base_url('login/signup'));
		}

		try {
			// Initialize Firebase
			$firebase = $this->firebase->init();
			$storage = $firebase->createStorage();
			$defaultBucket = $storage->getBucket();
			$auth = $firebase->createAuth();
			$firestore = $firebase->createFirestore();
			$db = $firestore->database();

			// Create Firebase Authentication User
			$userProperties = [
				'email' => $this->input->post('email'),
				'password' => $this->input->post('password'),
				'displayName' => $this->input->post('name')
			];

			$createdUser = $auth->createUser($userProperties);
			$userId = $createdUser->uid; // Get the Firebase UID

			$imageUrl = '';

			// Check if file exists and is valid before uploading
			if (
				isset($_FILES['shop_image']) &&
				$_FILES['shop_image']['error'] === UPLOAD_ERR_OK &&
				is_uploaded_file($_FILES['shop_image']['tmp_name'])
			) {
				// Define file path inside Users/{userId}/
				$file_name = 'Users/' . $userId . '/' . basename($_FILES['shop_image']['name']);

				// Upload file to Firebase Storage
				$uploadedFile = $defaultBucket->upload(
					file_get_contents($_FILES['shop_image']['tmp_name']),
					[
						'name' => $file_name,
						'predefinedAcl' => 'publicRead'
					]
				);

				if ($uploadedFile) {
					$imageUrl = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $file_name;
				} else {
					throw new Exception("File upload failed! Firebase did not return a valid response.");
				}
			}

			// Prepare user data for Firestore
			$userData = [
				'name' => $this->input->post('name'),
				'email' => $this->input->post('email'),
				'categoryId' => $this->input->post('categoryIds') ?? [],
				// 'startDate' => $this->input->post('start_date'),
				'shopTiming' => $this->input->post('shop_timing'),
				'shopLocation' => $this->input->post('shop_location'),
				'lat' => $this->input->post('lat') ?? '',
				'lng' => $this->input->post('lng') ?? '',
				'openingNumber' => $this->input->post('opening_number'),
				'u_image' => $imageUrl,
				'tailorType' => $this->input->post('tailor_type'),
				'userType' => 'tailor',
				'createdAt' => new \Google\Cloud\Core\Timestamp(new \DateTime())
			];

			$tailorType = $this->input->post('tailor_type');
			// Save user data to Firestore with Firebase UID as document ID
			$db->collection('Users')->document($userId)->set($userData);

			// Prepare Tailors data for signup
			$tailorData = [
				'categoryId' => $this->input->post('categoryIds') ?? [],
				'eta' => '', // optional default
				'gender' => ['male' => false, 'female' => false],
				'image' => $imageUrl,
				'isVerified' => false,
				'name' => $this->input->post('name'),
				'state' => $this->input->post('state') ?? '',
				'id' => $userId
			];

			// Set gender based on tailor type
			switch ($tailorType) {
				case "Men's Tailor":
					$tailorData['gender']['male'] = true;
					break;
				case "Women's Tailor":
					$tailorData['gender']['female'] = true;
					break;
				case "Both Men's & Women's Tailor":
					$tailorData['gender']['male'] = true;
					$tailorData['gender']['female'] = true;
					break;
			}

			// Save to Tailers collection
			$db->collection('Tailers')->document($userId)->set($tailorData);


			// **🔥 Automatically log in the user after signup 🔥**
			// $signInResult = $auth->signInWithEmailAndPassword(
			// 	$this->input->post('email'),
			// 	$this->input->post('password')
			// );

			// $my = $signInResult->data();
			// $firebaseToken = $my["idToken"];

			// // Store session
			// $session_data = array(
			// 	'userId' => $userId,
			// 	'name' => $userData["name"],
			// 	'email' => $userData["email"],
			// 	'u_image' => $userData["u_image"],
			// 	'firebaseToken' => $firebaseToken,
			// 	'userType' => $userData["userType"],
			// );

			// $this->session->set_userdata('session_data', $session_data);
			// $this->session->set_userdata('authenthicate', true);

			// Redirect to dashboard/profile page
			$this->session->set_flashdata('successmessage', 'Account created successfully! We are reviewing your account. You will be notified once your account verification is complete.');
			redirect(base_url('login'));

			// redirect(base_url('dashboard'));
		} catch (\Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Registration failed: ' . $e->getMessage());
			$this->session->set_flashdata('form_data', $this->input->post());
			redirect(base_url('login/signup'));
		}
	}

	public function logout()
	{
		// Removing session data
		$sess_array = array('userId' => '');
		$this->session->unset_userdata('session_data', $sess_array);
		$this->session->sess_destroy();
		$this->session->set_flashdata('successmessage', 'Successfully Logged out !');
		redirect(base_url('login'));
	}
}
