<?php
// /index.php (Página de Login)
session_start();
if (isset($_SESSION['user_id'])) {
    if ($_SESSION['user_rol'] === 'paciente') {
        header('Location: patient_dashboard.php');
    } else {
        header('Location: dashboard.php');
    }
    exit;
}
require 'db.php';
require_once 'logger.php'; // <-- ★★★ AÑADIDO ★★★
$error = '';
$success = '';

if (isset($_SESSION['success_message'])) {
    $success = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    if (empty($email) || empty($password)) {
        $error = 'Per favor, completa tots els camps.';
    } else {
        $stmt = $db->prepare("SELECT * FROM cuentas WHERE email = ? AND status = 'activo' AND is_archived = 0");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_nombre'] = $user['nombre'];
            $_SESSION['user_apellido'] = $user['apellido'];
            $_SESSION['user_rol'] = $user['rol'];
            $_SESSION['records_per_page'] = (int)$user['records_per_page'];
            // --- ★ INICIO: REGISTRO DE AUDITORÍA (A1) CORREGIDO ★ ---
            $log_details_A1 = "Login con éxito. Rol: " . $user['rol'];
            registrar_log($db, 'LOGIN_SUCCESS', $user['id'], $user['nombre'], $log_details_A1, $user['id']);
            // --- ★ FIN: REGISTRO DE AUDITORÍA ★ ---

            if ($user['rol'] === 'paciente') {
                header('Location: patient_dashboard.php');
            } else {
                header('Location: dashboard.php');
            }
            exit;
        } else {
            $error = 'Email o contrasenya incorrectes.';

            // --- ★ INICIO: REGISTRO DE AUDITORÍA (A2) CORREGIDO ★ ---
            // Target user = ID si existe (falló la contraseña), o NULL si el email no existía.
            $target_id = $user['id'] ?? null;
            $details_A2 = "Intento de login fallido para email: " . $email;
            // El actor es NULO (o 0) porque no sabemos quién es, pero el target es el usuario (si existe)
            registrar_log($db, 'LOGIN_FAIL', null, 'N/A', $details_A2, $target_id);
            // --- ★ FIN: REGISTRO DE AUDITORÍA ★ ---
        }
    }
}
$page_title = "Accés a AVANT ONLINE";
?>
<!DOCTYPE html>
<html lang="ca">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link rel="stylesheet" href="style.css">
    <link rel="icon" type="image/png" sizes="32x32" href="logos/favicon.png">
    <link rel="shortcut icon" href="logos/favicon.png">
    <style>
        /* ======================================================= */
        /* ============ INICIO: MODIFICACIÓN (Animación v3) ======== */
        /* ======================================================= */

        /* 1. Definimos la animación de zoom (usando 'transform') */
        @keyframes slowZoom {
            0% {
                transform: scale(1.0); /* Estado inicial */
            }
            100% {
                transform: scale(1.05); /* Zoom al 105% */
            }
        }

        /* 2. Estilo para el body (color de fondo de reserva) */
        body {
            background-color: #e9ecef; /* Color de fondo si la imagen falla */
            padding-top: 0;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }

        /* 3. El div de fondo animado */
        #animated-bg {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: -1; /* Detrás de todo el contenido */

            /* 4. La imagen de fondo y tu opacidad (0.65) */
            background: linear-gradient(rgba(233, 236, 239, 0.65), rgba(233, 236, 239, 0.65)), url('logos/front.jpg');
            background-size: cover;
            background-position: center center;
            background-repeat: no-repeat;

            /* 5. La animación (avanza y retrocede) */
            animation-name: slowZoom;
            animation-duration: 8s;
            animation-timing-function: ease-in-out;
            animation-direction: alternate;
            animation-iteration-count: infinite;
        }

        main.container {
            flex: 1;
        }

        /* 6. Hacemos el footer transparente */
        footer {
            background-color: transparent;
        }

        /* ======================================================= */
        /* ============= FIN: MODIFICACIÓN (Animación v3) ========== */
        /* ======================================================= */

        .password-group { position: relative; }
        .password-toggle-btn { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; }
    </style>
</head>
<body>

<div id="animated-bg"></div>
<main class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-6 col-lg-4">
            <div class="text-center mb-4">
                <img src="logos/logo2.jpg" alt="Logotip d'AVANT ONLINE" class="mb-2 logo-circle">
                <h1 class="h3 fw-bold" style="color: var(--custom-brand-purple);">
                    <i class="bi bi-heart-pulse-fill me-2" style="color: #77b9af;"></i>Avant Online
                </h1>
            </div>
            <div class="card shadow">
                <div class="card-body p-4">
                    <h3 class="text-center mb-4">Iniciar Sessió</h3>
                    <?php if ($error): ?><div class="alert alert-danger py-2"><?= htmlspecialchars($error) ?></div><?php endif; ?>
                    <?php if ($success): ?><div class="alert alert-success py-2"><?= htmlspecialchars($success) ?></div><?php endif; ?>

                    <form method="POST" action="index.php">
                        <div class="mb-3">
                            <label for="email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="email" name="email" required>
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">Contrasenya</label>
                            <div class="password-group">
                                <input type="password" class="form-control" id="password" name="password" required>
                                <button type="button" class="password-toggle-btn"><i class="bi bi-eye-slash"></i></button>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary w-100 mt-3">Entrar</button>
                    </form>

                    <div class="text-center mt-3">
                        <a href="forgot_password.php" class="small">Has oblidat la contrasenya?</a>
                    </div>
                    <div class="text-center mt-4">
                        <p class="mb-0 text-muted small">No tens encara un compte? <a href="register.php">Registra't</a></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<footer class="py-4 text-center mt-auto">
    <div class="container">
        <span class="text-muted">&copy; <?= date('Y') ?> AVANT ONLINE. Tots els drets reservats.</span>
        <div class="mt-2">
            <a href="legal/politica-privacidad.php" class="small text-muted mx-2">Política de Privacitat</a>
            <span class="small text-muted">|</span>
            <a href="legal/terminos-de-uso.php" class="small text-muted mx-2">Termes d'Ús</a>
            <span class="small text-muted">|</span>
            <a href="legal/politica-cookies.php" class="small text-muted ms-2">Política de Cookies</a>
        </div>
    </div>
</footer>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function() {
    $(document).on('click', '.password-toggle-btn', function() {
        const passwordInput = $(this).closest('.password-group').find('input');
        const icon = $(this).find('i');
        if (passwordInput.attr('type') === 'password') {
            passwordInput.attr('type', 'text');
            icon.removeClass('bi-eye-slash').addClass('bi-eye');
        } else {
            passwordInput.attr('type', 'password');
            icon.removeClass('bi-eye').addClass('bi-eye-slash');
        }
    });
});
</script>
</body>
</html>
