<?php
ob_start();
session_start();
date_default_timezone_set("Asia/Jakarta");

// ======================================================
// KONEKSI OTOMATIS
// ======================================================
$baseDir = dirname(__FILE__);
$configPaths = [
    $baseDir . '/../config/koneksi.php',
    $baseDir . '/../../config/koneksi.php'
];

$connected = false;
foreach ($configPaths as $path) {
    if (file_exists($path)) {
        include($path);
        $connected = true;
        break;
    }
}

if (!$connected || !isset($conn)) {
    die("Koneksi gagal. Pastikan config/koneksi.php ada.");
}

// ======================================================
// AMBIL PENGATURAN WEBSITE
// ======================================================
$qSeo = mysqli_query($conn, "SELECT * FROM tb_seo WHERE cuid = 1");
$s0 = mysqli_fetch_array($qSeo);

$urlwebs = $s0['urlweb'];           
$urlweb  = $urlwebs . '/kerbau';    

// ======================================================
// CEK SESSION LOGIN
// ======================================================
if (empty($_SESSION['user']) || empty($_SESSION['token'])) {
    header("Location: $urlweb/index.php?error=1");
    exit;
}

// ======================================================
// DATA USER LOGIN
// ======================================================
$user = mysqli_real_escape_string($conn, $_SESSION['user']);

$qUser = mysqli_query($conn, "SELECT * FROM tb_user WHERE user='$user'");

if (mysqli_num_rows($qUser) == 0) {
    session_destroy();
    header("Location: $urlweb/index.php?error=4");
    exit;
}

$u = mysqli_fetch_array($qUser);

// ======================================================
// BATAS LEVEL
// ======================================================
if (in_array($u['level'], ['user', 'vip', 'reseller'])) {
    session_destroy();
    header("Location: $urlweb/index.php?error=5");
    exit;
}

// ======================================================
// VALIDASI TOKEN
// ======================================================
function validateToken($tokenID)
{
    global $conn;
    if (empty($tokenID)) return false;

    $q = mysqli_query($conn, "SELECT * FROM tb_token WHERE cuid='$tokenID'");
    if (mysqli_num_rows($q) == 0) return false;

    $tokenDB = mysqli_fetch_array($q)['token'];
    $tokenSession = $_SESSION['token'] ?? '';

    return $tokenDB === $tokenSession;
}

if (!validateToken($u['token_id'])) {
    session_destroy();
    header("Location: $urlweb/index.php?error=5");
    exit;
}

// ======================================================
?>
