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

// Set cookie dengan atribut keamanan
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
]);

$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (preg_match('/python|curl|wget/i', $user_agent)) {
    die('Access Denied');
}

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


$sql_0 = mysqli_query($conn,"SELECT * FROM `tb_seo` WHERE cuid = 1") or die(mysqli_error());
$s0 = mysqli_fetch_array($sql_0);
$urlweb = $s0['urlweb'].'/backend';
$urlwebs = $s0['urlweb'];

if (empty($_SESSION['user']) AND empty($_SESSION['pass'])){
  header('location:'.$urlweb.'/login/');
  exit;
}

$allowed_referer = $urlwebs;
$referer = $_SERVER['HTTP_REFERER'] ?? '';

if (strpos($referer, $allowed_referer) === false) {
    // Referer tidak sesuai
    die('Access denied');
}

$usernya = mysqli_real_escape_string($conn, $_SESSION['user']);
$query = "SELECT * FROM `tb_user` WHERE user = '$usernya'";
$user = mysqli_query($conn, $query) or die(mysqli_error($conn));
$u = mysqli_fetch_assoc($user);
$token_id = isset($u['token_id']) ? $u['token_id'] : false;
$level = isset($u['level']) ? $u['level'] : false;

if(!validateToken($token_id)){
	$_SESSION['token'] = "";
	$_SESSION['user'] = "";
	$_SESSION['pass'] = "";
	header('location:'.$urlweb.'/login/?error=5');
	exit;
}

function validateToken($token_id){
    $conn = $GLOBALS['conn'];
	$q = mysqli_query($conn,"SELECT * FROM `tb_token` WHERE cuid='$token_id';") or die(mysqli_error($conn));
	if (mysqli_num_rows($q) > 0) {
		$token_data = mysqli_fetch_array($q);
		$token = $token_data['token'];
		$session_token = isset($_SESSION['token']) ? $_SESSION['token'] : "";
		
		if($token == $session_token){
			return true;
		}
	}
	
	return false;
}
?>