<?php
use PragmaRX\Google2FA\Google2FA;

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

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
 
 
if ($_POST) {
    
    
     if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("CSRF Token validation failed!");
    } else { 
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); 
    }
    
    
    // Post data retrieval
    $username = $_POST["username"];
    $pass = $_POST["password"];
    $captcha = $_POST['g-recaptcha-response'];
    $remember = $_POST["remember"];
    $two_factor_code = htmlspecialchars($_POST["two_factor_code"]);
    $googlesecret = $settings["recaptcha_secret"];

    // ReCaptcha validation
    $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);

    // ReCaptcha failure handling
    if ($settings["recaptcha"] == 2 && $captcha_control->success == false && $_SESSION["recaptcha"]) {
        $error = 1;
        $errorText = "Please verify that you are not a robot.";
        $_SESSION["recaptcha"] = true;
    } elseif (countRow(["table" => "admins", "where" => ["username" => $username, "client_type" => 1]])) {
        // Username does not exist
        $error = 1;
        $errorText = "Incorrect username or password.";  // Generic error message
        $_SESSION["recaptcha"] = true;
    } else {
        // Fetch admin data
        $admin = $conn->prepare("SELECT * FROM admins WHERE username=:username");
        $admin->execute(array("username" => $username));
        $admin = $admin->fetch(PDO::FETCH_ASSOC);







        // If user exists, check password
        if ($admin && password_verify($pass, $admin["password"])) {
            
             // Step 1: Check IP security (if enabled)
    if ($admin["ip_type"] == 2) { // If IP security is enabled
        $current_ip = $_SERVER['REMOTE_ADDR']; // Get current user IP
        $allowed_ip = $admin["ip"]; // Fetch allowed IP from database

        // Check if current IP matches the allowed IP
        if ($current_ip !== $allowed_ip) {
            die("Unauthorized IP address. You cannot access this account from this IP: {$current_ip}.");
        }
    }
            
            $access = json_decode($admin["access"], true);
            $_SESSION["msmbilisim_adminslogin"] = 1;
            $_SESSION["msmbilisim_adminid"] = $admin["admin_id"];
            $_SESSION["msmbilisim_adminpass"] = $pass;
            $_SESSION["recaptcha"] = false;

            if ($access["admin_access"]) {
                // Two-factor authentication check
                if ($admin["two_factor"] == 1) {
                     // Check if the two-factor code is empty
    if (empty($two_factor_code)) {
      $errorText = "Unauthorized IP address. You cannot access this account from this IP: {$current_ip}."; 
    }
                    $google2fa = new Google2FA();
                    $is_valid = $google2fa->verifyKey($admin["two_factor_secret_key"], $two_factor_code);
                }

                if ($admin["two_factor"] == 1 && $is_valid == true) {
    $_SESSION["msmbilisim_adminslogin"] = 1;
    $_SESSION["msmbilisim_adminid"] = $admin["admin_id"];
    $_SESSION["msmbilisim_adminpass"] = $pass;

    // Log admin login to the admin_report table
    $insert_report = $conn->prepare("
        INSERT INTO admin_report (admin_id, action, report_ip, report_date)
        VALUES (:admin_id, :action, :report_ip, :report_date)
    ");
    $insert_report->execute(array(
        "admin_id" => $admin["admin_id"],
        "action" => "Admin logged in",
        "report_ip" => GetIP(),
        "report_date" => date("Y-m-d H:i:s")
    ));

    // সফল লগইনের ইমেইল পাঠানো
    if ($settings["alert_adminlogin"] == "2") {
        $subject = "✅ Admin Login Successful";
        $msg = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; background-color: #f9f9f9; margin: 0; padding: 0; }
                .email-container { max-width: 600px; margin: 20px auto; background-color: #ffffff; border: 1px solid #ddd; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); }
                .header { background-color: #28a745; color: #ffffff; padding: 15px; text-align: center; font-size: 18px; font-weight: bold; }
                .content { padding: 20px; color: #333; font-size: 14px; }
                .footer { text-align: center; padding: 15px; font-size: 12px; color: #888; background-color: #f9f9f9; }
            </style>
        </head>
        <body>
            <div class='email-container'>
                <div class='header'>✅ Admin Login Successful</div>
                <div class='content'>
                    <p>Hello <b>" . htmlspecialchars($admin["username"]) . "</b>,</p>
                    <p>You have successfully logged into the admin panel. Here are the details:</p>
                    <p><b>IP Address:</b> " . $_SERVER['REMOTE_ADDR'] . "</p>
                    <p><b>Login Time:</b> " . date("Y-m-d H:i:s") . "</p>
                </div>
                <div class='footer'>This is an automated message from " . htmlspecialchars($settings["site_name"]) . ". Please do not reply.</div>
            </div>
        </body>
        </html>";
        sendMail(["subject" => $subject, "body" => $msg, "mail" => $settings["admin_mail"]]);
    }

    // Set cookies for admin session
    setcookie("a_login", 'ok', time() + (60 * 60 * 24 * 7), '/', null, null, true);
    setcookie("a_id", $admin["admin_id"], time() + (60 * 60 * 24 * 7), '/', null, null, true);
    setcookie("a_password", $admin["password"], time() + (60 * 60 * 24 * 7), '/', null, null, true);

    header('Location: ' . site_url('admin'));
    exit();
} else {
    $_SESSION["msmbilisim_adminslogin"] = 1;
    $_SESSION["msmbilisim_adminid"] = $admin["admin_id"];
    $_SESSION["msmbilisim_adminpass"] = $pass;
 
 

    // Set cookies for admin session
    setcookie("a_login", 'ok', time() + (60 * 60 * 24 * 7), '/', null, null, true);
    setcookie("a_id", $admin["admin_id"], time() + (60 * 60 * 24 * 7), '/', null, null, true);
    setcookie("a_password", $admin["password"], time() + (60 * 60 * 24 * 7), '/', null, null, true);
}

    // Redirect to activate 2FA page
    header('Location: ' . site_url('admin'));
    exit();
}

                // Update last login details
                $update = $conn->prepare("UPDATE admins SET login_date=:date, login_ip=:ip WHERE admin_id=:c_id ");
                $update->execute(array("c_id" => $admin["admin_id"], "date" => date("Y.m.d H:i:s"), "ip" => GetIP()));
            }
         else {
            // If username and password don't match, send email notification
            $error = 1;
            $errorText = "Incorrect username or password.";
        }

    if ($error) {
            // Generic error message
            

    }
    }
    }


if ($admin["access"]["admin_access"] && $_SESSION["msmbilisim_adminslogin"]) {
  exit();
} else {
  require admin_view('login');
}
?>
