<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/auth.php';
gpc_session_start();
$db = gpc_db();
$error = '';
if (isset($_GET['logout'])) { unset($_SESSION['reseller_id'], $_SESSION['reseller_user'], $_SESSION['reseller_name']); header('Location: index.php'); exit; }
if (isset($_GET['expired'])) { $error = 'Seu painel revenda está bloqueado, desativado ou vencido. Fale com o admin.'; }
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = trim((string)($_POST['username'] ?? ''));
    $pass = trim((string)($_POST['password'] ?? ''));
    $today = date('Y-m-d');
    $stmt = $db->prepare('SELECT * FROM resellers WHERE username=:u LIMIT 1');
    $stmt->execute([':u'=>$user]);
    $r = $stmt->fetch();
    $valid = $r && (int)$r['active'] === 1 && (empty($r['validity']) || $r['validity'] >= $today);
    if ($valid && password_verify($pass, (string)$r['password'])) {
        $_SESSION['reseller_id'] = (int)$r['id'];
        $_SESSION['reseller_user'] = (string)$r['username'];
        $_SESSION['reseller_name'] = (string)$r['name'];
        header('Location: dashboard.php'); exit;
    }
    $error = 'Usuário ou senha inválidos, painel vencido ou revendedor bloqueado.';
}
if (!empty($_SESSION['reseller_id'])) { header('Location: dashboard.php'); exit; }
?><!doctype html><html lang="pt-BR"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Revenda SYNTRA</title><link rel="stylesheet" href="../assets/style.css"></head><body><main class="login-wrap"><div class="login-card"><div class="brand"><div class="mark">S</div><h1>SYNTRA® Revenda</h1></div><p class="muted">Acesse para gerenciar suas Licenças MAC e DNS via Código.</p><?php if($error): ?><div class="alert alert-bad"><?= gpc_h($error) ?></div><?php endif; ?><form method="post"><label>Usuário</label><input name="username" required autofocus><label>Senha</label><input type="password" name="password" required><button class="btn" type="submit">Entrar</button></form><p class="muted small">Acesso exclusivo para revendedores autorizados pelo admin.</p></div></main></body></html>
