<?php

defined('BASEPATH') or exit('No direct script access allowed');
header('Content-Type: application/json');

class Auth extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        date_default_timezone_set('Asia/Kolkata');

        // Enable CORS
        header("Access-Control-Allow-Origin: https://mrit-24277.web.app");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        
        // Handle preflight OPTIONS request
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(200);
            exit;
        }
    }

    // * register user
    public function register()
    {
        request_method('POST');

        $request = check_parameter([
            'name' => true,
            'email' => true,
            'password' => true,
            'referral_code' => false,
            'regId' => false
        ]);

        $check_email = $this->cm->search_single_where(['email' => $request['email']], 'users');

        // check already register account 
        if ($check_email) {
            echo json_encode([
                'status' => '0',
                'message' => 'Email address already taken'
            ]);
            exit;
        }


        $referred_by = null;
        if (!empty($request['referral_code'])) {
            // * check referral code 
            $referrer = $this->cm->search_single_where(['referral_code' => $request['referral_code']], 'users');


            if ($referrer) {
                $referred_by = $referrer['id'];

                $tracking = array(
                    'referrer_id' => $referrer['id'],
                    'referee_id' => null,
                    'referral_code' => $referrer['referral_code'],
                    'referrer_type' => $referrer['user_type'],
                    'created_at' => date('Y-m-d H:i:s')
                );
            } else {
                echo json_encode([
                    'status' => '0',
                    'message' => 'Invalid referral code'
                ]);
                exit;
            }
        }

        // register user
        $request['wallet'] = 0;
        $request['password'] = md5($request['password']);
        $request['register'] = '1';
        $request['created_at'] = date('Y-m-d H:i:s');
        $request['referral_code'] = $this->generate_referral_code();
        $request['referred_by'] = $referred_by;


        $register = $this->cm->save_data($request, 'users');
        $user_id = $this->cm->last_id();

        // successful register
        if ($register) {

            $user_token  = $this->cm->get_auth_token();

            $token_data  = array(
                'auth_token' => $user_token,
                'user_id' => $user_id,
                'created_at' => date('Y-m-d H:i:s')
            );

            $register_token = $this->cm->save_data($token_data, 'user_tokens');

            if ($register_token) {

                $user_details = $this->cm->select_single_where('id, name, email, wallet, referral_code, created_at', ['id' => $user_id], 'users');

                $user_details['auth_token'] = $this->cm->search_single_where(['user_id' => $user_id], 'user_tokens')['auth_token'];


                if (isset($referred_by)) {

                    $tracking['referee_id'] = $user_id;

                    $this->cm->save_data($tracking, 'referral_tracking');
                }

                echo json_encode([
                    'status' => '1',
                    'message' => 'Registration successfully',
                    'details' => $user_details
                ]);
                exit;
            }
        }

        echo json_encode([
            'status' => '0',
            'message' => 'Error in registration processs, Please try again',
        ]);
        exit;
    }


    // * login
    public function login()
    {
        request_method('POST');

        $request = check_parameter([
            'email' => true,
            'password' => true,
            'regId' => false
        ]);

        // check email
        $check_email = $this->cm->search_single_where(['email' => $request['email']], 'users');

        if (empty($check_email)) {
            echo json_encode([
                'status' => '0',
                'message' => 'Email Id not registered'
            ]);
            exit;
        }

        if ($check_email['password'] != md5($request['password'])) {
            echo json_encode([
                'status' => '0',
                'message' => 'incorrect password'
            ]);
            exit;
        }

        // If regId is provided, update it in the database
        if (!empty($request['regId'])) {
            $this->cm->update_where(['regId' => $request['regId']], ['id' => $check_email['id']], 'users');
        }

        $user_token  = $this->cm->get_auth_token();

        $token_data = array(
            'user_id' => $check_email['id'],
            'auth_token' => $user_token,
            'created_at' => date('Y-m-d H:i:s')
        );

        $add_token = $this->cm->save_data($token_data, 'user_tokens');

        if ($add_token) {
            $user_details = $this->cm->select_single_where('id, name, email, referral_code, wallet, created_at', ['id' => $check_email['id']], 'users');
            $user_details['auth_token'] = $user_token;

            echo json_encode([
                'status' => '1',
                'message' => 'login successful',
                'details' => $user_details
            ]);
            exit;
        }


        echo json_encode([
            'status' => '0',
            'messsage' => 'login failed , try again'
        ]);
        exit;
    }


    // * social login
    public function social_login()
    {
        request_method('POST');

        $request = check_parameter([
            'name' => true,
            'email' => true,
            'social_id' => true,
            'referral_code' => false,
            'regId' => false
        ]);

        $referred_by = null;
        if (!empty($request['referral_code'])) {
            // * check referral code 
            $referrer = $this->cm->search_single_where(['referral_code' => $request['referral_code']], 'users');


            if ($referrer) {
                $referred_by = $referrer['id'];

                $tracking = array(
                    'referrer_id' => $referrer['id'],
                    'referee_id' => null,
                    'referral_code' => $referrer['referral_code'],
                    'referrer_type' => $referrer['user_type'],
                    'created_at' => date('Y-m-d H:i:s')
                );
            } else {
                echo json_encode([
                    'status' => '0',
                    'message' => 'Invalid referral code'
                ]);
                exit;
            }
        }
        $user_id = 0;
        $message = '';

        $check_social_id = $this->cm->search_single_where(['social_id' => $request['social_id']], 'users');

        // check already register account 
        if ($check_social_id) {

            if (!empty($request['regId'])) {
                $this->cm->update_where(['regId' => $request['regId']], ['id' => $check_social_id['id']], 'users');
            }

            $user_id = $check_social_id['id'];
            $status = '2';
            $message = 'User login succesfull.';
            
        } else {
            
            
            // register user
            $request['wallet'] = 0;
            $request['register'] = '1';
            $request['created_at'] = date('Y-m-d H:i:s');
            $request['referral_code'] = $this->generate_referral_code();
            $request['referred_by'] = $referred_by;
            
            $this->cm->save_data($request, 'users');
            $user_id = $this->cm->last_id();
            $status = '1';
            $message = 'User registeration succesfull.';
        }

        $user_token  = $this->cm->get_auth_token();

        $token_data  = array(
            'auth_token' => $user_token,
            'user_id' => $user_id,
            'created_at' => date('Y-m-d H:i:s')
        );

        $this->cm->save_data($token_data, 'user_tokens');

        $user_details = $this->cm->select_single_where('id, name, email, wallet, referral_code, created_at', ['id' => $user_id], 'users');
        $user_details['auth_token'] = $this->cm->search_single_where(['user_id' => $user_id], 'user_tokens')['auth_token'];

        if (isset($referred_by)) {

            $tracking['referee_id'] = $user_id;

            $this->cm->save_data($tracking, 'referral_tracking');
        }

        echo json_encode([
            'status' => $status,
            'message' => $message,
            'details' => $user_details
        ]);
        exit;
    }


    // * users : forgot password (send forgot password mail)
    public function forgot_password(){

        request_method('GET');

        $request = check_get_parameter(['email' => true]);

        $user = $this->cm->search_single_where(['email' => $request['email']], 'users');
        if(empty($user)){

            echo json_encode([
                "status" => "0",
                "message" => "Email id not found."
            ]);

            // $this->status = '0';
            // $this->message = 'Email not found.';
            exit;
        }

        if($user['register'] == '0'){

            echo json_encode([
                "status" => "0",
                "message" => "Email id not found."
            ]);
            // $this->status = '0';
            // $this->message = 'Email not found.';
            exit; 
            
        }


        $token = get_token(150);

        $check = $this->cm->search_single_where([

            'used' => '0',
            'date' => date('Y-m-d'),
            'user_id' => $user['id']
            
        ], 'user_forgot_password');
        if(empty($check)){

            $this->cm->save_data([

                'user_id' => $user['id'],
                'token' => $token,
                'valid_from' => date('Y-m-d H:i:s'),
                'valid_to' => $this->getDateTimePlusTenMinutes(),
                'date' => date('Y-m-d')
                
            ], 'user_forgot_password');
            
        }else{
            
            $this->cm->update_where([
                
                'token' => $token,
                'valid_from' => date('Y-m-d H:i:s'),
                'valid_to' => $this->getDateTimePlusTenMinutes(),
                'date' => date('Y-m-d')
                
            ], ['id' => $check['id']], 'user_forgot_password');
            
        }

        $email = $this->cm->search_single_where(['id' => '1'], 'mail_cred');

        send_forgot_password_email($user['email'], $email['email'], $email['password'], $email['username'], $token);

        // $this->status = '1';
        // $this->message = 'Mail has been sent to registered email address.';
        
    }


    // ? generate refertral code
    private function generate_referral_code()
    {
        do {
            // Generate a random referral code
            $referral_code = strtoupper(bin2hex(random_bytes(4))); // Example: 8 characters long

            // Check if the generated referral code already exists
            $existing_code = $this->cm->search_single_where(['referral_code' => $referral_code], 'users');
        } while ($existing_code); // Repeat until a unique code is found

        return $referral_code;
    }


    // ? get 10 min ahead time
    private function getDateTimePlusTenMinutes() {
        // Create a DateTime object for the current time
        $dateTime = new DateTime();
    
        // Add 10 minutes
        $dateTime->modify('+10 minutes');
    
        // Return the formatted date and time
        return $dateTime->format('Y-m-d H:i:s'); // Format: YYYY-MM-DD HH:MM:SS
    }
    
}
