<?php
if(!defined('BASEPATH')) {
   die('Direct access to the script is not allowed');
}

if( !route(1) ){
    $route[1] = "login";
}

if( route(1) == "login" ){
    $title .= $pagetitle;
}elseif( route(1) == "register" ){
    $title .= $languageArray["signup.title"];
}

if( ( route(1) == "login" || route(1) == "register") && ($_SESSION["msmbilisim_userlogin"] ?? 0) ){
     header("Location:".site_url());exit();
}
if(route(1) == "neworder" || route(1) == "orders" || route(1) == "tickets" || route(1) == "addfunds" || route(1) == "account" || route(1) == "dripfeeds" || route(1) == "reference" || route(1) == "subscriptions" ) {
    header("Location:".site_url()); exit();
} 
 
 if ($_SESSION['msmbilisim_userlogin'] ?? 0) {
    
    $client_id = $_SESSION['msmbilisim_userid'];
    $stmt = $conn->prepare("SELECT google_login_verified FROM clients WHERE client_id = :client_id");
    $stmt->execute(['client_id' => $client_id]);
    $client = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($client && !empty($client['google_login_verified']) && $client['google_login_verified'] == 1) {
        
        echo '<div class="tooltip5" style="display: inline-block; margin-left: 5px;">
                <i class="fab fa-google" style="color:#DB4437;"></i>
                <span class="tooltiptext5">Google Verified</span>
              </div>';
    }
}
 
 

$google_login_content = '';

$google_login_decoded = json_decode($settings["google_login"] ?? '{}', true);
$settings["google_login"] = $google_login_decoded["status"] ?? '0';

