<?php
/**
 * Login Page
 *
 * Handles user authentication with email and security token.
 */

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['acc'])) {
        $function = $_POST['acc'];
        if (!function_exists($function)) {
            die(json_encode(_response(true, 'Invalid action!')));
        }
        $function();
    }
}

/**
 * Handles the login process.
 * Validates email and sends security token.
 */
function login(): void
{
    $response = _response(true);
    $ip = $_SERVER['REMOTE_ADDR'];
    $log_type = 'error';
    $log_data = [];

    try {
        $email = strtolower(trim(filter_var($_POST['username'], FILTER_SANITIZE_EMAIL)));

        if (empty($email)) {
            throw new Exception('Email is required.');
        }

        // Find user by email
        $user = getObjectWithValue('user', 'email.keyword', $email);
        if (!$user) {
            throw new Exception("The email address is not registered.");
        }

        $user_id = $user['id'];
        unset($user['id']);

        // Check if user has a profile assigned
        if (empty($user['profile'])) {
            throw new Exception("Unable to login. Please contact the administrator.");
        }

        // Check if user is active
        if (empty($user['status']) || $user['status'] !== 'active') {
            throw new Exception("Unable to login. Please contact the administrator.");
        }

        // Generate 6-digit token
        $token = rand(100000, 999999);

        $now = new DateTime();
        $fecha_creacion = $now->format('Y-m-d H:i');
        $now->modify('+10 minutes');
        $fecha_expiracion = $now->format('Y-m-d H:i');

        $log_data['email'] = $email;
        $log_data['token'] = $token;

        // Send token via email
        $sended = sendToken($email, [
            'token' => $token,
            'fecha_creacion' => $fecha_creacion,
            'fecha_expiracion' => $fecha_expiracion
        ]);

        if ($sended) {
            // Store token in session
            _SLM::$session['access']['token'] = $token;
            _SLM::$session['access']['token_creacion'] = $fecha_creacion;
            _SLM::$session['access']['token_expiracion'] = $fecha_expiracion;

            // Remove password from user data
            unset($user['password']);

            // Store user info in session
            _SLM::$session['access']['user']['id'] = $user_id;
            _SLM::$session['access']['user']['img'] = $user['img'] ?? '';
            _SLM::$session['access']['user']['full_name'] = $user['name'] ?? '';
            _SLM::$session['access']['user']['language'] = $user['language'] ?? 'en';
            _SLM::$session['access']['user']['mode'] = $user['mode'] ?? 'light';
            _SLM::$session['access']['user'] = array_merge($user, _SLM::$session['access']['user']);

            _SLM::saveSession();

            $response['error'] = false;
            $response['message'] = 'Security code sent to your email.';
            $log_type = 'success';
        } else {
            $response['message'] = 'Failed to send security code.';
        }
    } catch (Exception $e) {
        $response['message'] = $e->getMessage();
    } finally {
        $log_data['return'] = $response;
        addToLog($log_type, 'security', __FUNCTION__, $log_data);
    }

    die(json_encode($response));
}

/**
 * Validates the security token.
 */
