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

class Login extends CI_Controller {

    public function __construct()
	{
	    parent::__construct();
	    $this->load->helper('email');  
	    $this->load->helper('date');  
		$this->load->helper('common'); 
		
		$this->output
             ->set_content_type('application/json', 'utf-8')
             ->set_header('Access-Control-Allow-Origin: *')
             ->set_header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE')
             ->set_header('Access-Control-Allow-Headers: Content-Type, Authorization');
		
		$sql =  "SELECT * FROM tbl_api_auth";
		$api_auth= $this->db->get('tbl_api_auth')->row();
		if(isset($_SERVER['PHP_AUTH_USER']) and isset($_SERVER['PHP_AUTH_PW'])){
			if(($_SERVER['PHP_AUTH_USER'] != $api_auth->username) || ($_SERVER['PHP_AUTH_PW'] != $api_auth->password))
			{
				outputJSON(400, 'error', 'Authentication failed');
				return;
			}
	    }else{
			outputJSON(400, 'error', 'Authentication Username and password not set');
			return;
		}

	}
   
    
   public function send_otp()
	{
		if (strtoupper($this->input->method()) !== 'POST') {
			outputJSON(405, 'error', 'Invalid request method. Please use POST.');
			return;
		}
		$input = inputJson();
		$rules = [
			['field' => 'phone', 'label' => 'Mobile Number', 'rules' => 'required|trim|exact_length[10]|numeric']
		];
		checkValidation($input,$rules);
		$phone=$input['phone'];

		$check = $this->db->where('mobile_no', $phone)->where('delete_status', 'false')->get('tbl_user')->num_rows();
		if($check==0){

			$code = $this->db->order_by('user_id', 'DESC')->limit(1)->get('tbl_user')->row();
				
			if (!empty($code)) {
				$prefix = 'User-';
				$string_with_number = $code->user_id;
				if (preg_match('/([a-zA-Z]+)-(\d+)/', $string_with_number, $matches)) {
					$string_part = $matches[1];
					$number_part = $matches[2]; 
					$userrid = (int)$number_part + 1;
					$user_id = $prefix . str_pad($userrid, 8, '0', STR_PAD_LEFT);
				} else {
					$user_id = $prefix . '00000001';
				}
			} else {
				$user_id = $prefix . '00000001';
			}
			$data = [
				'user_id' => $user_id,
				'mobile_no'   => $phone
			];

			$this->db->insert('tbl_user', $data);

			if ($this->db->affected_rows() == 0) {
				outputJSON(200, 'error', 'something went wrong, please try after sometime.');
				return;
			}
			
		}

		$template = $this->db->where(['status'=>0,'type'=>'send_otp'])->get('sms_template')->row();

		if (!$template) {
			outputJSON(200, 'error', 'OTP template not found.');
			return;
		}

		$otp = "123456";
		// $otp = sprintf("%06d", mt_rand(0, 999999));
		$user = $this->db->where('mobile_no', $phone)->get('tbl_user')->row();
		$username = !empty($user->f_name) ? str_replace(' ', '', $user->f_name) : 'User';

		$message = str_replace(
			['mobile_number', 'user_name', 'otp_now'],
			[$phone,$username, $otp],
			$template->body
		);

		$otpData = [
			'phone' => $phone,
			'otp' => $otp,
			'user_id' => 'User',
			'status' => 0 ,
			'added_by_web' => $_SERVER['HTTP_HOST'],
			'updated_at' => date('Y-m-d H:i:s')
		];

		$existingOtp = $this->db->where('phone',$phone)->get('all_otp')->num_rows();

		if ($existingOtp>0) {
			$this->db->update('all_otp', ['otp' => $otp, 'status'=> 0 ,'updated_at' => date('Y-m-d H:i:s')], ['phone' => $phone]);
		} else {
			$this->db->insert('all_otp', $otpData);
		}

		// $result=send_text_msg_new($message);
		// if (!$result) {
		// 	outputJSON(200, 'error', 'Failed to send sms, try again');
		// 	return;
		// }
		outputJSON(200, 'success', 'OTP has been sent successfully',['phone'=>$phone,'otp'=>$otp]);
		return;
	}

    
    public function verify_otp()
	{
		if (strtoupper($this->input->method()) !== 'POST') {
			outputJSON(405, 'error', 'Invalid request method. Please use POST.');
			return;
		}
		$input = inputJson();
		$rules = [
			['field' => 'phone', 'label' => 'Mobile Number', 'rules' => 'required|trim|exact_length[10]|numeric'],
			['field' => 'otp', 'label' => 'OTP', 'rules' => 'required|trim']
		];
		checkValidation($input,$rules);
		$phone=$input['phone'];
		$otp=$input['otp'];

		$check = $this->db->where('mobile_no', $phone)->where('delete_status', 'false')->get('tbl_user')->num_rows();
		if($check==0){
			outputJSON(200, 'error', 'Invalid User mobile number, Record not found.');
			return;
		}

		$otpQuery = "SELECT * FROM all_otp WHERE phone = ? AND otp = ? AND status = 0";
		$otpRecord = $this->db->query($otpQuery, [$phone, $otp])->row();

		if (!$otpRecord) {
			outputJSON(200, 'error', 'Incorrect otp.');
			return;
		}

		$otpTime = strtotime($otpRecord->updated_at);
		$currentTime = time();
		$expiryTime = 10 * 60;

		if (($currentTime - $otpTime) > $expiryTime) {
			outputJSON(200, 'error', 'OTP has expired. Please request a new one.');
			return;
		}

		$this->db->update('all_otp', ['status' => 1], ['phone' => $phone, 'otp' => $otp]);

		$userRecord = $this->db->get_where('tbl_user', ['mobile_no'=>$phone,'delete_status'=>'false'])->row();

	   $response = [
			'id' => $userRecord->id,
			'user_id' => $userRecord->user_id,
			'name' => $userRecord->f_name,
			'email' => $userRecord->email_id,
			'mobile' => $userRecord->mobile_no,
			
		];

		outputJSON(200, 'success', 'Login successfully',$response);
		return;
	}

    
    public function verify_multi_user()
	{
		if (strtoupper($this->input->method()) !== 'POST') {
			outputJSON(405, 'error', 'Invalid request method. Please use POST.');
			return;
		}
		$input = inputJson();
		$rules = [
			['field' => 'phone', 'label' => 'Mobile Number', 'rules' => 'required|trim|exact_length[10]|numeric'],
			['field' => 'name', 'label' => 'Name', 'rules' => 'required'],
			['field' => 'email', 'label' => 'Email', 'rules' => 'required'],
		];
		checkValidation($input,$rules);
		$phone=$input['phone'];

		$check = $this->db->where('mobile_no', $phone)->where('delete_status', 'false')->get('tbl_user')->num_rows();
		if($check==0){
			$code = $this->db->order_by('user_id', 'DESC')->limit(1)->get('tbl_user')->row();
				
			if (!empty($code)) {
				$prefix = 'User-';
				$string_with_number = $code->user_id;
				if (preg_match('/([a-zA-Z]+)-(\d+)/', $string_with_number, $matches)) {
					$string_part = $matches[1];
					$number_part = $matches[2]; 
					$userrid = (int)$number_part + 1;
					$user_id = $prefix . str_pad($userrid, 8, '0', STR_PAD_LEFT);
				} else {
					$user_id = $prefix . '00000001';
				}
			} else {
				$user_id = $prefix . '00000001';
			}
			$data = [
				'user_id' => $user_id,
				'mobile_no'   => $phone,
				'f_name' => $input['name'],
				'email_id' => $input['email'],
			];

			$this->db->insert('tbl_user', $data);

			if ($this->db->affected_rows() == 0) {
				outputJSON(200, 'error', 'something went wrong, please try after sometime.');
				return;
			}
		}

		$userRecord = $this->db->get_where('tbl_user', ['mobile_no'=>$phone,'delete_status'=>'false'])->row();

	   $response = [
			'id' => $userRecord->id,
			'user_id' => $userRecord->user_id,
			'name' => $userRecord->f_name,
			'email' => $userRecord->email_id,
			'mobile' => $userRecord->mobile_no,
			
		];

		outputJSON(200, 'success', 'Verify successfully',$response);
		return;
	}
       
}