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

setcookie('session_id', session_id(), [
    'expires' => time() + 3600, // 1 jam
    'path' => '/',
    'domain' => '', // Biarkan kosong jika cookie hanya digunakan di domain ini
    'secure' => true, // Hanya kirim melalui HTTPS
    'httponly' => true, // Tidak dapat diakses oleh JavaScript
    'samesite' => 'Strict' // Cegah pengiriman lintas situs
]);

if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit();
}

// Validasi sesi berdasarkan User-Agent dan IP Address
if (!isset($_SESSION['user_agent'])) {
    $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
}
if (!isset($_SESSION['ip_address'])) {
    $_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];
}
if ($_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT'] || 
    $_SESSION['ip_address'] !== $_SERVER['REMOTE_ADDR']) {
    session_unset();
    session_destroy();
    exit('Sesi tidak valid.');
}

// Validasi token sesi
if (!isset($_POST['session_token']) || $_POST['session_token'] !== $_SESSION['session_token']) {
    session_unset();
    session_destroy();
    exit('Sesi tidak valid (token salah).');
}

// Regenerasi token setelah permintaan berhasil
$_SESSION['session_token'] = bin2hex(random_bytes(32));

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;
}
?>
