<?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"] ){
     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();
}
$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 successfully authenticated.","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() ));
$google_login_content = '';
$client_id = $settings["googleclientid"];
$client_secret = $settings["googleclientsecret"];
$redirect_uri = site_url("");
$settings["google_login"] = json_decode($settings["google_login"], true)["status"];

if ($_SERVER["REQUEST_METHOD"] == "GET" && $settings["google_login"] == "1") {
    // Google One Tap & Sign-In Button
    $google_login_content = '
        <hr>
        <div id="g_id_onload"
             data-client_id="' . htmlspecialchars($client_id, ENT_QUOTES, 'UTF-8') . '"
             data-callback="handleCredentialResponse">
        </div>
        <div class="g_id_signin" data-type="standard"></div>';

    // OAuth 2.0 Client
    $client = new Google\Client();
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->addScope('email');
    $client->addScope('profile');

    // Redirect Login (Button Click)
    if (isset($_GET["login-with-google"])) {
        $auth_url = $client->createAuthUrl();
        header("Location: " . filter_var($auth_url, FILTER_SANITIZE_URL));
        exit();
    }

    // OAuth 2.0 Login Callback (Redirect)
    if (isset($_GET['code'])) {
        $token = $client->fetchAccessTokenWithAuthCode(urldecode($_GET['code']));
        $client->setAccessToken($token['access_token']);
        $oauth2 = new Google\Service\Oauth2($client);
        $userinfo = $oauth2->userinfo->get();
        handleGoogleUser($userinfo, $conn);
    }
}

// Google One Tap (POST Request)
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['google_token'])) {
    $client = new Google\Client(['client_id' => $client_id]); // Verify token
    $payload = $client->verifyIdToken($_POST['google_token']);

    if ($payload) {
        $userinfo = (object)[
            'email' => $payload['email'],
            'name' => $payload['name']
        ];
        handleGoogleUser($userinfo, $conn);
    } else {
        die("Invalid Google token.");
    }
}

// Function to Handle Google User (Login/Signup)
function handleGoogleUser($userinfo, $conn)
{
    $_SESSION['email'] = $userinfo->email;
    $stmt = $conn->prepare("SELECT * FROM clients WHERE email=:email");
    $stmt->execute(["email" => $userinfo->email]);

    if ($stmt->rowCount()) {
        // LOGIN EXISTING USER
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        $update = $conn->prepare("UPDATE clients SET login_date=:date, login_ip=:ip WHERE client_id=:c_id");
        $update->execute([
            "c_id" => $user["client_id"],
            "date" => date("Y-m-d H:i:s"),
            "ip" => GetIP()
        ]);

        // Log the client report
        $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 successfully logged in via Google.",
            "ip" => GetIP(),
            "date" => date("Y-m-d H:i:s")
        ]);
        
    } else {
        // SIGNUP NEW USER
        $username = generateUniqueUsername($userinfo->email, $conn); // Unique username function
        $ref_code = substr(bin2hex(random_bytes(18)), 5, 6);
        $apikey = md5(openssl_random_pseudo_bytes(16));
        $pass = openssl_random_pseudo_bytes(16);
        $secure_token = bin2hex(random_bytes(32)); // Generate Secure Token

        $conn->beginTransaction();
        $insert = $conn->prepare("INSERT INTO clients 
            (name, username, email, password, lang, register_date, login_date, login_ip, apikey, ref_code, email_type, balance, spent, currency_type, secure_token) 
            VALUES (:name, :username, :email, :pass, :lang, :date, :date, :ip, :key, :ref_code, :type, :spent, :spent, :currency_type, :secure_token)");
        $insert->execute([
            "name" => $userinfo->name,
            "username" => $username,
            "email" => $userinfo->email,
            "pass" => md5($pass),
            "lang" => "en",
            "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(),
            "secure_token" => $secure_token
        ]);
        $conn->commit();

        // Fetch the newly created user
        $stmt = $conn->prepare("SELECT * FROM clients WHERE email=:email");
        $stmt->execute(["email" => $userinfo->email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            die("Signup failed. Please try again.");
        }

        // Log the client report for signup
        $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 successfully signed up via Google.",
            "ip" => GetIP(),
            "date" => date("Y-m-d H:i:s")
        ]);
    }

    // Set Session & Cookies
    $_SESSION["msmbilisim_userlogin"] = 1;
    $_SESSION["msmbilisim_userid"] = $user["client_id"];
    $_SESSION["msmbilisim_userpass"] = $user["password"];
    $_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);

    header("Location: " . site_url(""));
    exit();
}

