<?php
declare(strict_types=1);

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

gpc_session_start();
gpc_no_cache_headers();
$db = gpc_db();

function syntra_client_ip(): string
{
    $ip = (string)($_SERVER['REMOTE_ADDR'] ?? '');
    return substr($ip, 0, 64);
}

function syntra_client_ua(): string
{
    return substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 240);
}

function syntra_client_session_guard(): void
{
    $minutes = max(5, (int)gpc_setting('client_session_minutes', '30'));
    if (!empty($_SESSION['client_mac']) && !empty($_SESSION['client_last_activity']) && time() - (int)$_SESSION['client_last_activity'] > ($minutes * 60)) {
        unset($_SESSION['client_mac'], $_SESSION['client_last_activity']);
        $_SESSION['client_flash'] = ['type' => 'bad', 'msg' => 'Sessão expirada por segurança. Faça login novamente.'];
    }
    if (!empty($_SESSION['client_mac'])) {
        $_SESSION['client_last_activity'] = time();
    }
}

function syntra_log_client_action(string $mac, string $action, string $details = ''): void
{
    try {
        $stmt = gpc_db()->prepare('INSERT INTO client_access_logs (mac_address, action, ip, user_agent, details) VALUES (:m,:a,:ip,:ua,:d)');
        $stmt->execute([':m'=>$mac, ':a'=>$action, ':ip'=>syntra_client_ip(), ':ua'=>syntra_client_ua(), ':d'=>substr($details, 0, 1000)]);
    } catch (Throwable $e) {}
}

function syntra_login_attempt(string $mac, bool $success, string $reason = ''): void
{
    try {
        $stmt = gpc_db()->prepare('INSERT INTO client_login_attempts (mac_address, ip, success, reason) VALUES (:m,:ip,:s,:r)');
        $stmt->execute([':m'=>$mac, ':ip'=>syntra_client_ip(), ':s'=>$success ? 1 : 0, ':r'=>substr($reason, 0, 500)]);
    } catch (Throwable $e) {}
}

function syntra_login_blocked(string $mac): bool
{
    $max = max(3, (int)gpc_setting('client_login_max_attempts', '5'));
    $minutes = max(5, (int)gpc_setting('client_login_block_minutes', '15'));
    $since = date('Y-m-d H:i:s', time() - ($minutes * 60));
    try {
        $stmt = gpc_db()->prepare('SELECT COUNT(*) FROM client_login_attempts WHERE success = 0 AND created_at >= :since AND (ip = :ip OR mac_address = :m)');
        $stmt->execute([':since'=>$since, ':ip'=>syntra_client_ip(), ':m'=>$mac]);
        return (int)$stmt->fetchColumn() >= $max;
    } catch (Throwable $e) { return false; }
}

function syntra_mask_key(?string $key): string
{
    $key = trim((string)$key);
    if ($key === '') return 'KEY não gerada';
    return substr($key, 0, 4) . '-••••-••••';
}

function syntra_mask_value(?string $value, int $left = 3, int $right = 2): string
{
    $value = trim((string)$value);
    if ($value === '') return 'Não informado';
    $len = strlen($value);
    if ($len <= ($left + $right)) return str_repeat('•', max(3, $len));
    return substr($value, 0, $left) . str_repeat('•', min(8, $len - $left - $right)) . substr($value, -$right);
}

function syntra_safe_dns(?string $dns): string
{
    $dns = trim((string)$dns);
    if ($dns === '') return 'DNS não informada';
    $p = parse_url($dns);
    if (!$p || empty($p['host'])) return 'DNS cadastrada';
    return ($p['scheme'] ?? 'http') . '://' . $p['host'] . (isset($p['port']) ? ':' . $p['port'] : '');
}

syntra_client_session_guard();

function syntra_client_active_device(string $mac): ?array
{
    $stmt = gpc_db()->prepare("SELECT * FROM devices WHERE mac_address = :m AND COALESCE(access_type,'app_license') = 'app_license' ORDER BY CASE WHEN COALESCE(license_type,'official')='official' THEN 0 ELSE 1 END, expire_date DESC, id DESC LIMIT 1");
    $stmt->execute([':m' => $mac]);
    $row = $stmt->fetch();
    if (!$row) {
        return null;
    }
    $expire = (string)($row['expire_date'] ?? '');
    if ($expire === '' || gpc_expired($expire)) {
        return null;
    }
    return $row;
}

