<?php
require_once 'header.php';

$me = get_current_user_data();
if (!$me || (($me['role'] ?? '') !== 'admin')) {
    http_response_code(403);
    echo '<div class="alert alert-danger m-3">Samo administrator može pregledavati logove prijave.</div>';
    require_once 'footer.php';
    exit;
}

function table_exists(mysqli $mysqli, string $table): bool {
    $safe = $mysqli->real_escape_string($table);
    $res = $mysqli->query("SHOW TABLES LIKE '{$safe}'");
    return $res && $res->num_rows > 0;
}

if (!table_exists($mysqli, 'auth_logs')) {
    echo '<div class="row g-3 mb-3"><div class="col"><div class="section-title">Logovi prijave</div><div class="text-muted small">Pregled uspješnih i neuspješnih prijava te odjava</div></div></div>';
    echo '<div class="alert alert-warning">Tablica <strong>auth_logs</strong> ne postoji. Prvo pokreni SQL migraciju za logove.</div>';
    require_once 'footer.php';
    exit;
}

$q = trim($_GET['q'] ?? '');
$event = trim($_GET['event'] ?? '');
$dateFrom = trim($_GET['date_from'] ?? '');
$dateTo = trim($_GET['date_to'] ?? '');
$limit = (int)($_GET['limit'] ?? 100);
if (!in_array($limit, [50, 100, 200, 500], true)) $limit = 100;

$allowedEvents = ['login_success', 'login_failed', 'logout'];
if ($event !== '' && !in_array($event, $allowedEvents, true)) {
    $event = '';
}

$where = [];
$params = [];
$types = '';

if ($q !== '') {
    $where[] = '(COALESCE(username_attempted, "") LIKE CONCAT("%", ?, "%") OR COALESCE(ip_address, "") LIKE CONCAT("%", ?, "%") OR COALESCE(details, "") LIKE CONCAT("%", ?, "%") OR COALESCE(user_agent, "") LIKE CONCAT("%", ?, "%"))';
    array_push($params, $q, $q, $q, $q);
    $types .= 'ssss';
}

if ($event !== '') {
    $where[] = 'event_type = ?';
    $params[] = $event;
    $types .= 's';
}

if ($dateFrom !== '') {
    $dt = DateTime::createFromFormat('Y-m-d', $dateFrom);
    if ($dt) {
        $where[] = 'created_at >= ?';
        $params[] = $dt->format('Y-m-d 00:00:00');
        $types .= 's';
    }
}

