<?php
/**
 * Token Validation API
 * Endpoint: /admin/adminapi/validate_token.php
 * 
 * Checks if current token is still valid.
 * Used by Android app to check session status on resume.
 * Returns remaining time before expiry.
 */

require_once __DIR__ . '/includes/auth.php';

header('Content-Type: application/json');

$token = extractToken();

if (!$token) {
    echo json_encode(['success' => false, 'valid' => false, 'message' => 'No token provided']);
    exit;
}

$adminId = validateAuthToken($token);

if ($adminId === false) {
    echo json_encode(['success' => false, 'valid' => false, 'message' => 'Token expired or invalid', 'code' => 'TOKEN_EXPIRED']);
    exit;
}

// Get last_activity to calculate remaining time
global $pdo;
$stmt = $pdo->prepare("SELECT last_activity FROM admin_tokens WHERE token = ? LIMIT 1");
$stmt->execute([$token]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

$remainingSeconds = TOKEN_EXPIRY_SECONDS - (time() - strtotime($row['last_activity']));

echo json_encode([
    'success' => true,
    'valid' => true,
    'admin_id' => $adminId,
    'remaining_seconds' => max(0, $remainingSeconds),
    'expiry_minutes' => TOKEN_EXPIRY_SECONDS / 60
]);