// Function to Generate Unique Username from Email
function generateUniqueUsername($email, $conn)
{
    $base_username = explode("@", $email)[0]; // Email ke @ se pehle ka part
    $username = $base_username;
    $counter = 1;

    while (usernameExists($username, $conn)) {
        $username = $base_username . $counter;
        $counter++;
    }

    return $username;
}

// Function to Check if Username Already Exists
function usernameExists($username, $conn)
{
    $stmt = $conn->prepare("SELECT * FROM clients WHERE username=:username");
    $stmt->execute(["username" => $username]);
    return $stmt->rowCount() > 0;
}





if( $route[1] == "login" && $_POST ){

$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);


$_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( $access["admin_access"] ):
            $_SESSION["msmbilisim_adminlogin"] = 1;
            $_SESSION["login_referrer"] = true;
        endif;
        if( $remember ){
            if($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);
        }
        
        // Prepare the email notification

        // Telegram Notification after successful login
    $chat_id = $row["chat_id"]; // Fetch the user's chat_id stored in the database
    $login_time = $row["login_date"];  // Assuming login_date column stores the time
            $login_ip = $row["login_ip"]; 
    $telegramApiUrl = "https://api.telegram.org/bot" . $settings['telegramusertoken'] . "/sendMessage";
    
    $message = "Hello, $username!\n\n";
