<?php

declare(strict_types=1);

require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/api.php';

$path = request_path();
$method = (string)($_SERVER['REQUEST_METHOD'] ?? 'GET');
route_public_api($path, $method);

if (is_admin()) {
    redirect('dashboard.php');
}

$error = '';
$isSetup = admin_count() === 0;

if ($method === 'POST') {
    $username = trim((string)($_POST['username'] ?? ''));
    $password = (string)($_POST['password'] ?? '');

    if ($isSetup) {
        if ($username === '' || strlen($password) < 8) {
            $error = 'Informe um usuário e uma senha com pelo menos 8 caracteres.';
        } else {
            try {
                $stmt = db()->prepare('INSERT INTO admins(username,password_hash,created_at) VALUES(?,?,?)');
                $stmt->execute([$username, password_hash($password, PASSWORD_DEFAULT), now()]);
                session_regenerate_id(true);
                $_SESSION['admin_id'] = (int)db()->lastInsertId();
                redirect('dashboard.php');
            } catch (Throwable $e) {
                $error = 'Não foi possível criar o administrador. Escolha outro usuário.';
            }
        }
    } else {
        $stmt = db()->prepare('SELECT * FROM admins WHERE username=? LIMIT 1');
        $stmt->execute([$username]);
        $admin = $stmt->fetch();
        if ($admin && password_verify($password, (string)$admin['password_hash'])) {
            session_regenerate_id(true);
            $_SESSION['admin_id'] = (int)$admin['id'];
            redirect('dashboard.php');
        }
        $error = 'Usuário ou senha inválidos.';
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <title>Max Rebrands | <?=$isSetup ? 'Primeiro acesso' : 'Login'?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="theme-color" content="#050507">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Orbitron:wght@600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        :root{
            --bg:#050507;--card:rgba(14,15,22,.84);--card2:rgba(255,255,255,.055);
            --red:#ff1b2d;--red2:#970711;--text:#f7f7fb;--muted:#a8acbb;
            --line:rgba(255,255,255,.12);--line-red:rgba(255,27,45,.42);
        }
        *{box-sizing:border-box;}
        html,body{min-height:100%;}
        body{
            min-height:100vh;margin:0;font-family:'Inter',Arial,sans-serif;color:var(--text);
            background:radial-gradient(circle at 16% 16%,rgba(255,27,45,.23),transparent 32%),radial-gradient(circle at 78% 12%,rgba(255,255,255,.08),transparent 28%),linear-gradient(135deg,#030304 0%,#0b0b10 50%,#190005 100%);
            overflow-x:hidden;
        }
        body:before{content:"";position:fixed;inset:0;background:linear-gradient(rgba(255,255,255,.025) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.025) 1px,transparent 1px);background-size:42px 42px;pointer-events:none;z-index:-2;}
        #particles-js{position:fixed;inset:0;z-index:-1;opacity:.45;}
        .login-shell{
            width:min(460px,92vw);
            min-height:100vh;
            margin:0 auto;
            display:flex;
            align-items:center;
            justify-content:center;
            padding:28px 0;
        }
        .login-card{
            width:100%;
            border-radius:32px;
            padding:30px;
            background:linear-gradient(180deg,var(--card),rgba(8,8,12,.94));
            border:1px solid var(--line-red);
            box-shadow:0 30px 90px rgba(0,0,0,.56);
            backdrop-filter:blur(16px);
            -webkit-backdrop-filter:blur(16px);
        }
        .login-head{text-align:center;margin-bottom:24px;}
        .login-head img{width:122px;height:122px;border-radius:50%;object-fit:cover;border:1px solid rgba(255,255,255,.14);box-shadow:0 0 36px rgba(255,27,45,.28);}
        .login-head h2{font-family:'Orbitron',sans-serif;margin:16px 0 5px;font-size:1.55rem;letter-spacing:.08em;}
        .login-head span{color:var(--muted);font-size:.92rem;}
        .login-error{display:flex;align-items:flex-start;gap:10px;margin:0 0 17px;padding:13px 14px;border-radius:16px;background:rgba(255,27,45,.14);border:1px solid rgba(255,27,45,.42);color:#ffdadd;font-size:.9rem;line-height:1.4;}
        .input-box{position:relative;margin-bottom:17px;}
        .input-box input{width:100%;height:54px;padding:0 48px 0 16px;border-radius:17px;border:1px solid rgba(255,255,255,.12);background:rgba(0,0,0,.36);color:#fff;font-size:16px;outline:none;transition:.18s ease;}
        .input-box input:focus{border-color:var(--red);box-shadow:0 0 0 4px rgba(255,27,45,.16);}
        .input-box i{position:absolute;right:17px;top:18px;color:#ff4c58;}
        .btn-login{width:100%;height:54px;border:0;border-radius:17px;color:#fff;background:linear-gradient(135deg,var(--red),var(--red2));font-weight:900;font-size:16px;cursor:pointer;box-shadow:0 18px 35px rgba(255,27,45,.25);transition:.18s ease;}
        .btn-login:hover{transform:translateY(-2px);box-shadow:0 22px 42px rgba(255,27,45,.36);}
        .btn-login:focus{outline:3px solid rgba(255,27,45,.28);outline-offset:3px;}
        .login-note{margin-top:20px;padding:14px;border-radius:18px;background:rgba(255,255,255,.055);border:1px solid var(--line);color:var(--muted);font-size:.88rem;text-align:center;}
        .footer-text{text-align:center;margin-top:20px;color:#818696;font-size:.83rem;}
        .footer-text strong{color:#fff;}
        .footer-text a{color:#fff;text-decoration:none;font-weight:700;transition:.18s ease;}
        .footer-text a:hover{color:var(--red);text-shadow:0 0 12px rgba(255,27,45,.45);}
        @media(max-width:520px){
            .login-shell{width:min(92vw,430px);padding:18px 0 24px;align-items:center;}
            .login-card{border-radius:24px;padding:20px;}
            .login-head img{width:102px;height:102px;}
            .login-head h2{font-size:1.28rem;}
        }
        @media(max-height:650px){
            .login-shell{align-items:flex-start;padding-top:16px;}
            .login-head img{width:86px;height:86px;}
            .login-head{margin-bottom:18px;}
            .login-note,.footer-text{margin-top:14px;}
        }
    </style>
</head>
<body>
<div id="particles-js"></div>
<main class="login-shell">
    <section class="login-card">
        <div class="login-head">
            <img src="<?=e(panel_url('img/max_rebrands_logo.png'))?>" alt="Max Rebrands">
            <h2>MAX REBRANDS</h2>
            <span><?=$isSetup ? 'Configure o primeiro acesso administrativo' : 'Acesso seguro ao painel'?></span>
        </div>
        <?php if ($error !== ''): ?>
            <div class="login-error"><i class="fa-solid fa-triangle-exclamation"></i><span><?=e($error)?></span></div>
        <?php endif; ?>
        <form method="post" autocomplete="off">
            <div class="input-box">
                <input type="text" name="username" placeholder="Usuário" value="<?=e($_POST['username'] ?? '')?>" autocomplete="username" required autofocus>
                <i class="fa-solid fa-user"></i>
            </div>
            <div class="input-box">
                <input type="password" name="password" placeholder="Senha" autocomplete="<?=$isSetup ? 'new-password' : 'current-password'?>" <?=$isSetup ? 'minlength="8"' : ''?> required>
                <i class="fa-solid fa-lock"></i>
            </div>
            <button type="submit" class="btn-login">
                <i class="fa-solid fa-right-to-bracket"></i> <?=$isSetup ? 'Criar e Entrar' : 'Entrar no Painel'?>
            </button>
        </form>
        <div class="login-note">Para mais scripts ou solicitação de nossos serviços, acesse maxloja.xyz</div>
        <div class="footer-text">Desenvolvido por <a href="https://t.me/dvmaxrebrands" target="_blank" rel="noopener noreferrer"><strong>Max Rebrands</strong></a></div>
    </section>
</main>
<script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
<script>
if (window.particlesJS) {
    particlesJS('particles-js', {
        particles: {number:{value:72,density:{enable:true,value_area:850}},color:{value:'#ff1b2d'},shape:{type:'circle'},opacity:{value:.38,random:true},size:{value:3,random:true},line_linked:{enable:true,distance:150,color:'#ff1b2d',opacity:.24,width:1},move:{enable:true,speed:1.6,direction:'none',random:false,straight:false,out_mode:'out'}},
        interactivity: {detect_on:'canvas',events:{onhover:{enable:true,mode:'grab'},onclick:{enable:true,mode:'push'}},modes:{grab:{distance:140,line_linked:{opacity:.5}},push:{particles_nb:4}}},retina_detect:true
    });
}
</script>
</body>
</html>
