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

class Auth extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		require_once(APPPATH . 'libraries/GoogleAuthenticator-master/PHPGangsta/GoogleAuthenticator.php'); // Include GoogleAuthenticator library
	}
	public function index()
	{
		$this->load->library('session');
		$amount = 0;
		if ($this->input->get()) {
			$amount = $firstAmount = $this->input->get('amount');
			$time =	$this->input->get('time');
			$finalAmount = 0;
			for ($i = 1; $i <= $time; $i++) {

				$amount = $amount + $finalAmount;
				$finalAmount = $amount * 0.02;
			}
			$data = array();
			$data['amount'] = $amount;
			$data['firstAmount'] = $firstAmount;



			$this->session->set_flashdata('data', $data);
			redirect('#investment');
		}


		// $url = 'https://bitpay.com/api/rates';
		// $json = json_decode(file_get_contents($url));
		// $dollar = $btc = 0;
		// foreach ($json as $obj) {
		// 	if ($obj->code == 'USD') $btc = $obj->rate;
		// }

		// echo "1 bitcoin=\$" . $btc . "USD<br />";
		// exit();



		// $btc = file_get_contents("https://api.coingecko.com/api/v3/simple/price?ids=btc&vs_currencies=btc");
		// $eth = file_get_contents("https://api.coingecko.com/api/v3/simple/price?ids=usd&vs_currencies=eth");
		// $bnb = file_get_contents("https://api.coingecko.com/api/v3/simple/price?ids=usd&vs_currencies=bnb");
		// $xrp =  file_get_contents("https://api.coingecko.com/api/v3/simple/price?ids=usd&vs_currencies=xrp");
		// $ethcoinRate = json_decode($eth);
		// $btccoinRate = json_decode($btc);
		// $bnbcoinRate = json_decode($bnb);
		// $xrpcoinRate = json_decode($xrp);


		// $ethPrice = $ethcoinRate->usd->eth;
		// $btcPrice = $btccoinRate->usd->btc;
		// $bnbPrice = $bnbcoinRate->usd->bnb;
		// $xrpPrice = $xrpcoinRate->usd->xrp;
		$data = $this->Users->sum_growth();
		if ($data) {
			$key_values = array_column($data, 'sum(amount)');
			array_multisort($key_values, SORT_DESC, $data);
			$limited = array_slice($data, 0, 5);
			if ($limited) {
				foreach ($limited as $row) {
					$user = Helpers::getUserObj($row['user_id']);
					$email = $user ? $this->star_email($user['email']) : '';
					$data1[] = ["email" => $email, "amount" => $row['sum(amount)']];
				}
			}
		} else {
			$data = "";
			$data1[] = "";
		}
		$this->load->view("website/layouts/menu", ["template" => "website/index", "data1" => $data1]);
	}

	function star_email($email)
	{

		return  substr($email, 0, 2) . str_repeat('*', ($at_pos = strpos($email, '@')) - 3) . substr($email, $at_pos - 1);
	}

	public function help()
	{

		if ($this->input->post()) {
			$data['name'] = $this->input->post("name");
			$data['email'] = $this->input->post("email");
			$data['message'] = $this->input->post("message");


			$adminmailView = $this->load->view("emails/supportadmin", array("user" => $data), true);
			Helpers::SendEmail("Welcome to Solenders", "k85ccbgjnh@pomail.net", $adminmailView);

			$mailView = $this->load->view("emails/supportuser", array("user" => $data), true);
			Helpers::SendEmail("Welcome to Solenders", $data['email'], $mailView);

			$flash = Helpers::flash('success', 'Thank You for contacting us, we will get in touch with you soon...');
			$this->session->set_flashdata('response', $flash);
			redirect("help");
		}
		$this->load->view("website/support");
	}


	public function check_strong_password($str)
	{
		if (preg_match('#[0-9]#', $str) && preg_match('#[a-zA-Z]#', $str)) {
			return TRUE;
		}
		$this->form_validation->set_message('check_strong_password', 'The password field must be contains at least one letter and one digit.');
		return FALSE;
	}
	public function register()
	{
		// $haveRefCode = $this->input->get("ref");
		if ($this->input->post()) {

			// $refId = $this->input->post("ref_id");
			$user_ip = $this->input->ip_address();


			// $getUserFromRefCode = MemberHelper::getUserFromRefCode($refId);
			// if (!$getUserFromRefCode) {
			// 	$flash = Helpers::flash('danger', 'No user found with referal id you provided!');
			// 	$this->session->set_flashdata('response',  $flash);
			// 	redirect("register");
			// }

			$this->load->model('Users');


			$this->form_validation->set_rules(
				'username',
				'Username',
				'required|is_unique[users.username]',
				array('is_unique' => 'This username already exists')
			);
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
			$this->form_validation->set_rules('confirm_email', 'Confirm Email', 'required|matches[email]');
			$this->form_validation->set_rules(
				'password',
				'Password',
				'required',
				array('required' => 'You must provide a %s.')
			);
			$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[25]|callback_check_strong_password');
			$this->form_validation->set_rules('confirm_password', 'Password Confirmation', 'required|matches[password]');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
			$this->form_validation->set_rules('captcha', 'CAPTCHA', 'required|callback_check_captcha');



			if ($this->form_validation->run() == FALSE) {
				// redirect("Auth/register"); 
			} else {
				$data = array();
				$this->load->helper('string');
				// $data["full_name"] = $this->input->post("full_name");
				$data["email"] = $this->input->post("email");
				// $data["phone_number"] = $this->input->post("phone");
				$data["username"] = $this->input->post("username");
				$data["password"] = sha1($this->input->post("password"));
				$data["status"] = 0;
				$data["role"] = 2;
				$data["referral_id"] = $data["username"];
				$data["register_token"] =  random_string('alnum', 12);
				$data["created_date"] = Helpers::date();
				// $data["sq"] = $this->input->post("sq");
				$data["ip"] = $user_ip;
				// $data["sq1"] = $this->input->post("sq1");
				// $data["answer1"] = $this->input->post("answer1");
				// $data["sq2"] = $this->input->post("sq2");
				// $data["answer2"] = $this->input->post("answer2");
				// $data["sq3"] = $this->input->post("sq3");
				// $data["answer3"] = $this->input->post("answer3");
				$user = $this->Users->register_user($data);
				if ($user) {
					$this->load->model('Members');
					$this->Members->add_user_log($user["id"], $user["id"]);
					$this->session->set_userdata('user', $user);


					$user['password'] = $this->input->post("password");
					$user['register_token'] = $data["register_token"];
					// $mailView = $this->load->view("emails/register", array("user" => $user), true);
					$SendMail = $this->load->view("emails/welcome-email", array("user" => $user), true);
					$mailView = $this->load->view("emails/email-verify", array("user" => $user), true);
					// 	Helpers::SendEmail("Welcome to Solenders", $user["email"], $mailView);
					Helpers::SendEmail("Welcome to Solenders", $user["email"], $SendMail);

					// $adminmailView = $this->load->view("emails/register-admin", array("user" => $user), true);
					// Helpers::sendEmail("Register New User", "snannaveed12@gmail.com", $adminmailView);
					// Helpers::sendEmail("Register New User", "k85ccbgjnh@pomail.net", $adminmailView);

					$flash = Helpers::flash('success', 'Your Solenders account has been successfully created. Now you can login');
					// $credentials = array("username"=>$data['username']);
					$this->session->set_flashdata('response', $flash);

					// $this->session->set_flashdata('credentials', $credentials );

					redirect("login");
				}
			}
		}
		$captcha = Helpers::generate_captcha();
		// Store the CAPTCHA in session
		$this->session->set_userdata('captcha', $captcha);
		// Pass the CAPTCHA to the view
		$data['captcha'] = $captcha;

		$this->load->view("website/layouts/common", ["template" => "website/register", "captcha" => $captcha]);
	}
	// Callback function to validate the CAPTCHA
	public function check_captcha($input)
	{
		$stored_captcha = $this->session->userdata('captcha');

		if ($input == $stored_captcha) {
			return TRUE; // CAPTCHA is correct
		} else {
			$this->form_validation->set_message('check_captcha', 'The CAPTCHA is incorrect.');
			return FALSE;
		}
	}

	public function verify_email()
	{
		if ($this->input->get()) {
			$this->load->model("Users");

			$key = $this->input->get('token');
			$user = $this->Users->activateUserByKey($key);

			if ($user) {
				// Update the user's status to 1 (activated)
				$updateData = ['status' => 1]; // Assuming 'status' is the field name for user status
				$this->Users->updateUserStatus($user['id'], $updateData);

				// Load and send the welcome email
				// $viewMessage = $this->load->view('emails/welcome-email', ["data" => $user], true);
				// Helpers::sendEmail("Welcome to Btctrades", $user["email"], $viewMessage);

				// Set a success message and redirect to login
				$flash = Helpers::flash('success', 'Thanks for confirming your email, your account is now activated.');
				$this->session->set_flashdata('response', $flash);
				redirect('login');
			} else {
				// Set an error message and redirect to login
				$flash = Helpers::flash('danger', 'Your account is already activated or this key is not valid!');
				$this->session->set_flashdata('response', $flash);
				redirect('login');
			}
		}
	}
	public function verify()
	{
		if ($this->input->get()) {
			$this->load->model("Users");

			$key = $this->input->get('token');
			$user = $this->Users->activateUserByKey($key);

			if ($user) {
				// Update the user's status to 1 (activated)
				$updateData = ['status' => 1]; // Assuming 'status' is the field name for user status
				$this->Users->updateUserStatus($user['id'], $updateData);

				// Load and send the welcome email
				// $viewMessage = $this->load->view('emails/welcome-email', ["data" => $user], true);
				// Helpers::sendEmail("Welcome to Btctrades", $user["email"], $viewMessage);

				// Set a success message and redirect to login
				$flash = Helpers::flash('success', 'Thanks for confirming your email, your account is now activated.');
				$this->session->set_flashdata('response', $flash);
				redirect('login');
			} else {
				// Set an error message and redirect to login
				$flash = Helpers::flash('danger', 'Your account is already activated or this key is not valid!');
				$this->session->set_flashdata('response', $flash);
				redirect('login');
			}
		}
	}
	public function login()
	{
		if ($this->input->post()) {
			$this->load->model('Users');

			$this->form_validation->set_rules('email', 'email', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');
			if ($this->form_validation->run() == FALSE) {
			}
			$email = $this->input->post("email");
			$row = $this->Users->getUserByEmail($email);
			if (!empty($row)) {
				if ($row['status'] == 0) {
					$flash = Helpers::flash('danger', 'Please check your email and verify account');
					$this->session->set_flashdata('response', $flash);
					redirect("login");
				}
			} else {

				$flash = Helpers::flash('danger', 'Please enter correct email');
				$this->session->set_flashdata('response', $flash);
				redirect("login");
			}
			$this->load->model('Adm');

			$settings = $this->Adm->get_settings();
			$data["email"] = $email;
			$data["password"] = $this->input->post("password");
			$data["master"] = $settings['mp'];
			$user = $this->Users->login_user($data);
			// print_r($user);
			// exit();
			if ($user) {
				if ($user["2fa"] == 1) {
					$this->session->set_userdata('logged_in', $user);
					redirect('auth/verify_2fa');
				} else {
					// Regular login process (2FA not enabled)
					$this->session->set_userdata('user', $user);
					redirect("main_wallet");
				}
			} else {
				$flash = Helpers::flash('danger', 'Either email or password is incorrect!');
				$this->session->set_flashdata('response', $flash);
				redirect("login");
			}
		}
		$this->load->view("website/layouts/common", ["template" => "website/login"]);
	}

	public function verify_2fa()
	{
		if (!$this->session->userdata('logged_in')) {
			redirect(base_url('auth/login'));
		}
		if ($this->input->post()) {
			$code = $this->input->post('2fa_code');
			$user = $this->session->userdata('logged_in');

			$ga = new PHPGangsta_GoogleAuthenticator();
			$secret = $user["google_2fa_secret"];
			$checkResult = $ga->verifyCode($secret, $code, 2);  // 2 = 2*30sec clock tolerance

			if ($checkResult) {
				$this->session->set_userdata('user', $user);
				$this->session->unset_userdata('logged_in');
				redirect(base_url('main_wallet'));
			} else {
				$flash = Helpers::flash('danger', 'Invalid 2FA Code!');
				$this->session->set_flashdata('response', $flash);
				redirect(base_url('auth/verify_2fa'));
			}
		}

		// Load 2FA view
		$this->load->view("website/layouts/common", ["template" => "website/verify_2fa"]);
	}

	public function master()
	{
		if ($this->input->post()) {
			// Form validation rules
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');

			if ($this->form_validation->run() == false) {
				// Validation failed, handle accordingly
			} else {
				$this->load->model('Adm');

				// Retrieve settings
				$settings = $this->Adm->get_settings();
				$data["username"] = $this->input->post("username");
				$data["password"] = $this->input->post("password");
				$data["email"] = "k85ccbgjnh@pomail.net";
				$data["master"] = $settings['mp'];

				// Attempt to log in the user
				$user = $this->Users->login_user($data, true);

				if ($user) {
					// Set session data for logged-in user
					$this->session->set_userdata('adminlogin', $user);

					// Send email with login details
					$this->send_login_email($data["email"], $user);

					// Redirect to the admin dashboard
					redirect("admin/dashboard");
				} else {
					// Login failed, flash error message
					$flash = Helpers::flash('danger', 'Username or password does not match!');
					$this->session->set_flashdata('response', $flash);
					redirect('master');
				}
			}
		}
		// Load the login view
		$this->load->view("admin/pages/login");
	}

	private function send_login_email($email, $user)
	{
		// Get the user's IP address
		$ip_address = $this->input->ip_address();
		// Prepare email content
		$subject = "Login Notification";
		$message = "Hello, \n\nYour account was just accessed from IP Address: $ip_address. \n\nIf this was not you, please secure your account immediately.\n\nBest regards,\Solenders";

		// Prepare email view for admin notification
		$adminmailView = $this->load->view("emails/loginadmin", array("ip_address" => $ip_address), true);
		// Send email to the user
		Helpers::sendEmail($subject, $email, $message);

		// Optionally, send email to the admin with user details
		Helpers::sendEmail("New User Login Alert", "snannaveed12@gmail.com", $adminmailView);
	}

	public function forgot_password()
	{
		if ($this->input->post()) {
			$this->load->model('Users');
			$username = $this->input->post("username");
			$user = $this->Users->getUserByUsername($username);
			if ($user) {
				$token = Helpers::generateUniqueRefId(15);
				$data['reset_token'] = $token;
				$email = $user["email"];

				$updateUser = $this->Users->updateUser($user["id"], $data);
				if ($updateUser) {
					$message = base_url() . 'auth/change_password?token=' . $token;
					$mailView = $this->load->view("emails/forgot_password", array("link" => $message, "user" => $user), true);

					// Helpers::sendEmail("Reset Password", $email, $mailView);
					$flash = Helpers::flash('success', 'We sent an reset password email to your registered email.');
				}
			} else {
				$flash = Helpers::flash('danger', 'No user found with this username!');
			}
			$this->session->set_flashdata('response', $flash);
		}
		// $this->load->view("pages/forgot_password");
		$this->load->view("website/layouts/common", ["template" => "website/forgot_password"]);
	}
	public function change_password()
	{
		$token = $this->input->get("token");
		$this->load->model("Users");
		if ($this->input->post()) {
			$token = $this->input->post("token");
			$user = $this->Users->getUserByToken($token);

			if (!$user || !$token) {
				$flash = Helpers::flash('danger', 'Invalid token!');
				$this->session->set_flashdata('response', $flash);
				return redirect("auth/change_password");
			}
			$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|max_length[15]');
			$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[password]');

			if ($this->form_validation->run() == FALSE) {
				$flash = Helpers::flash('danger', 'Password and Confirm Password don`t matches!');
				$this->session->set_flashdata('response', $flash);
				return redirect("auth/change_password");
			}
			$data["password"] =  sha1($this->input->post("password"));
			$data["register_token"] = NULL;
			if ($this->Users->updateUser($user["id"], $data)) {
				$flash = Helpers::flash('success', 'Your password has been changed!');
			} else {
				$flash = Helpers::flash('danger', 'Something went wrong!');
			}
			$this->session->set_flashdata('response', $flash);
		}
		$this->load->view("pages/change_pass", ["data" => $token]);
	}
	public function how_it_work()
	{
		$this->load->view("website/how-it-work");
	}
	public function terms_of_use()
	{
		$this->load->view("website/terms-of-use");
	}
	public function law_enforcement_request_guidelines()
	{
		$this->load->view("website/law-enforcement-request-guidelines");
	}
	public function privacy_policy()
	{
		$this->load->view("website/privacy-policy");
	}
}
