<?php
session_start();

// 1. Incluir el archivo de configuración centralizado
require_once '../config.php';

// 2. Lógica específica de la página
$pageTitle = $translations["login"];
$currentPage = 'login';
$login_error = '';

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

    $stmt = $conn->prepare("SELECT userid, password, confirmed FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows == 1) {
        $stmt->bind_result($userid, $hashed_password, $confirmed);
        $stmt->fetch();

        if (password_verify($password, $hashed_password)) {
            if ($confirmed == 'Yes') {
                $current_datetime = date('Y-m-d H:i:s');
                $user_ip = $_SERVER['REMOTE_ADDR'];
                $update_stmt = $conn->prepare("UPDATE users SET lastlogin = ?, lastip = ? WHERE userid = ?");
                $update_stmt->bind_param("ssi", $current_datetime, $user_ip, $userid);
                $update_stmt->execute();
                $update_stmt->close();
                $_SESSION['userid'] = $userid;
                header("Location: ../dashboard");
                exit();
            } else {
                $login_error = $translations["acceptemailplease"];
            }
        } else {
            $login_error = $translations["notcorrectlogin"];
        }
    } else {
        $login_error = $translations["notcorrectlogin"];
    }

    $stmt->close();
    $conn->close();
}

// 4. Incluir el contenido de la página
require_once __DIR__ . '/../templates/pages/login.php';

?>