<?php
require_once __DIR__.'/../includes/config.php';
header('Content-Type: application/json; charset=utf-8');

$db = db();

$client = [
    'username' => trim((string)($_GET['username'] ?? $_POST['username'] ?? '')),
    'password' => trim((string)($_GET['password'] ?? $_POST['password'] ?? '')),
    'android_id' => trim((string)($_GET['android_id'] ?? $_POST['android_id'] ?? $_GET['device_id'] ?? $_POST['device_id'] ?? '')),
    'code' => trim((string)($_GET['code'] ?? $_POST['code'] ?? '')),
    'client_key' => trim((string)($_GET['client_key'] ?? $_POST['client_key'] ?? '')),
];

$row = $db->querySingle("SELECT * FROM screen_logo WHERE id=1 AND is_active=1", true);
if (!$row || empty($row['image_path'])) {
    echo json_encode(['success'=>true,'active'=>false], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    exit;
}

$targetType = (string)($row['target_type'] ?? 'global');
$targetValue = (string)($row['target_value'] ?? '');

$allowed = false;
if ($targetType === 'global' || $targetValue === '') {
    $allowed = true;
} elseif (isset($client[$targetType]) && $client[$targetType] !== '' && hash_equals($targetValue, $client[$targetType])) {
    $allowed = true;
}

if (!$allowed) {
    echo json_encode(['success'=>true,'active'=>false], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    exit;
}

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$base = $scheme.'://'.($_SERVER['HTTP_HOST'] ?? '').rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/\\');
$image = (string)$row['image_path'];
if (!preg_match('~^https?://~i', $image)) {
    $image = $base.'/'.ltrim($image, '/');
}

echo json_encode([
    'success' => true,
    'active' => true,
    'image_url' => $image,
    'position' => 'bottom_left',
    'opacity' => max(0, min(100, (int)($row['opacity'] ?? 45))),
    'width' => max(20, (int)($row['width'] ?? 120)),
    'height' => max(20, (int)($row['height'] ?? 60)),
    'updated_at' => (string)($row['updated_at'] ?? ''),
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