if($_SERVER["REQUEST_METHOD"] == "GET" && $settings["google_login"] == "1"){

$google_login_content = '<br>
<button type="button" id="login-with-google-btn" class="btn btn-block btn-big-primary" onclick="showLoading(this);">
  <i class="fab fa-google" style="font-size: 20px;"></i> Continue with Google
</button>

<script>
  function showLoading(button) {
    button.innerHTML = \'<i class="fas fa-spinner fa-spin"></i> Redirecting...\';
    button.disabled = true;
    setTimeout(() => {
      window.location.href = \'?login-with-google\';
    }, 1000);
  }
</script>';

$google_client_id = $settings["google_client_id"];
$google_client_secret = $settings["google_client_secret"];
$google_client_id = $settings["google_client_id"];
$google_client_secret = $settings["google_client_secret"];
$client = new Google\Client();
$client->setClientId($google_client_id);
$client->setClientSecret($google_client_secret);
$site_url = site_url(); 
$client->setRedirectUri($site_url); 
$client->addScope('email');
$client->addScope('profile');

if(array_key_exists("login-with-google",$_GET)){
$auth_url = $client->createAuthUrl();
header('Location: ' .filter_var($auth_url, FILTER_SANITIZE_URL));
exit();
}


if (isset($_GET['code'])) {
    // Get the access token from Google
    $token = $client->fetchAccessTokenWithAuthCode(urldecode($_GET['code']));
    $client->setAccessToken($token['access_token']);
    
    // Create the Google service object
    $oauth2 = new Google\Service\Oauth2($client);
    $userinfo = $oauth2->userinfo->get();
    $_SESSION['email'] = $userinfo->email;

    // Check if the email already exists in the database
    $check_if_username_exists = $conn->prepare("SELECT * FROM clients WHERE email=:email");
    $check_if_username_exists->execute([
        "email" => $userinfo->email
    ]);

    if ($check_if_username_exists->rowCount()) {
        // If the email already exists, log the user in
        $user = $check_if_username_exists->fetch(PDO::FETCH_ASSOC);

        // Set the session variables for logged in user
        $_SESSION["msmbilisim_userid"] = $user["client_id"];
        $_SESSION["msmbilisim_userpass"] = $user["password"];
        $_SESSION["msmbilisim_userlogin"] = 1;
        $_SESSION["currency_hash"] = $user["currency_type"];

        // Set the cookies for the logged in user
        setcookie("u_id", $user["client_id"], strtotime('+1 days'), '/', null, null, true);
        setcookie("u_password", $user["password"], strtotime('+1 days'), '/', null, null, true);
        setcookie("u_login", 'ok', strtotime('+1 days'), '/', null, null, true);
        setcookie("currency_hash", $user["currency_type"], strtotime('+1 days'), '/', null, null, true);

        // Optionally, you can log the login event
        $insert = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date");
        $insert->execute([
            "c_id" => $user["client_id"],
            "action" => "User Logged in using Google",
            "ip" => GetIP(),
            "date" => date("Y-m-d H:i:s")
        ]);

        // Redirect to the homepage or any other page after login
        header("Location: " . site_url(""));
        exit();
    } else {
        // If the email does not exist, proceed with sign-up
        $username = generateUsername($userinfo->name);
        $ref_code = substr(bin2hex(random_bytes(18)), 5, 6);
        $apikey = md5(openssl_random_pseudo_bytes(16));
        $pass = openssl_random_pseudo_bytes(16);

        $conn->beginTransaction();
        $insert = $conn->prepare("INSERT INTO clients SET 
            name=:name, 
            username=:username, 
            email=:email, 
            password=:pass, 
            lang=:lang, 
            telephone=:phone, 
            register_date=:date, 
            apikey=:key, 
            ref_code=:ref_code, 
            email_type=:type, 
            balance=:spent, 
            spent=:spent, 
            currency_type=:currency_type, 
            google_login_verified=1, 
            login_date=:date, 
            login_ip=:ip
        ");
        $insert->execute([
            "name" => $userinfo->name,
            "username" => $username,
            "email" => $userinfo->email,
            "pass" => md5($pass),
            "lang" => "en",
            "phone" => "",
            "date" => date("Y-m-d H:i:s"),
            "ip" => GetIP(),
            "key" => $apikey,
            "ref_code" => $ref_code,
            "type" => 2,
            "spent" => "0.0000",
            "currency_type" => get_default_currency()
        ]);
        $conn->commit();

        // Retrieve the new user data from the database
        $user = $conn->prepare("SELECT * FROM clients WHERE email=:email");
        $user->execute([
            "email" => $userinfo->email
        ]);
        $user = $user->fetch(PDO::FETCH_ASSOC);

        // Insert into client_report for the new user
        $insert = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date");
        $insert->execute([
            "c_id" => $user["client_id"],
            "action" => "User Signed up using Google",
            "ip" => GetIP(),
            "date" => date("Y-m-d H:i:s")
        ]);

        // Set session variables and cookies for the new user
        $_SESSION["msmbilisim_userid"] = $user["client_id"];
        $_SESSION["msmbilisim_userpass"] = $user["password"];
        $_SESSION["msmbilisim_userlogin"] = 1;
        $_SESSION["currency_hash"] = $user["currency_type"];

        setcookie("u_id", $user["client_id"], strtotime('+1 days'), '/', null, null, true);
        setcookie("u_password", $user["password"], strtotime('+1 days'), '/', null, null, true);
        setcookie("u_login", 'ok', strtotime('+1 days'), '/', null, null, true);
        setcookie("currency_hash", $user["currency_type"], strtotime('+1 days'), '/', null, null, true);

        // Redirect to the homepage or any other page after successful sign-up
        header("Location: " . site_url(""));
        exit();
    }
}




}





$error = 0;
$errorText = '';
if( ($route[1] ?? '') == "login" && $_POST ){
if (hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    
    } else {
        
        die("Invalid CSRF token");
    }
$username       = $_POST["username"];
$mail = "@";
// Test if string contains the word 

$username       = $_POST["username"];
    $username = strip_tags($username);
    $username = filter_var($username, FILTER_SANITIZE_STRING);
    $pass           = $_POST["password"];
    $captcha        = $_POST['g-recaptcha-response'];
    $remember       = $_POST["remember"];
    $googlesecret   = $settings["recaptcha_secret"];
 $captcha_control= file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$googlesecret&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
 $captcha_control= json_decode($captcha_control);


if(strpos($username, $mail) == false){

    if( $settings["recaptcha"] == 2 && $captcha_control->success == false && $_SESSION["recaptcha"]  ){
        $error      = 1;
        $errorText  = $languageArray["error.signin.recaptcha"];
        if( $settings["recaptcha"] == 2 ){ $_SESSION["recaptcha"]  = true; }
    }elseif( !userdata_check("username",$username) ){
        $error      = 1;
        $errorText  = $languageArray["error.signin.username"];
        if( $settings["recaptcha"] == 2 ){ $_SESSION["recaptcha"]  = true; }
}elseif( !userdata_check("password",md5($pass)) ){
        $error      = 1;
        $errorText  = $languageArray["error.signin.notmatch"];
        if( $settings["recaptcha"] == 2 ){ $_SESSION["recaptcha"]  = true; }
    }elseif( countRow(["table"=>"clients","where"=>["username"=>$username,"client_type"=>1]]) ){
        $error      = 1;
        $errorText  = $languageArray["error.signin.deactive"];
        if( $settings["recaptcha"] == 2 ){ $_SESSION["recaptcha"]  = true; }
    }else{
        $row    = $conn->prepare("SELECT * FROM clients WHERE username=:username && password=:password ");
        $row  -> execute(array("username"=>$username,"password"=>md5($pass) ));
        $row    = $row->fetch(PDO::FETCH_ASSOC);
        $access = json_decode($row["access"],true);

// Check if email verification is required and user is not verified
if ($settings["email_confirmation"] == 1 && ($row["email_verified"] ?? 0) == 0) {
    $otp = generateOtp();
    $otpExpiryMin = $settings["otp_expiry_minutes"] ?? 10;
    storeOtp($conn, $row["client_id"], $otp, $otpExpiryMin);
    sendOtpEmail($row["email"], $otp, $settings["site_name"], $settings["smtp_user"], $otpExpiryMin);
    $_SESSION["otp_verify_client_id"] = $row["client_id"];
    $_SESSION["otp_verify_email"] = maskEmail($row["email"]);
    $_SESSION["otp_resend_cooldown"] = time();
    Header("Location:" . site_url("verify_otp"));
    exit();
}

$_SESSION["msmbilisim_userlogin"] = 1;
$_SESSION["msmbilisim_userid"] = $row["client_id"];
$_SESSION["msmbilisim_userpass"]       = md5($pass);
$_SESSION["recaptcha"]= false;
$update = $conn->prepare("UPDATE clients SET broadcast_id=:bid WHERE client_id=:cid");
$update->execute(array(
"bid" => 0,
"cid" => $row["client_id"]
));
$currency_hash = get_currency_hash_by_code(get_default_currency());

$_SESSION["currency_hash"] = $currency_hash;

        if( is_array($access) && !empty($access["admin_access"]) ):
            $_SESSION["msmbilisim_adminlogin"] = 1;
            $_SESSION["login_referrer"] = true;
        endif;
        if( $remember ){
            if(is_array($access) && !empty($access["admin_access"])):
                setcookie("a_login", 'ok', strtotime('+28 days'), '/', null, null, true);
            endif;
            setcookie("u_id", $row["client_id"], strtotime('+28 days'), '/', null, null, true);
            setcookie("u_password", $row["password"], strtotime('+28 days'), '/', null, null, true);
            setcookie("u_login", 'ok', strtotime('+28 days'), '/', null, null, true);
            setcookie("currency_hash",$currency_hash,strtotime('+28 days'),'/',null,null,true);
        }else{
            setcookie("u_id", $row["client_id"], strtotime('+7 days'), '/', null, null, true);
            setcookie("u_password", $row["password"], strtotime('+7 days'), '/', null, null, true);
            setcookie("u_login", 'ok', strtotime('+7 days'), '/', null, null, true );
            setcookie("currency_hash",$currency_hash,strtotime('+7 days'),'/',null,null,true);
        }
        
        header('Location:'.site_url(''));
        $insert = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
        $insert->execute(array("c_id"=>$row["client_id"],"action"=>"User Logged in.","ip"=>GetIP(),"date"=>date("Y-m-d H:i:s") ));
        $update = $conn->prepare("UPDATE clients SET login_date=:date, login_ip=:ip WHERE client_id=:c_id ");
        $update->execute(array("c_id"=>$row["client_id"],"date"=>date("Y.m.d H:i:s"),"ip"=>GetIP() ));
    }









} else {


$row    = $conn->prepare("SELECT * FROM clients WHERE email=:username && password=:password ");
        $row  -> execute(array("username"=>$username,"password"=>md5($pass) ));
        $row    = $row->fetch(PDO::FETCH_ASSOC);
$usersname  =  $row ? $row["username"] : '';

if( $settings["recaptcha"] == 2 && $captcha_control->success == false && $_SESSION["recaptcha"]  ){
        $error      = 1;
        $errorText  = $languageArray["error.signin.recaptcha"];
        if( $settings["recaptcha"] == 2 ){ $_SESSION["recaptcha"]  = true; }
    }elseif( !userdata_check("email",$username) ){
        $error      = 1;
        $errorText  = $languageArray["error.signin.username"];
        if( $settings["recaptcha"] == 2 ){ $_SESSION["recaptcha"]  = true; }
    }elseif( !userdata_check("password", md5($pass) ) ){
        $error      = 1;
        $errorText  = $languageArray["error.signin.notmatch"];
        if( $settings["recaptcha"] == 2 ){ $_SESSION["recaptcha"]  = true; }
    }elseif( countRow(["table"=>"clients","where"=>["username"=>$username,"client_type"=>1]]) ){
        $error      = 1;
        $errorText  = $languageArray["error.signin.deactive"];
        if( $settings["recaptcha"] == 2 ){ $_SESSION["recaptcha"]  = true; }
    }else{
        $row    = $conn->prepare("SELECT * FROM clients WHERE email=:username && password=:password ");
        $row  -> execute(array("username"=>$username,"password"=>md5($pass) ));
        $row    = $row->fetch(PDO::FETCH_ASSOC);
        $access = json_decode($row["access"],true);

// Check if email verification is required and user is not verified
if ($settings["email_confirmation"] == 1 && ($row["email_verified"] ?? 0) == 0) {
    $otp = generateOtp();
    $otpExpiryMin = $settings["otp_expiry_minutes"] ?? 10;
    storeOtp($conn, $row["client_id"], $otp, $otpExpiryMin);
    sendOtpEmail($row["email"], $otp, $settings["site_name"], $settings["smtp_user"], $otpExpiryMin);
    $_SESSION["otp_verify_client_id"] = $row["client_id"];
    $_SESSION["otp_verify_email"] = maskEmail($row["email"]);
    $_SESSION["otp_resend_cooldown"] = time();
    Header("Location:" . site_url("verify_otp"));
    exit();
}

    $_SESSION["msmbilisim_userlogin"]      = 1;
        $_SESSION["msmbilisim_userid"]         = $row["client_id"];
        $_SESSION["msmbilisim_userpass"]       = md5($pass);
        $_SESSION["recaptcha"]                = false;
        $update = $conn->prepare("UPDATE clients SET broadcast_id=:bid WHERE client_id=:cid");
$update->execute(array(
"bid" => 0,
"cid" => $row["client_id"]
));
$currency_hash = get_currency_hash_by_code(get_default_currency());

$_SESSION["currency_hash"] = $currency_hash;
        if( is_array($access) && !empty($access["admin_access"]) ):
            $_SESSION["msmbilisim_adminlogin"] = 1;
            $_SESSION["login_referrer"] = true;
        endif;
        if( $remember ){
            if(is_array($access) && !empty($access["admin_access"])):
                setcookie("a_login", 'ok', strtotime('+7 days'), '/', null, null, true);
            endif;
            setcookie("u_id", $row["client_id"], strtotime('+7 days'), '/', null, null, true);
            setcookie("u_password", $row["password"], strtotime('+7 days'), '/', null, null, true);
            setcookie("u_login", 'ok', strtotime('+7 days'), '/', null, null, true);
        }else{
            setcookie("u_id", $row["client_id"], strtotime('+7 days'), '/', null, null, true);
            setcookie("u_password", $row["password"], strtotime('+7 days'), '/', null, null, true);
            setcookie("u_login", 'ok', strtotime('+7 days'), '/', null, null, true );
            setcookie("currency_hash",$currency_hash,strtotime('+7 days'),'/',null,null,true);
        }
        
        header('Location:'.site_url(''));
        $insert = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
        $insert->execute(array("c_id"=>$row["client_id"],"action"=>"User Logged in.","ip"=>GetIP(),"date"=>date("Y-m-d H:i:s") ));
        $update = $conn->prepare("UPDATE clients SET login_date=:date, login_ip=:ip WHERE client_id=:c_id ");
        $update->execute(array("c_id"=>$row["client_id"],"date"=>date("Y.m.d H:i:s"),"ip"=>GetIP() ));
    }


    
} 
}

     