<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

// ================= FETCH LOGIN LOGS =================
$logs = $conn->query("
    SELECT ll.*, u.username
    FROM user_logs ll
    LEFT JOIN users u ON ll.user_id = u.id
    ORDER BY ll.login_time DESC
");

// ================= SUMMARY STATS =================
$today      = date('Y-m-d');
$week_start = date('Y-m-d', strtotime('-7 days'));
$month_start= date('Y-m-01');

// Daily
$daily_total = $conn->query("
    SELECT COUNT(*) as total 
    FROM user_logs 
    WHERE DATE(login_time)='$today'
")->fetch_assoc()['total'] ?? 0;

// Weekly
$weekly_total = $conn->query("
    SELECT COUNT(*) as total 
    FROM user_logs 
    WHERE login_time >= '$week_start'
")->fetch_assoc()['total'] ?? 0;

// Monthly
$monthly_total = $conn->query("
    SELECT COUNT(*) as total 
    FROM user_logs 
    WHERE login_time >= '$month_start'
")->fetch_assoc()['total'] ?? 0;

// Average session duration (minutes)
$avg_session = $conn->query("
    SELECT AVG(TIMESTAMPDIFF(MINUTE, login_time, logout_time)) as avg_minutes
    FROM user_logs
    WHERE logout_time IS NOT NULL
")->fetch_assoc()['avg_minutes'] ?? 0;
?>

<div class="container mt-4">
    <h4><i class="fa fa-history"></i> Login Logs</h4>
    <hr>

    <!-- ================= SUMMARY CARDS ================= -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <h6>Today Logins</h6>
                    <h3><?= $daily_total ?></h3>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <h6>Last 7 Days</h6>
                    <h3><?= $weekly_total ?></h3>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <h6>This Month</h6>
                    <h3><?= $monthly_total ?></h3>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card bg-dark text-white">
                <div class="card-body">
                    <h6>Avg Session (mins)</h6>
                    <h3><?= number_format($avg_session,1) ?></h3>
                </div>
            </div>
        </div>
    </div>

    <!-- ================= LOGIN TABLE ================= -->
    <div class="card">
        <div class="card-header bg-info text-white">
            System Login History
        </div>
        <div class="card-body">

            <table class="table table-bordered table-striped table-sm">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Username</th>
                        <th>IP Address</th>
                        <th>Login Time</th>
                        <th>Logout Time</th>
                        <th>Duration</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                <?php $i=1; while($log = $logs->fetch_assoc()): 

                    // ===== SESSION DURATION =====
                    $duration_text = '<span class="text-warning">Active</span>';

                    if(!empty($log['logout_time'])){
                        $seconds = strtotime($log['logout_time']) - strtotime($log['login_time']);
                        $hours   = floor($seconds / 3600);
                        $minutes = floor(($seconds % 3600) / 60);
                        $duration_text = "{$hours}h {$minutes}m";
                    }
                ?>
                    <tr>
                        <td><?= $i ?></td>
                        <td><?= htmlspecialchars($log['username'] ?? 'Unknown') ?></td>
                        <td><?= htmlspecialchars($log['ip_address'] ?? '') ?></td>

                        <td><?= date("d-M-Y H:i:s", strtotime($log['login_time'])) ?></td>

                        <td>
                            <?= !empty($log['logout_time'])
                                ? date("d-M-Y H:i:s", strtotime($log['logout_time']))
                                : '<span class="badge bg-warning">Active</span>' ?>
                        </td>

                        <td><?= $duration_text ?></td>

                        <td>
                            <?php if(($log['status'] ?? '')=='Success'): ?>
                                <span class="badge bg-success">Success</span>
                            <?php else: ?>
                                <span class="badge bg-danger">Failed</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php $i++; endwhile; ?>
                </tbody>
            </table>

        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