function validateToken(): void
{
    $response = _response(true);
    $log_type = 'error';
    $log_data = [];

    try {
        if (empty(_SLM::$session['access']['user']['email'])) {
            throw new Exception('Validation not possible.');
        }

        if (empty($_POST['token'])) {
            throw new Exception('Security code is required.');
        }

        $code = trim(filter_var($_POST['token'], FILTER_VALIDATE_INT));

        if ($code === false || strlen((string)$code) !== 6) {
            throw new Exception('Invalid code.');
        }

        // Check if token exists in session
        if (!isset(_SLM::$session['access']['token'])) {
            throw new Exception('Verification not possible.');
        }

        if (_SLM::$session['access']['token'] == $code) {
            $now = new DateTime();
            $expiry = DateTime::createFromFormat('Y-m-d H:i', _SLM::$session['access']['token_expiracion']);

            if ($now < $expiry) {
                // Token valid - complete login
                unset(_SLM::$session['access']['token']);
                unset(_SLM::$session['access']['token_creacion']);
                unset(_SLM::$session['access']['token_expiracion']);

                _SLM::$session['user'] = _SLM::$session['access']['user'];
                unset(_SLM::$session['access']);

                _SLM::saveSession();

                $response['error'] = false;
                $response['message'] = 'Login successful.';
                $log_type = 'success';
            } else {
                // Token expired
                unset(_SLM::$session['access']);
                _SLM::saveSession();
                throw new Exception('Code expired.');
            }
        } else {
            throw new Exception('Invalid code.');
        }
    } catch (Exception $e) {
        $response['message'] = $e->getMessage();
    } finally {
        $log_data['return'] = $response;
        addToLog($log_type, 'security', __FUNCTION__, $log_data);
    }

    exit(json_encode($response));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Login - <?= APP_NAME ?></title>

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">

    <style>
        :root {
            --primary-color: #3b82f6;
            --primary-dark: #2563eb;
        }

        body {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .login-container {
            max-width: 420px;
            width: 100%;
        }

        .login-card {
            background: white;
            border-radius: 16px;
            padding: 40px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        }

        .login-logo {
            max-height: 60px;
            margin-bottom: 30px;
        }

        .login-title {
            font-size: 1.75rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 8px;
        }

        .login-subtitle {
            color: #64748b;
            margin-bottom: 30px;
        }

        .form-control {
            border-radius: 8px;
            padding: 12px 16px;
            border: 2px solid #e2e8f0;
            transition: all 0.2s;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .form-label {
            font-weight: 600;
            color: #334155;
            margin-bottom: 8px;
        }

        .btn-primary {
            background: var(--primary-color);
            border-color: var(--primary-color);
            border-radius: 8px;
            padding: 12px 24px;
            font-weight: 600;
            transition: all 0.2s;
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            border-color: var(--primary-dark);
            transform: translateY(-1px);
        }

        .btn-primary:disabled {
            background: #94a3b8;
            border-color: #94a3b8;
            transform: none;
        }

        .token-input {
            font-size: 1.5rem;
            letter-spacing: 8px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card text-center">
            <img src="<?= LOGO_URL ?>" alt="<?= APP_NAME ?>" class="login-logo"
                 onerror="this.style.display='none'">

            <h1 class="login-title">Welcome</h1>
            <p class="login-subtitle">Enter your email to continue</p>

            <!-- Login Form -->
            <form id="loginForm" autocomplete="off">
                <div class="mb-4 text-start">
                    <label for="email" class="form-label">Email Address</label>
                    <input type="email" class="form-control" id="email" name="username"
                           placeholder="your@email.com" required autofocus>
                </div>

                <button type="submit" class="btn btn-primary w-100" id="loginBtn">
                    Continue
                </button>
            </form>
        </div>
    </div>

    <!-- Token Modal -->
    <div class="modal fade" id="tokenModal" data-bs-backdrop="static" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header border-0">
                    <h5 class="modal-title">Enter Security Code</h5>
                </div>
                <div class="modal-body text-center">
                    <p class="text-muted mb-4">
                        A 6-digit code has been sent to your email.
                    </p>
                    <form id="tokenForm" autocomplete="off">
                        <input type="text" class="form-control token-input mb-4"
                               id="token" name="token" maxlength="6"
                               placeholder="000000" required>
                        <button type="submit" class="btn btn-primary w-100">
                            Verify Code
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <!-- Bootstrap 5 JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        const tokenModal = new bootstrap.Modal(document.getElementById('tokenModal'));

        // Login form handler
        document.getElementById('loginForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const btn = document.getElementById('loginBtn');
            const email = document.getElementById('email').value;

            if (!email) return;

            btn.disabled = true;
            btn.textContent = 'Loading...';

            try {
                const formData = new FormData();
                formData.append('acc', 'login');
                formData.append('username', email);

                const response = await fetch('./', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (result.error) {
                    throw new Error(result.message);
                }

                Swal.fire({
                    icon: 'info',
                    title: 'Check your email',
                    text: result.message,
                    confirmButtonText: 'Continue'
                }).then(() => {
                    tokenModal.show();
                    document.getElementById('token').focus();
                });

            } catch (error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            } finally {
                btn.disabled = false;
                btn.textContent = 'Continue';
            }
        });

        // Token form handler
        document.getElementById('tokenForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const token = document.getElementById('token').value;

            if (!token || token.length !== 6) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Please enter a valid 6-digit code'
                });
                return;
            }

            try {
                const formData = new FormData();
                formData.append('acc', 'validateToken');
                formData.append('token', token);

                const response = await fetch('./', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (result.error) {
                    throw new Error(result.message);
                }

                tokenModal.hide();

                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: 'Login successful',
                    timer: 1500,
                    showConfirmButton: false
                }).then(() => {
                    window.location.href = './';
                });

            } catch (error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            }
        });

        // Only allow numbers in token input
        document.getElementById('token').addEventListener('input', function(e) {
            this.value = this.value.replace(/\D/g, '').substring(0, 6);
        });
    </script>
</body>
</html>