function syntra_client_lists(string $mac): array
{
    $stmt = gpc_db()->prepare('SELECT * FROM devices WHERE mac_address = :m ORDER BY id ASC');
    $stmt->execute([':m' => $mac]);
    $rows = [];
    while ($row = $stmt->fetch()) {
        if (gpc_playlist_url($row) !== '') {
            $rows[] = $row;
        }
    }
    return $rows;
}


function syntra_extract_m3u_credentials(string $url): array
{
    $url = trim($url);
    $parts = parse_url($url);
    if (!$parts || empty($parts['scheme']) || empty($parts['host'])) {
        throw new RuntimeException('URL M3U inválida. Use um link completo começando com http:// ou https://.');
    }

    $query = [];
    if (!empty($parts['query'])) {
        parse_str((string)$parts['query'], $query);
    }

    $username = trim((string)($query['username'] ?? $query['user'] ?? ''));
    $password = trim((string)($query['password'] ?? $query['pass'] ?? ''));

    if ($username === '' || $password === '') {
        $path = trim((string)($parts['path'] ?? ''), '/');
        $segments = $path !== '' ? explode('/', $path) : [];
        // Suporte extra para formatos simples como: http://servidor:porta/usuario/senha/...
        if (count($segments) >= 2 && !in_array(strtolower($segments[0]), ['get.php', 'player_api.php', 'xmltv.php'], true)) {
            $username = rawurldecode($segments[0]);
            $password = rawurldecode($segments[1]);
        }
    }

    if ($username === '' || $password === '') {
        throw new RuntimeException('Não consegui extrair usuário e senha desse M3U. Use um link no formato get.php?username=USUARIO&password=SENHA ou cadastre pela opção Xtream Codes.');
    }

    $dns = gpc_base_url($url);
    $playlist = rtrim($dns, '/') . '/get.php?username=' . rawurlencode($username) . '&password=' . rawurlencode($password) . '&type=m3u_plus&output=mpegts';

    return [
        'dns' => $dns,
        'username' => $username,
        'password' => $password,
        'playlist_url' => $playlist,
    ];
}

function syntra_partner_expire_date(?string $dnsValidity, ?string $resellerValidity = null): string
{
    // Para login por Código DNS, a validade do APP/MAC não manda.
    // O vencimento final nunca pode passar da validade da revenda master.
    $final = '2099-12-31';
    foreach ([trim((string)$dnsValidity), trim((string)$resellerValidity)] as $limitDate) {
        if ($limitDate !== '' && $limitDate < $final) {
            $final = $limitDate;
        }
    }
    return $final;
}

function syntra_upsert_playlist(string $mac, string $title, string $username, string $password, string $dns, string $playlistUrl, string $notes = '', string $accessType = 'app_license', ?string $forcedExpire = null): void
{
    $db = gpc_db();
    $key = gpc_device_key($mac);

    if ($accessType === 'app_license') {
        $main = syntra_client_active_device($mac);
        if (!$main) {
            throw new RuntimeException('MAC não encontrado ou licença vencida.');
        }
        $expire = (string)$main['expire_date'];
        $key = (string)($main['device_key'] ?: $key);

        $stmt = $db->prepare("SELECT id FROM devices WHERE mac_address = :m AND COALESCE(access_type,'app_license') = 'app_license' AND COALESCE(playlist_url,'') = '' AND COALESCE(username,'') = '' ORDER BY id ASC LIMIT 1");
        $stmt->execute([':m' => $mac]);
        $blank = $stmt->fetch();

        if ($blank) {
            $upd = $db->prepare('UPDATE devices SET username=:u, password=:p, dns=:d, playlist_url=:pl, title=:t, expire_date=:e, device_key=:k, notes=:n, access_type=:a WHERE id=:id');
            $upd->execute([':u'=>$username, ':p'=>$password, ':d'=>$dns, ':pl'=>$playlistUrl, ':t'=>$title, ':e'=>$expire, ':k'=>$key, ':n'=>$notes, ':a'=>$accessType, ':id'=>(int)$blank['id']]);
            return;
        }
    } else {
        $expire = $forcedExpire ?: '2099-12-31';
    }

    $ins = $db->prepare('INSERT INTO devices (mac_address, username, password, dns, playlist_url, title, expire_date, device_key, notes, access_type) VALUES (:m,:u,:p,:d,:pl,:t,:e,:k,:n,:a)');
    $ins->execute([':m'=>$mac, ':u'=>$username, ':p'=>$password, ':d'=>$dns, ':pl'=>$playlistUrl, ':t'=>$title, ':e'=>$expire, ':k'=>$key, ':n'=>$notes, ':a'=>$accessType]);
}

