<?php
require_once __DIR__.'/includes/config.php';
$login_slug = trim((string)($_GET['login_slug'] ?? ''));

if(logged()){
    header('Location: dashboard.php');
    exit;
}

$erro='';

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

    // 1) ADMIN
    $stmt=$db->prepare('SELECT * FROM users WHERE username=:u LIMIT 1');
    $stmt->bindValue(':u',$username,SQLITE3_TEXT);
    $row=$stmt->execute()->fetchArray(SQLITE3_ASSOC);

    if($row && password_ok($password, $row['password'] ?? '')){
        session_regenerate_id(true);
        $_SESSION['loggedin']=true;
        $_SESSION['role']='admin';
        $_SESSION['owner_type']='admin';
        $_SESSION['owner_id']=0;
        $_SESSION['name']=$row['username'];
        header('Location: dashboard.php');
        exit;
    }

    // 2) REVENDA
    $stmt=$db->prepare('SELECT * FROM revendas WHERE usuario=:u LIMIT 1');
    $stmt->bindValue(':u',$username,SQLITE3_TEXT);
    $row=$stmt->execute()->fetchArray(SQLITE3_ASSOC);

    if($row && password_ok($password, $row['senha'] ?? '')){
        if((int)($row['is_active'] ?? 0) !== 1 || (int)($row['manual_blocked'] ?? 0) === 1){
            $erro='Revenda bloqueada. Fale com o administrador.';
        } elseif(function_exists('is_plan_expired') && is_plan_expired($row)){
            $erro='Revenda vencida. Fale com o administrador.';
        } else {
            session_regenerate_id(true);
            $_SESSION['loggedin']=true;
            $_SESSION['role']='revenda';
            $_SESSION['owner_type']='revenda';
            $_SESSION['owner_id']=(int)$row['id'];
            $_SESSION['name']=$row['nome'] ?: $row['usuario'];
            $_SESSION['username']=$row['usuario'];
            header('Location: dashboard.php');
            exit;
        }
    }

    // 3) SUB REVENDA
    if($erro===''){
        $stmt=$db->prepare('SELECT * FROM sub_revendas WHERE usuario=:u LIMIT 1');
        $stmt->bindValue(':u',$username,SQLITE3_TEXT);
        $row=$stmt->execute()->fetchArray(SQLITE3_ASSOC);

        if($row && password_ok($password, $row['senha'] ?? '')){
            if((int)($row['is_active'] ?? 0) !== 1 || (int)($row['manual_blocked'] ?? 0) === 1){
                $erro='Sub revenda bloqueada. Fale com o administrador.';
            } elseif(function_exists('is_plan_expired') && is_plan_expired($row)){
                $erro='Sub revenda vencida. Fale com o administrador.';
            } else {
                session_regenerate_id(true);
                $_SESSION['loggedin']=true;
                $_SESSION['role']='subrevenda';
                $_SESSION['owner_type']='subrevenda';
                $_SESSION['owner_id']=(int)$row['id'];
                $_SESSION['revenda_id']=(int)($row['revenda_id'] ?? 0);
                $_SESSION['name']=$row['nome'] ?: $row['usuario'];
                $_SESSION['username']=$row['usuario'];
                header('Location: dashboard.php');
                exit;
            }
        }
    }

    if($erro==='') $erro='Usuário ou senha inválidos';
}

include __DIR__.'/includes/header.php';
?>
<div class="login-page">
    <div class="brand-panel">
        <div class="play-mark"></div>
        <div class="logo-text"><span>POP</span><span>PLAY</span></div>
        <div class="admin-sub">Painel de Administração</div>
        <div class="neon-line"></div>
        <div class="brand-title">Painel de Administração</div>
        <div class="brand-bullets">Admin • Revenda • Sub Revenda</div>
    </div>
    <div class="ghost-play"></div>
    <form class="login-card" method="post">
        <div class="login-icon">
            <svg viewBox="0 0 24 24" width="54" height="54" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
        </div>
        <h1>LOGIN <span>PAINEL</span></h1>
        <div class="small-line"></div>
        <p>Acesse sua conta</p>
        <?php if($erro): ?><p class="login-error"><?=h($erro)?></p><?php endif; ?>
        <div class="field">
            <svg viewBox="0 0 24 24" fill="none" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
            <input name="username" placeholder="Usuário" autocomplete="username" required>
        </div>
        <div class="field">
            <svg viewBox="0 0 24 24" fill="none" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
            <input name="password" type="password" placeholder="Senha" autocomplete="current-password" required>
            <span class="eye">◉</span>
        </div>
        <div class="login-options">
            <span class="check"><span class="box"></span> Lembrar-me</span>
            <a class="forgot" href="#" onclick="return false;">Esqueceu sua senha?</a>
        </div>
        <button class="login-btn" name="login">ENTRAR <span>→</span></button>
        <div class="secure-divider">🛡</div>
        <div class="secure-text">Conexão segura</div>
    </form>
</div>
<div class="login-footer">🛡 PopPlay - Painel de Administração v2.0</div>
<?php include __DIR__.'/includes/footer.php'; ?>
