<?php
require_once 'config.php';

if (!function_exists('auth_logs_table_exists')) {
    function auth_logs_table_exists(mysqli $mysqli): bool {
        $res = $mysqli->query("SHOW TABLES LIKE 'auth_logs'");
        return $res && $res->num_rows > 0;
    }
}

if (!function_exists('client_ip_address')) {
    function client_ip_address(): string {
        $keys = ['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
        foreach ($keys as $key) {
            if (!empty($_SERVER[$key])) {
                $value = trim(explode(',', (string)$_SERVER[$key])[0]);
                if (filter_var($value, FILTER_VALIDATE_IP)) {
                    return $value;
                }
            }
        }
        return '';
    }
}

if (!function_exists('write_auth_log')) {
    function write_auth_log(mysqli $mysqli, string $eventType, ?int $userId, ?string $username, ?string $details = null): void {
        static $checked = null;
        if ($checked === null) {
            $checked = auth_logs_table_exists($mysqli);
        }
        if (!$checked) return;

        $ip = client_ip_address();
        $userAgent = substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255);
        $sessionId = substr(session_id(), 0, 128);

        $stmt = $mysqli->prepare(
            'INSERT INTO auth_logs (event_type, user_id, username_attempted, ip_address, user_agent, session_id, details) VALUES (?, ?, ?, ?, ?, ?, ?)'
        );
        if (!$stmt) return;
        $stmt->bind_param('sisssss', $eventType, $userId, $username, $ip, $userAgent, $sessionId, $details);
        $stmt->execute();
        $stmt->close();
    }
}

if (!empty($_SESSION['user']['id']) || !empty($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

$error = '';

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

    if ($username !== '' && $password !== '') {
        $stmt = $mysqli->prepare('
            SELECT id, username, password_hash,
                   role,
                   can_projects, can_items, can_orders,
                   can_suppliers, can_receipts, can_stock
            FROM users
            WHERE username = ?
            LIMIT 1
        ');

        if ($stmt) {
            $stmt->bind_param('s', $username);
            $stmt->execute();
            $stmt->bind_result(
                $id, $uName, $hash,
                $role,
                $can_projects, $can_items, $can_orders,
                $can_suppliers, $can_receipts, $can_stock
            );

            $loginOk = false;
            if ($stmt->fetch() && password_verify($password, $hash)) {
                $loginOk = true;
            }
            $stmt->close();

            if ($loginOk) {
                session_regenerate_id(true);

                $_SESSION['user_id']  = $id;
                $_SESSION['username'] = $uName;
                $_SESSION['user'] = [
                    'id'            => $id,
                    'username'      => $uName,
                    'role'          => $role,
                    'can_projects'  => (int)$can_projects,
                    'can_items'     => (int)$can_items,
                    'can_orders'    => (int)$can_orders,
                    'can_suppliers' => (int)$can_suppliers,
                    'can_receipts'  => (int)$can_receipts,
                    'can_stock'     => (int)$can_stock,
                ];

                if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
                    $newHash = password_hash($password, PASSWORD_DEFAULT);
                    $rehashStmt = $mysqli->prepare('UPDATE users SET password_hash = ? WHERE id = ?');
                    if ($rehashStmt) {
                        $rehashStmt->bind_param('si', $newHash, $id);
                        $rehashStmt->execute();
                        $rehashStmt->close();
                    }
                }

                write_auth_log($mysqli, 'login_success', (int)$id, $uName, 'Uspješna prijava');
                header('Location: index.php');
                exit;
            }

            write_auth_log($mysqli, 'login_failed', null, $username, 'Neuspješna prijava');
            $error = 'Neispravno korisničko ime ili lozinka.';
            usleep(300000);
        } else {
            $error = 'Greška pri obradi prijave.';
        }
    } else {
        $error = 'Unesite korisničko ime i lozinku.';
    }
}
?>
<!doctype html>
<html lang="hr">
<head>
    <meta charset="utf-8">
    <title>Prijava - Evidencija materijala</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container d-flex align-items-center justify-content-center" style="min-height:100vh;">
    <div class="card shadow-sm" style="max-width:400px;width:100%;">
        <div class="card-body">
            <h4 class="mb-3 text-center">Evidencija materijala</h4>
            <?php if ($error): ?>
                <div class="alert alert-danger py-2 small"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            <form method="post" autocomplete="off">
                <div class="mb-3">
                    <label class="form-label">Korisničko ime</label>
                    <input type="text" name="username" class="form-control" required autofocus>
                </div>
                <div class="mb-3">
                    <label class="form-label">Lozinka</label>
                    <input type="password" name="password" class="form-control" required>
                </div>
                <button class="btn btn-primary w-100 mb-2" type="submit">Prijava</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>
