<?php
// admin/index.php

$tokenDir = __DIR__ . '/token';
$tokenFile = $tokenDir . '/file.txt';

if (!file_exists($tokenFile)) {
    header("Location: expired.php");
    exit;
}

// token from URL or cookie
$urlToken = $_GET['t'] ?? null;
$cookieToken = $_COOKIE['admin_token'] ?? null;

$data = json_decode(file_get_contents($tokenFile), true);

if (!$data || !isset($data['token'], $data['expiry'])) {
    header("Location: expired.php");
    exit;
}

// if token passed via URL
if ($urlToken) {
    if (
        hash_equals($data['token'], $urlToken) &&
        time() <= $data['expiry']
    ) {
        // save cookie for 30 minutes
        setcookie(
            "admin_token",
            $urlToken,
            time() + (30 * 60),
            "/",
            "",
            false,
            true // httpOnly
        );

        // clean URL
        header("Location: dashboard.php");
        exit;
    } else {
        header("Location: expired.php");
        exit;
    }
}

// if token from cookie
if ($cookieToken) {
    if (
        hash_equals($data['token'], $cookieToken) &&
        time() <= $data['expiry']
    ) {
        // ✅ ACCESS GRANTED
        header("Location: dashboard.php");
        exit;
    }
}

// fallback
header("Location: expired.php");
exit;