function syntra_flash(string $type, string $msg): void
{
    $_SESSION['client_flash'] = ['type' => $type, 'msg' => $msg];
}

function syntra_take_flash(): ?array
{
    if (empty($_SESSION['client_flash'])) return null;
    $f = $_SESSION['client_flash'];
    unset($_SESSION['client_flash']);
    return $f;
}

if (isset($_GET['logout'])) {
    unset($_SESSION['client_mac'], $_SESSION['client_last_activity']);
    syntra_flash('ok', 'Sessão encerrada.');
    header('Location: client.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && gpc_csrf_check($_POST['csrf'] ?? null)) {
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'login_mac') {
            $mac = gpc_format_mac((string)($_POST['mac_address'] ?? ''));
            if (strlen(str_replace(':', '', $mac)) !== 12) {
                throw new RuntimeException('Informe um MAC válido.');
            }
            if (syntra_login_blocked($mac)) {
                syntra_log_client_action($mac, 'login_bloqueado', 'Muitas tentativas inválidas no período de segurança.');
                throw new RuntimeException('Muitas tentativas inválidas. Aguarde alguns minutos e tente novamente.');
            }
            $devLogin = syntra_client_active_device($mac);
            if (!$devLogin) {
                syntra_login_attempt($mac, false, 'MAC não encontrado/vencido');
                throw new RuntimeException('MAC não encontrado, vencido ou ainda não liberado no painel admin.');
            }
            $licenseType = strtolower((string)($devLogin['license_type'] ?? 'official'));
            $savedKey = trim((string)($devLogin['device_key'] ?? ''));
            $inputKey = strtoupper(trim((string)($_POST['device_key'] ?? '')));
            if ($licenseType !== 'trial') {
                if ($savedKey === '') {
                    syntra_login_attempt($mac, false, 'Licença oficial sem KEY');
                    throw new RuntimeException('Esta licença ainda não possui KEY. Solicite ao suporte ou gere uma nova chave no painel.');
                }
                if ($inputKey === '' || !hash_equals(strtoupper($savedKey), $inputKey)) {
                    syntra_login_attempt($mac, false, 'KEY inválida');
                    throw new RuntimeException('KEY de segurança inválida. Informe o MAC + KEY da licença.');
                }
            }
            session_regenerate_id(true);
            $_SESSION['client_mac'] = $mac;
            $_SESSION['client_last_activity'] = time();
            syntra_login_attempt($mac, true, 'Login liberado');
            syntra_log_client_action($mac, 'login_ok', $licenseType === 'trial' ? 'Acesso de teste por MAC' : 'Acesso oficial por MAC + KEY');
            syntra_flash('ok', $licenseType === 'trial' ? 'Acesso de teste liberado.' : 'Acesso liberado com KEY de segurança.');
            header('Location: client.php');
            exit;
        }

        $isQuickCode = false;
        if ($action === 'quick_code') {
            $mac = gpc_format_mac((string)($_POST['mac_address'] ?? ''));
            if (strlen(str_replace(':', '', $mac)) !== 12) {
                throw new RuntimeException('Informe um MAC válido.');
            }
            $isQuickCode = true;
            $action = 'add_code';
        } else {
            $mac = (string)($_SESSION['client_mac'] ?? '');
        }

        if ($action !== 'add_code') {
            if ($mac === '' || !syntra_client_active_device($mac)) {
                unset($_SESSION['client_mac'], $_SESSION['client_last_activity']);
                throw new RuntimeException('Faça login com um MAC ativo antes de alterar listas.');
            }
        }

        if ($action === 'add_code') {
            $code = trim((string)($_POST['code'] ?? ''));
            $user = trim((string)($_POST['username'] ?? ''));
            $pass = trim((string)($_POST['password'] ?? ''));
            if ($code === '' || $user === '' || $pass === '') {
                throw new RuntimeException('Preencha código, usuário e senha.');
            }
            $stmt = $db->prepare('SELECT ds.*, r.active AS reseller_active, r.validity AS reseller_validity FROM dns_servers ds LEFT JOIN resellers r ON r.id = ds.reseller_id WHERE ds.code = :c LIMIT 1');
            $stmt->execute([':c' => $code]);
            $dns = $stmt->fetch();
            if (!$dns) throw new RuntimeException('Código DNS inválido.');
            if ((int)$dns['status'] !== 1) throw new RuntimeException('DNS desativada no painel admin.');
            if (!empty($dns['validity']) && gpc_expired((string)$dns['validity'])) throw new RuntimeException('DNS vencida no painel admin.');
            if (!empty($dns['reseller_id'])) {
                if ((int)($dns['reseller_active'] ?? 0) !== 1) throw new RuntimeException('Revenda bloqueada pelo admin.');
                if (!empty($dns['reseller_validity']) && gpc_expired((string)$dns['reseller_validity'])) throw new RuntimeException('Revenda vencida. Código DNS bloqueado automaticamente.');
            }
            $base = gpc_base_url((string)$dns['url']);
            $playlist = rtrim($base, '/') . '/get.php?username=' . rawurlencode($user) . '&password=' . rawurlencode($pass) . '&type=m3u_plus&output=mpegts';
            $partnerExpire = syntra_partner_expire_date((string)($dns['validity'] ?? ''), (string)($dns['reseller_validity'] ?? ''));
            syntra_upsert_playlist($mac, (string)($dns['name'] ?: 'Código ' . $code), $user, $pass, $base, $playlist, 'Adicionada pelo Syntra Client via Código DNS: ' . $code . '. Validade independente da licença do APP.', 'partner_code', $partnerExpire);
            gpc_log_register(['mac'=>$mac, 'user'=>$user, 'pass'=>$pass, 'cod'=>$code, 'dns_id'=>(int)$dns['id'], 'dns_url'=>$base]);
            syntra_flash('ok', 'Playlist via código adicionada. Este acesso segue a validade da DNS/parceiro, não a licença do APP.');
            header('Location: client.php');
            exit;
        }

        if ($action === 'add_xtream') {
            $name = trim((string)($_POST['title'] ?? 'Xtream')) ?: 'Xtream';
            $dns = gpc_base_url((string)($_POST['dns'] ?? ''));
            $user = trim((string)($_POST['username'] ?? ''));
            $pass = trim((string)($_POST['password'] ?? ''));
            if ($dns === '' || $user === '' || $pass === '') {
                throw new RuntimeException('Preencha servidor, usuário e senha.');
            }
            $playlist = rtrim($dns, '/') . '/get.php?username=' . rawurlencode($user) . '&password=' . rawurlencode($pass) . '&type=m3u_plus&output=mpegts';
            syntra_upsert_playlist($mac, $name, $user, $pass, $dns, $playlist, 'Adicionada pelo Syntra Client via Xtream Codes.');
            syntra_log_client_action($mac, 'add_xtream', 'Lista Xtream sincronizada pelo Painel Cliente.');
            syntra_flash('ok', 'Xtream adicionada e sincronizada com o APP.');
            header('Location: client.php');
            exit;
        }

        if ($action === 'add_m3u') {
            $name = trim((string)($_POST['title'] ?? 'M3U')) ?: 'M3U';
            $url = trim((string)($_POST['playlist_url'] ?? ''));
            if ($url === '' || !preg_match('#^https?://#i', $url)) {
                throw new RuntimeException('Informe uma URL M3U começando com http:// ou https://.');
            }
            $extracted = syntra_extract_m3u_credentials($url);
            syntra_upsert_playlist(
                $mac,
                $name,
                $extracted['username'],
                $extracted['password'],
                $extracted['dns'],
                $extracted['playlist_url'],
                'Adicionada pelo Syntra Client via URL M3U com extração automática de DNS, usuário e senha.'
            );
            syntra_log_client_action($mac, 'add_m3u', 'Lista M3U extraída e sincronizada pelo Painel Cliente.');
            syntra_flash('ok', 'M3U extraída com sucesso: DNS, usuário e senha foram salvos no formato aceito pelo painel.');
            header('Location: client.php');
            exit;
        }

        if ($action === 'delete_list') {
            $id = (int)($_POST['id'] ?? 0);
            $stmt = $db->prepare('SELECT id, access_type FROM devices WHERE id = :id AND mac_address = :m LIMIT 1');
            $stmt->execute([':id' => $id, ':m' => $mac]);
            $row = $stmt->fetch();
            if (!$row) {
                throw new RuntimeException('Lista não encontrada para este MAC.');
            }
            $rowAccess = (string)($row['access_type'] ?? 'app_license');
            if ($rowAccess === 'partner_code') {
                $del = $db->prepare("DELETE FROM devices WHERE id = :id AND mac_address = :m AND COALESCE(access_type,'app_license') = 'partner_code'");
                $del->execute([':id' => $id, ':m' => $mac]);
                syntra_log_client_action($mac, 'delete_partner_code', 'Lista por código removida do MAC.');
                syntra_flash('ok', 'Lista por código removida deste MAC.');
            } else {
                $upd = $db->prepare("UPDATE devices SET username='', password='', dns='', playlist_url='', notes=:n WHERE id = :id AND mac_address = :m AND COALESCE(access_type,'app_license') = 'app_license'");
                $upd->execute([':n' => 'Playlist removida pelo Painel Cliente. Licença MAC preservada.', ':id' => $id, ':m' => $mac]);
                syntra_log_client_action($mac, 'delete_playlist_preserve_license', 'Playlist removida, licença MAC preservada.');
                syntra_flash('ok', 'Playlist removida. A licença MAC e a KEY foram preservadas.');
            }
            header('Location: client.php');
            exit;
        }
    } catch (Throwable $e) {
        try { if (isset($db) && $db instanceof PDO && $db->inTransaction()) { $db->rollBack(); } } catch (Throwable $ignore) {}
        syntra_flash('bad', $e->getMessage());
        header('Location: client.php');
        exit;
    }
}