if ($dateTo !== '') {
    $dt = DateTime::createFromFormat('Y-m-d', $dateTo);
    if ($dt) {
        $where[] = 'created_at <= ?';
        $params[] = $dt->format('Y-m-d 23:59:59');
        $types .= 's';
    }
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$stats = [
    'login_success' => 0,
    'login_failed' => 0,
    'logout' => 0,
    'total' => 0,
];
$statsSql = "SELECT event_type, COUNT(*) AS cnt FROM auth_logs {$whereSql} GROUP BY event_type";
$statsStmt = $mysqli->prepare($statsSql);
if ($statsStmt) {
    if ($types !== '') {
        $statsStmt->bind_param($types, ...$params);
    }
    $statsStmt->execute();
    $statsRes = $statsStmt->get_result();
    while ($row = $statsRes->fetch_assoc()) {
        $stats[$row['event_type']] = (int)$row['cnt'];
        $stats['total'] += (int)$row['cnt'];
    }
    $statsStmt->close();
}

$sql = "
    SELECT id, event_type, user_id, username_attempted, ip_address, user_agent, session_id, details, created_at
    FROM auth_logs
    {$whereSql}
    ORDER BY created_at DESC, id DESC
    LIMIT {$limit}
";
$stmt = $mysqli->prepare($sql);
if ($stmt) {
    if ($types !== '') {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $res = $stmt->get_result();
} else {
    $res = false;
}

function event_badge_class(string $event): string {
    return match ($event) {
        'login_success' => 'success',
        'login_failed' => 'danger',
        'logout' => 'secondary',
        default => 'light',
    };
}

function event_label(string $event): string {
    return match ($event) {
        'login_success' => 'Uspješna prijava',
        'login_failed' => 'Neuspješna prijava',
        'logout' => 'Odjava',
        default => $event,
    };
}
?>

<div class="row g-3 mb-3 align-items-center">
    <div class="col">
        <div class="section-title">Logovi prijave</div>
        <div class="text-muted small">Pregled uspješnih i neuspješnih prijava te odjava korisnika</div>
    </div>
    <div class="col-auto d-flex flex-wrap gap-2">
        <a href="users.php" class="btn btn-outline-secondary btn-soft btn-sm">← Korisnici</a>
        <a href="login_logs.php" class="btn btn-outline-secondary btn-soft btn-sm">Reset</a>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-12 col-md-6 col-xl-3">
        <div class="card card-soft h-100">
            <div class="card-body card-soft-body">
                <div class="text-muted small mb-1">Ukupno događaja</div>
                <div class="fs-4 fw-semibold"><?php echo (int)$stats['total']; ?></div>
            </div>
        </div>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
        <div class="card card-soft h-100">
            <div class="card-body card-soft-body">
                <div class="text-muted small mb-1">Uspješne prijave</div>
                <div class="fs-4 fw-semibold text-success"><?php echo (int)$stats['login_success']; ?></div>
            </div>
        </div>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
        <div class="card card-soft h-100">
            <div class="card-body card-soft-body">
                <div class="text-muted small mb-1">Neuspješne prijave</div>
                <div class="fs-4 fw-semibold text-danger"><?php echo (int)$stats['login_failed']; ?></div>
            </div>
        </div>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
        <div class="card card-soft h-100">
            <div class="card-body card-soft-body">
                <div class="text-muted small mb-1">Odjave</div>
                <div class="fs-4 fw-semibold"><?php echo (int)$stats['logout']; ?></div>
            </div>
        </div>
    </div>
</div>

<div class="card card-soft mb-3">
    <div class="card-header card-soft-header">
        <span class="fw-semibold">Filter logova</span>
    </div>
    <div class="card-body card-soft-body">
        <form method="get" class="row g-2 align-items-end">
            <div class="col-12 col-lg-4">
                <label class="form-label">Pretraga</label>
                <input type="text" name="q" class="form-control form-control-sm" placeholder="korisnik, IP, detalj..." value="<?php echo htmlspecialchars($q); ?>">
            </div>
            <div class="col-6 col-lg-2">
                <label class="form-label">Događaj</label>
                <select name="event" class="form-select form-select-sm">
                    <option value="">Svi</option>
                    <option value="login_success" <?php echo $event==='login_success' ? 'selected' : ''; ?>>Uspješna prijava</option>
                    <option value="login_failed" <?php echo $event==='login_failed' ? 'selected' : ''; ?>>Neuspješna prijava</option>
                    <option value="logout" <?php echo $event==='logout' ? 'selected' : ''; ?>>Odjava</option>
                </select>
            </div>
            <div class="col-6 col-lg-2">
                <label class="form-label">Datum od</label>
                <input type="date" name="date_from" class="form-control form-control-sm" value="<?php echo htmlspecialchars($dateFrom); ?>">
            </div>
            <div class="col-6 col-lg-2">
                <label class="form-label">Datum do</label>
                <input type="date" name="date_to" class="form-control form-control-sm" value="<?php echo htmlspecialchars($dateTo); ?>">
            </div>
            <div class="col-6 col-lg-1">
                <label class="form-label">Broj</label>
                <select name="limit" class="form-select form-select-sm">
                    <?php foreach ([50,100,200,500] as $lim): ?>
                        <option value="<?php echo $lim; ?>" <?php echo $limit===$lim ? 'selected' : ''; ?>><?php echo $lim; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-12 col-lg-1 d-grid">
                <button class="btn btn-primary btn-soft btn-sm" type="submit">Primijeni</button>
            </div>
        </form>
    </div>
</div>

<div class="card card-soft">
    <div class="card-header card-soft-header d-flex justify-content-between align-items-center">
        <span class="fw-semibold">Zapisi</span>
        <span class="pill-counter d-none d-sm-inline"><?php echo $res ? (int)$res->num_rows : 0; ?> zapisa</span>
    </div>
    <div class="card-body card-soft-body">
        <div class="table-responsive d-none d-md-block">
            <table class="table table-sm align-middle">
                <thead class="small text-muted">
                    <tr>
                        <th>Vrijeme</th>
                        <th>Događaj</th>
                        <th>Korisnik</th>
                        <th>IP</th>
                        <th>Detalj</th>
                        <th>User-Agent</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$res || $res->num_rows === 0): ?>
                    <tr><td colspan="6" class="text-muted small">Nema logova za odabrane kriterije.</td></tr>
                <?php else: ?>
                    <?php while ($row = $res->fetch_assoc()): ?>
                        <tr>
                            <td class="small"><?php echo htmlspecialchars((string)$row['created_at']); ?></td>
                            <td><span class="badge rounded-pill text-bg-<?php echo event_badge_class((string)$row['event_type']); ?>"><?php echo htmlspecialchars(event_label((string)$row['event_type'])); ?></span></td>
                            <td>
                                <div class="fw-semibold"><?php echo htmlspecialchars((string)($row['username_attempted'] ?: '-')); ?></div>
                                <?php if (!empty($row['user_id'])): ?><div class="text-muted small">ID: <?php echo (int)$row['user_id']; ?></div><?php endif; ?>
                            </td>
                            <td class="small"><?php echo htmlspecialchars((string)($row['ip_address'] ?: '-')); ?></td>
                            <td class="small">
                                <?php echo htmlspecialchars((string)($row['details'] ?: '-')); ?>
                                <?php if (!empty($row['session_id'])): ?><div class="text-muted">SID: <?php echo htmlspecialchars((string)$row['session_id']); ?></div><?php endif; ?>
                            </td>
                            <td class="small text-break" style="max-width:320px;"><?php echo htmlspecialchars((string)($row['user_agent'] ?: '-')); ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="d-md-none">
            <?php if (!$res || $res->num_rows === 0): ?>
                <div class="text-muted small">Nema logova za odabrane kriterije.</div>
            <?php else: ?>
                <?php $res->data_seek(0); while ($row = $res->fetch_assoc()): ?>
                    <div class="list-card">
                        <div class="d-flex justify-content-between gap-2 align-items-start">
                            <div class="list-card-title"><?php echo htmlspecialchars((string)($row['username_attempted'] ?: '-')); ?></div>
                            <span class="badge rounded-pill text-bg-<?php echo event_badge_class((string)$row['event_type']); ?>"><?php echo htmlspecialchars(event_label((string)$row['event_type'])); ?></span>
                        </div>
                        <div class="list-card-sub"><?php echo htmlspecialchars((string)$row['created_at']); ?></div>
                        <div class="list-card-meta">
                            IP: <?php echo htmlspecialchars((string)($row['ip_address'] ?: '-')); ?><br>
                            <?php if (!empty($row['details'])): ?>Detalj: <?php echo htmlspecialchars((string)$row['details']); ?><br><?php endif; ?>
                            <?php if (!empty($row['session_id'])): ?>SID: <?php echo htmlspecialchars((string)$row['session_id']); ?><br><?php endif; ?>
                            UA: <?php echo htmlspecialchars((string)($row['user_agent'] ?: '-')); ?>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php if ($stmt) $stmt->close(); ?>
<?php require_once 'footer.php'; ?>