$message .= "You have successfully logged into your account.\n\n";
$message .= "Username: $username\n";
$message .= "Date and Time: $login_time\n";
$message .= "IP Address: $login_ip\n\n";
$message .= "If this login was not performed by you, please contact support immediately.\n";
$message .= "\nBest regards,\n{$settings['site_name']}";
    // Send the Telegram message
    $data = [
        'chat_id' => $chat_id,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $telegramApiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $response = curl_exec($ch);
    curl_close($ch);

$to = $row["email"]; // User's email address
$from = $settings["smtp_user"]; 
$fromName = $settings["site_seo"]; 
$replyTo = $settings["admin_mail"];
$subject = "Successful Login Notification - {$settings['site_name']}";
$email_message = "
<html>
<head>
    <title>Successful Login Notification</title>
    <style>
        body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; }
        .container { max-width: 600px; background: #ffffff; padding: 20px; margin: 20px auto; border-radius: 8px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); }
        .header { background-color: #007bff; color: white; padding: 15px; text-align: center; font-size: 20px; font-weight: bold; border-top-left-radius: 8px; border-top-right-radius: 8px; }
        .content { padding: 20px; font-size: 16px; color: #333; }
        .highlight { background: #f8f9fa; padding: 10px; border-radius: 5px; font-size: 18px; font-weight: bold; color: #007bff; }
        .footer { text-align: center; padding: 15px; font-size: 14px; color: #666; border-top: 1px solid #ddd; margin-top: 20px; }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>{$settings['site_name']} Login Alert</div>
        <div class='content'>
            <p>Dear <strong>$username</strong>,</p>
            <p>You have successfully logged into your account.</p>
            <p><strong>Login Details:</strong></p>
            <p class='highlight'>Username: $username</p>
            <p class='highlight'>Date & Time: $login_time</p>
            <p class='highlight'>IP Address: $login_ip</p>
            <p>If this was not you, please <strong>contact support</strong> immediately.</p>
        </div>
        <div class='footer'>
            &copy; " . date("Y") . " {$settings['site_name']} | All rights reserved.
        </div>
    </div>
</body>
</html>";


// Email headers
$headers = "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
$headers .= 'From: '.$fromName.'<'.$from.'>' . "\r\n"; 
$headers .= 'Reply-To: '.$replyTo . "\r\n";



// Send the email
mail($to, $subject, $email_message, $headers);
        $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 successfully authenticated.","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() ));
    }

// Check if 2FA is enabled
            if ($row["two_factor"] == 1) {
                header('Location:' . site_url('2fa-verification'));
                exit();
            } else {
                header('Location:' . site_url(''));
                exit();
            }







} 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["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);

     
    $_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( $access["admin_access"] ):
            $_SESSION["msmbilisim_adminlogin"] = 1;
            $_SESSION["login_referrer"] = true;
        endif;
        if( $remember ){
            if($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);
        }
        // Check if 2FA is enabled
            if ($row["two_factor"] == 1) {
                header('Location:' . site_url('2fa-verification'));
                exit();
            } else {
                header('Location:' . site_url('neworder'));
                exit();
            }
        // Telegram Notification after successful login
    $chat_id = $row["chat_id"]; // Fetch the user's chat_id stored in the database
    $login_time = $row["login_date"];  // Assuming login_date column stores the time
            $login_ip = $row["login_ip"]; 
    $telegramApiUrl = "https://api.telegram.org/bot" . $settings['telegramusertoken'] . "/sendMessage";
    
    $message = "Hello, $username!\n\n";
$message .= "You have successfully logged into your account.\n\n";
$message .= "Username: $username\n";
$message .= "Date and Time: $login_time\n";
$message .= "IP Address: $login_ip\n\n";
$message .= "If this login was not performed by you, please contact support immediately.\n";
$message .= "\nBest regards,\n{$settings['site_name']}Team";
    // Send the Telegram message
    $data = [
        'chat_id' => $chat_id,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $telegramApiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $response = curl_exec($ch);
    curl_close($ch);
 
    $to = $row["email"]; // User's email address
    $from = $settings["smtp_user"]; 
$fromName = $settings["site_seo"]; 
$replyTo = $settings["admin_mail"];
$subject = "Successful Login Notification - {$settings['site_name']}";
$email_message = "
<html>
<head>
    <title>Successful Login Notification</title>
    <style>
        body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; }
        .container { max-width: 600px; background: #ffffff; padding: 20px; margin: 20px auto; border-radius: 8px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); }
        .header { background-color: #007bff; color: white; padding: 15px; text-align: center; font-size: 20px; font-weight: bold; border-top-left-radius: 8px; border-top-right-radius: 8px; }
        .content { padding: 20px; font-size: 16px; color: #333; }
        .highlight { background: #f8f9fa; padding: 10px; border-radius: 5px; font-size: 18px; font-weight: bold; color: #007bff; }
        .footer { text-align: center; padding: 15px; font-size: 14px; color: #666; border-top: 1px solid #ddd; margin-top: 20px; }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>{$settings['site_name']} Login Alert</div>
        <div class='content'>
            <p>Dear <strong>$username</strong>,</p>
            <p>You have successfully logged into your account.</p>
            <p><strong>Login Details:</strong></p>
            <p class='highlight'>Username: $username</p>
            <p class='highlight'>Date & Time: $login_time</p>
            <p class='highlight'>IP Address: $login_ip</p>
            <p>If this was not you, please <strong>contact support</strong> immediately.</p>
        </div>
        <div class='footer'>
            &copy; " . date("Y") . " {$settings['site_name']} | All rights reserved.
        </div>
    </div>
</body>
</html>";


// Email headers
$headers = "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
$headers .= 'From: '.$fromName.'<'.$from.'>' . "\r\n"; 
$headers .= 'Reply-To: '.$replyTo . "\r\n";
// Send the email
mail($to, $subject, $email_message, $headers);
        $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 successfully authenticated.","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() ));
    }


    
} 
}