$csrf = gpc_csrf_token();
$flash = syntra_take_flash();
$mac = (string)($_SESSION['client_mac'] ?? '');
$device = $mac !== '' ? syntra_client_active_device($mac) : null;
if (!$device) {
    unset($_SESSION['client_mac'], $_SESSION['client_last_activity']);
    $mac = '';
}
$lists = $mac !== '' ? syntra_client_lists($mac) : [];
$panelName = gpc_setting('panel_name', 'Syntra');
?>
<!doctype html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= gpc_h($panelName) ?> Client</title>
    <style>
        :root{--bg:#050511;--card:#0c0d1b;--card2:#12142b;--text:#fbfaff;--muted:#b8b0c8;--line:rgba(168,85,247,.28);--line2:rgba(192,132,252,.45);--purple:#a855f7;--purple2:#7c3aed;--purple3:#d946ef;--ok:#39ff78;--bad:#ff4d6d;--warn:#facc15;--radius:24px;font-family:Outfit,Inter,system-ui,-apple-system,Segoe UI,sans-serif}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:radial-gradient(circle at 18% 10%,rgba(168,85,247,.22),transparent 28%),radial-gradient(circle at 88% 20%,rgba(79,70,229,.16),transparent 34%),linear-gradient(135deg,#060611,#0c0a1f 48%,#03040a);color:var(--text)}body:before{content:"";position:fixed;inset:0;pointer-events:none;opacity:.33;background-image:linear-gradient(rgba(168,85,247,.055) 1px,transparent 1px),linear-gradient(90deg,rgba(168,85,247,.055) 1px,transparent 1px);background-size:54px 54px;mask-image:linear-gradient(to bottom,#000,transparent 82%)}a{color:inherit}.wrap{width:min(1220px,100%);margin:0 auto;padding:28px 18px 46px}.top{display:flex;justify-content:space-between;align-items:center;gap:14px;margin-bottom:18px}.brand{display:flex;align-items:center;gap:14px}.logo{width:58px;height:58px;border-radius:50%;display:grid;place-items:center;background:radial-gradient(circle at 50% 35%,rgba(255,255,255,.38),transparent 26%),linear-gradient(135deg,#4c1d95,#7c3aed 48%,#c084fc);font-weight:900;box-shadow:0 0 34px rgba(168,85,247,.65),inset 0 0 22px rgba(255,255,255,.12);border:1px solid rgba(216,180,254,.45);letter-spacing:.02em}.brand h1{margin:0;font-size:26px;letter-spacing:-.045em;text-transform:uppercase}.brand p{margin:0;color:var(--muted);font-size:13px}.pill{border:1px solid var(--line);background:rgba(14,15,31,.75);padding:12px 16px;border-radius:14px;color:#ddd6fe;text-decoration:none;font-size:14px;box-shadow:0 0 22px rgba(168,85,247,.10)}.hero{display:grid;grid-template-columns:1.05fr .95fr;gap:18px;align-items:stretch}.card{position:relative;border:1px solid var(--line);background:linear-gradient(180deg,rgba(16,18,36,.88),rgba(6,7,16,.94));border-radius:var(--radius);box-shadow:0 24px 80px rgba(0,0,0,.42),0 0 42px rgba(124,58,237,.11);overflow:hidden;backdrop-filter:blur(18px)}.card:before{content:"";position:absolute;inset:0;background:linear-gradient(135deg,rgba(255,255,255,.045),transparent 32%),radial-gradient(circle at top right,rgba(168,85,247,.18),transparent 36%);pointer-events:none}.card-body{position:relative;z-index:1;padding:24px}.card h2,.card h3{margin:0 0 8px;letter-spacing:-.035em}.card p{margin:0 0 18px;color:var(--muted)}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.field{margin-bottom:14px}.field label{display:block;font-size:13px;color:#d8d1e7;margin:0 0 7px}.input{width:100%;border:1px solid var(--line);border-radius:15px;background:rgba(5,8,20,.72);color:#fff;padding:14px 15px;font-size:16px;outline:none;transition:.18s}.input::placeholder{color:rgba(230,220,255,.45)}.input:focus{border-color:var(--line2);box-shadow:0 0 0 3px rgba(168,85,247,.16),0 0 22px rgba(168,85,247,.18)}.btn{border:0;border-radius:15px;background:linear-gradient(135deg,var(--purple2),var(--purple) 55%,var(--purple3));color:#fff;padding:15px 18px;font-weight:900;font-size:15px;cursor:pointer;width:100%;box-shadow:0 14px 38px rgba(147,51,234,.30),inset 0 1px 0 rgba(255,255,255,.16);letter-spacing:.01em}.btn.secondary{background:linear-gradient(135deg,#1f1642,#581c87);box-shadow:0 10px 28px rgba(88,28,135,.20)}.btn.danger{background:linear-gradient(135deg,#9f1239,#e11d48);box-shadow:none}.option{border:1px solid var(--line);border-radius:20px;padding:18px;background:rgba(23,17,52,.54);margin-bottom:14px;box-shadow:inset 0 1px 0 rgba(255,255,255,.035)}.option strong{display:block;font-size:18px}.option span{display:block;color:var(--muted);font-size:14px;margin-top:3px}.flash{padding:13px 16px;border-radius:16px;margin-bottom:18px;border:1px solid}.flash.ok{background:rgba(34,197,94,.1);border-color:rgba(57,255,120,.35);color:#bbf7d0}.flash.bad{background:rgba(239,68,68,.1);border-color:rgba(255,77,109,.35);color:#fecaca}.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:18px}.stat{border:1px solid var(--line);background:rgba(15,16,33,.68);border-radius:18px;padding:15px;box-shadow:inset 0 1px 0 rgba(255,255,255,.035)}.stat small{display:block;color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.06em}.stat b{display:block;margin-top:4px;font-size:17px}.stat b[style*="--ok"],.stat b[style*="var(--ok)"]{color:var(--ok)!important;text-shadow:0 0 14px rgba(57,255,120,.3)}.list{display:grid;gap:10px}.list-item{display:flex;justify-content:space-between;gap:12px;align-items:center;border:1px solid var(--line);background:rgba(2,6,23,.46);border-radius:18px;padding:15px}.list-item code{color:#d8b4fe;word-break:break-all}.tabs{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:18px}.tab{padding:12px;border:1px solid var(--line);border-radius:14px;background:rgba(91,33,182,.20);color:#f3e8ff;text-align:center;font-weight:800;font-size:13px}.section{margin-top:18px}.muted{color:var(--muted)}@media(max-width:780px){.hero,.grid,.stats{grid-template-columns:1fr}.top{align-items:flex-start;flex-direction:column}.wrap{padding-top:18px}.brand h1{font-size:22px}.card-body{padding:18px}.tabs{grid-template-columns:1fr}.list-item{align-items:flex-start;flex-direction:column}.pill{width:100%;text-align:center}}
    </style>
</head>
<body>
<div class="wrap">
    <div class="top">
        <div class="brand"><div class="logo">S</div><div><h1>SYNTRA Cliente</h1><p>Central de licença e sincronização</p></div></div>
        <?php if ($mac): ?><a class="pill" href="?logout=1">Sair do MAC</a><?php endif; ?>
    </div>

    <?php if ($flash): ?><div class="flash <?= gpc_h($flash['type']) ?>"><?= gpc_h($flash['msg']) ?></div><?php endif; ?>

    <?php if (!$mac): ?>
    <div class="hero">
        <div class="card"><div class="card-body">
            <h2>Como deseja acessar?</h2>
            <p>Use o MAC do dispositivo para gerenciar a licença com segurança. Licenças oficiais usam KEY; testes grátis usam apenas MAC.</p>

            <div class="option"><strong>1. Login com MAC</strong><span>Acesse sua licença e gerencie as listas vinculadas ao dispositivo.</span></div>
            <form method="post">
                <input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>"><input type="hidden" name="action" value="login_mac">
                <div class="field"><label>Endereço MAC</label><input class="input" name="mac_address" placeholder="AA:BB:CC:DD:EE:FF" required></div>
                <div class="field"><label>KEY de segurança <span class="muted">(somente licença oficial)</span></label><input class="input" name="device_key" placeholder="SYN-XXXX-XXXX"></div>
                <p class="muted">Teste grátis entra apenas com MAC. Licença oficial exige MAC + KEY. Após muitas tentativas incorretas, o acesso é bloqueado temporariamente.</p>
                <button class="btn" type="submit">Acessar painel cliente</button>
            </form>
        </div></div>

        <div class="card"><div class="card-body">
            <h2>Carregar playlist com código</h2>
            <p>Envie uma conexão por Código DNS + usuário + senha. Não usa validade da licença do APP; segue a validade da DNS/parceiro.</p>
            <form method="post">
                <input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>"><input type="hidden" name="action" value="quick_code">
                <div class="field"><label>Endereço MAC</label><input class="input" name="mac_address" placeholder="AA:BB:CC:DD:EE:FF" required></div>
                <div class="field"><label>Código DNS</label><input class="input" name="code" placeholder="Código" required></div>
                <div class="field"><label>Nome de usuário</label><input class="input" name="username" placeholder="Usuário" required></div>
                <div class="field"><label>Senha</label><input class="input" name="password" placeholder="Senha" required></div>
                <button class="btn" type="submit">Carregar playlist</button>
            </form>
        </div></div>
    </div>
    <?php else: ?>
    <div class="card"><div class="card-body">
        <h2>Licença ativa</h2>
        <p>As listas manuais seguem a licença do APP. As listas por Código DNS seguem a validade da DNS/parceiro.</p>
        <div class="stats">
            <div class="stat"><small>MAC</small><b><?= gpc_h($mac) ?></b></div>
            <div class="stat"><small>Status</small><b style="color:var(--ok)">Ativo</b></div>
            <div class="stat"><small>Vencimento</small><b><?= gpc_h(date('d/m/Y', strtotime((string)$device['expire_date']))) ?></b></div>
            <div class="stat"><small>Tipo</small><b><?= strtolower((string)($device['license_type'] ?? 'official')) === 'trial' ? 'Teste grátis' : 'Licença oficial' ?></b></div>
            <div class="stat"><small>KEY</small><b><?= gpc_h(syntra_mask_key((string)($device['device_key'] ?? ''))) ?></b></div>
        </div>
        <p class="muted">Por segurança, a KEY completa não fica exposta nesta tela. Se perder a chave, solicite ao suporte/admin a recuperação ou geração de uma nova KEY.</p>
    </div></div>

    <div class="grid section">
        <div class="card"><div class="card-body">
            <h3>Adicionar via Código DNS</h3><p>Código cadastrado no painel admin + usuário e senha.</p>
            <form method="post"><input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>"><input type="hidden" name="action" value="add_code">
                <div class="field"><label>Código DNS</label><input class="input" name="code" required></div>
                <div class="field"><label>Usuário</label><input class="input" name="username" required></div>
                <div class="field"><label>Senha</label><input class="input" name="password" required></div>
                <button class="btn" type="submit">Sincronizar por código</button>
            </form>
        </div></div>
        <div class="card"><div class="card-body">
            <h3>Adicionar Xtream Codes</h3><p>Use servidor, usuário e senha da sua própria lista.</p>
            <form method="post"><input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>"><input type="hidden" name="action" value="add_xtream">
                <div class="field"><label>Nome da lista</label><input class="input" name="title" placeholder="Minha lista"></div>
                <div class="field"><label>Servidor/DNS</label><input class="input" name="dns" placeholder="http://servidor:8080" required></div>
                <div class="field"><label>Usuário</label><input class="input" name="username" required></div>
                <div class="field"><label>Senha</label><input class="input" name="password" required></div>
                <button class="btn" type="submit">Adicionar Xtream</button>
            </form>
        </div></div>
    </div>

    <div class="grid section">
        <div class="card"><div class="card-body">
            <h3>Adicionar URL M3U</h3><p>Cole o link M3U completo. O sistema extrai automaticamente DNS, usuário e senha.</p>
            <form method="post"><input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>"><input type="hidden" name="action" value="add_m3u">
                <div class="field"><label>Nome da lista</label><input class="input" name="title" placeholder="M3U principal"></div>
                <div class="field"><label>URL M3U completa</label><input class="input" name="playlist_url" placeholder="http://servidor:porta/get.php?username=usuario&password=senha&type=m3u_plus" required></div>
                <button class="btn secondary" type="submit">Extrair e adicionar M3U</button>
            </form>
        </div></div>
        <div class="card"><div class="card-body">
            <h3>Minhas listas</h3><p><?= count($lists) ?> lista(s) vinculada(s) a este MAC.</p>
            <div class="list">
                <?php foreach ($lists as $item): $url = gpc_playlist_url($item); ?>
                <div class="list-item">
                    <div>
                        <b><?= gpc_h((string)($item['title'] ?: 'Lista')) ?></b><br>
                        <span class="muted">Tipo: <?= ((string)($item['access_type'] ?? 'app_license') === 'partner_code') ? 'Código/DNS' : 'Licença MAC' ?></span><br>
                        <span class="muted">DNS: <?= gpc_h(syntra_safe_dns((string)($item['dns'] ?? ''))) ?></span><br>
                        <span class="muted">Usuário: <?= gpc_h(syntra_mask_value((string)($item['username'] ?? ''), 2, 2)) ?></span><br>
                        <span class="muted">Playlist protegida: link completo e senha ocultos por segurança.</span>
                    </div>
                    <form method="post" onsubmit="return confirm('Remover esta lista deste MAC? A licença MAC será preservada.')"><input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>"><input type="hidden" name="action" value="delete_list"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><button class="btn danger" type="submit">Remover</button></form>
                </div>
                <?php endforeach; ?>
                <?php if (!$lists): ?><span class="muted">Nenhuma playlist adicionada ainda.</span><?php endif; ?>
            </div>
        </div></div>
    </div>
    <?php endif; ?>
</div>
</body>
</html>
