<?php
// config.php
session_start();

function get_current_user_data()
{
    if (isset($_SESSION['user']) && is_array($_SESSION['user'])) {
        return $_SESSION['user'];
    }

    if (!isset($_SESSION['user_id'])) {
        return null;
    }

    global $mysqli;
    $stmt = $mysqli->prepare("
        SELECT id, username, role,
               can_projects, can_items, can_orders,
               can_suppliers, can_receipts, can_stock
        FROM users
        WHERE id = ?
    ");
    $stmt->bind_param('i', $_SESSION['user_id']);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        $_SESSION['user'] = $row;
        return $row;
    }
    return null;
}

/**
 * Provjera prava na određenu “karticu”
 * $section može biti: projects, items, orders, suppliers, receipts, stock
 */
function user_can($section)
{
    $user = get_current_user_data();
    if (!$user) return false;

    // admin može sve
    if ($user['role'] === 'admin') return true;

    $map = [
        'projects'  => 'can_projects',
        'items'     => 'can_items',
        'orders'    => 'can_orders',
        'suppliers' => 'can_suppliers',
        'receipts'  => 'can_receipts',
        'stock'     => 'can_stock',
    ];

    if (!isset($map[$section])) return false;

    $col = $map[$section];
    return !empty($user[$col]);
}

/**
 * Zaštita stranica – ako nema pravo, prekini
 */
function require_permission($section)
{
    if (!user_can($section)) {
        http_response_code(403);
        echo '<div style="padding:20px;font-family:sans-serif;">
                <h3>Nemate ovlasti za pristup ovoj stranici.</h3>
                <p>Obratite se administratoru.</p>
              </div>';
        exit;
    }
}


$DB_HOST = 'localhost';
$DB_USER = 'tesadmin';
$DB_PASS = '!5r;aXV35N8z0s$I';
$DB_NAME = 'tes';

$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ($mysqli->connect_errno) {
    die('Greška spajanja na bazu: ' . $mysqli->connect_error);
}

$mysqli->set_charset('utf8mb4');

function require_login() {
    if (empty($_SESSION['user_id'])) {
        header('Location: login.php');
        exit;
    }
}

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

function write_auth_log(mysqli $mysqli, string $eventType, ?int $userId, ?string $username, ?string $details = null): void {
    $ip = client_ip();
    $ua = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255);
    $sid = session_id();

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