<?php
session_start();

// Arquivo JSON dos parceiros
$arquivo = __DIR__ . '/data/parceiros.json';

// Redireciona se já estiver logado
if(isset($_SESSION['usuario'])){
    header("Location: produtos.php");
    exit;
}

// Processa login
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $senha = trim($_POST['senha'] ?? '');

    header('Content-Type: application/json');

    if (!$email || !$senha) {
        echo json_encode(['status' => 'error', 'message' => 'Preencha todos os campos!']);
        exit;
    }

    if (!file_exists($arquivo)) {
        echo json_encode(['status' => 'error', 'message' => 'Nenhum usuário cadastrado.']);
        exit;
    }

    $dados = json_decode(file_get_contents($arquivo), true);
    $usuarioEncontrado = null;

    foreach ($dados as $u) {
        if ($u['email'] === $email) {
            if (password_verify($senha, $u['senha'])) {
                $usuarioEncontrado = $u;
            }
            break;
        }
    }

    if ($usuarioEncontrado) {
        $_SESSION['usuario'] = $usuarioEncontrado;
        echo json_encode(['status' => 'success', 'nome' => $usuarioEncontrado['nome']]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'E-mail ou senha incorretos!']);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - NT INDICA</title>
<link rel="icon" type="image/x-icon" href="imagem/favicon.ico">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
* { box-sizing: border-box; }
html, body { height: 100%; width: 100%; margin: 0; padding: 0; font-family: 'Inter', sans-serif; background: #f1f5f9; display: flex; align-items: center; justify-content: center; }
.login-container {
    background: white; padding: 35px; width: 92%; max-width: 480px; border-radius: 20px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.08); text-align: center;
}
.logo-img { max-height: 60px; margin-bottom: 15px; object-fit: contain; max-width: 100%; }
h2 { color: #1e293b; margin: 0 0 10px 0; font-size: 1.5rem; font-weight: 800; }
.form-group { position: relative; margin-bottom: 12px; text-align: left; }
.form-group i { position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: #94a3b8; z-index: 1; font-size: 0.95rem; }
input { width: 100%; padding: 12px 12px 12px 45px; border: 1px solid #cbd5e1; border-radius: 10px; font-size: 1rem; background: #f8fafc; transition: 0.3s; color: #334155; }
input:focus { outline: none; border-color: #0f172a; background: #fff; box-shadow: 0 0 0 3px rgba(15, 23, 42, 0.1); }
button { width: 100%; padding: 14px; background: #000; color: #fff; border: none; border-radius: 10px; font-weight: 700; font-size: 1rem; cursor: pointer; margin-top: 8px; transition: 0.2s; display: flex; align-items: center; justify-content: center; gap: 10px; }
button:hover { background: #333; transform: translateY(-2px); }
.footer-link { margin-top: 15px; display: block; color: #64748b; text-decoration: none; font-size: 0.9rem; }
.footer-link:hover { color: #0f172a; text-decoration: underline; }
</style>
</head>
<body>

<div class="login-container">
    <div class="logo-container">
        <img src="imagem/logo.png" alt="Logo" class="logo-img">
    </div>
    <h2>Área Administrativa</h2>

    <form id="loginForm" method="POST">
        <div class="form-group">
            <i class="fas fa-envelope"></i>
            <input type="email" name="email" placeholder="E-mail" required>
        </div>
        <div class="form-group">
            <i class="fas fa-lock"></i>
            <input type="password" name="senha" placeholder="Senha" required>
        </div>
        <button type="submit">ACESSAR <i class="fas fa-sign-in-alt"></i></button>
    </form>

    <a href="novo_parceiro.php" class="footer-link"><i class="fas fa-arrow-left"></i> Criar Conta</a>
</div>

<script>
const form = document.getElementById('loginForm');

form.addEventListener('submit', function(e){
    e.preventDefault();
    const formData = new FormData(form);

    fetch('admin_login.php', { method: 'POST', body: formData })
    .then(res => res.json())
    .then(data => {
        if(data.status === 'success'){
            Swal.fire({
                icon: 'success',
                title: 'Login Realizado!',
                html: `Bem-vindo, <b>${data.nome}</b>!`,
                background: '#fff',
                color: '#000',
                confirmButtonColor: '#000'
            }).then(() => { window.location.href = 'produtos.php'; });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Ops...',
                text: data.message,
                background: '#fff',
                color: '#000',
                confirmButtonColor: '#000'
            });
        }
    })
    .catch(err => {
        Swal.fire({
            icon: 'error',
            title: 'Erro',
            text: 'Ocorreu um erro ao processar.',
            background: '#fff',
            color: '#000',
            confirmButtonColor: '#000'
        });
        console.error(err);
    });
});
</script>

</body>
</html>