<?php
ob_start();
session_start();
date_default_timezone_set("Asia/Jakarta");
include('../config/koneksi.php');

// Check if the request is over HTTPS
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    header("HTTP/1.1 403 Forbidden");
    echo "Access forbidden. Use HTTPS.";
    exit();
}

function isLoggedIn()
{
    return isset($_SESSION['user']) && $_SESSION['user'] !== "" && isset($_SESSION['token']) && $_SESSION['token'] !== "";
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Regenerate CSRF token on each form request
    if (isset($_POST['csrf_token']) && hash_equals($_POST['csrf_token'], $_SESSION['csrf_token'])) {
        if ($_POST['captcha_input'] != $_SESSION['captcha_code']) {
            echo "captcha salah?";
            exit();
        }

        $last_login = date('Y-m-d H:i:s');
        $user = filter_input(INPUT_POST, 'user', FILTER_SANITIZE_STRING);
        $pass = filter_input(INPUT_POST, 'pass', FILTER_SANITIZE_STRING);

        if (empty($user) || empty($pass)) {
            header('location:../?error=1');
            exit;
        } elseif (isLoggedIn()) {
            header('location:../dashboard/');
            exit;
        }

        $stmt = $conn->prepare("SELECT cuid, pass, level FROM `tb_user` WHERE user = ?");
        $stmt->bind_param("s", $user);
        $stmt->execute();
        $result = $stmt->get_result();
        $stmt->close();

        if ($result->num_rows > 0) {
            $user_data = $result->fetch_array(MYSQLI_ASSOC);
            $token = insertToken($user_data['cuid']);
            $password = $user_data['pass'];

            if (password_verify($pass, $password)) {
                $userID = $user_data['cuid'];
                $_SESSION['user'] = htmlspecialchars($user);
                $_SESSION['token'] = $token;

                if ($user_data['level'] == 'user') {
                    $_SESSION['user'] = '';
                    unset($_SESSION['user']);
                    session_destroy();
                    header('location:../../login/');
                } else {
                    session_regenerate_id(true);
                    $update = $conn->prepare("UPDATE `tb_user` SET last_login = ? WHERE user = ?");
                    $update->bind_param("ss", $last_login, $_SESSION['user']);
                    $update->execute();
                    $update->close();
                    header('location:../dashboard/');
                }
            } else {
                session_destroy();
                header('location:../../login/');
                exit;
            }
        } else {
            header('location:../?error=4');
        }
    } else {
    // Regenerate CSRF token on each form request
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

    // CSRF token is invalid, handle the error
        echo "Ngapain Bang Ngetamper Data Kah?";
        exit();
    }
}

function insertToken($user_id = 0)
{
    global $conn;
    if (empty($user_id) && $user_id === 0) {
        return false;
    }

    $token = generateToken();

    $stmt = $conn->prepare("INSERT INTO tb_token (token) VALUES (?)");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $token_id = $stmt->insert_id;
    $stmt->close();

    $stmt = $conn->prepare("UPDATE tb_user SET token_id = ? WHERE cuid = ?");
    $stmt->bind_param("ii", $token_id, $user_id);
    $stmt->execute();
    $stmt->close();

    return $token;
}

function generateToken()
{
    $length = 10;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';

    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }

    $token = password_hash(microtime(true) . $randomString, PASSWORD_DEFAULT);
    return $token;
}
?>
