<?php
include '../config/db.php';
session_start();

// Redirect to login if not admin
if (!isset($_SESSION['username']) || $_SESSION['role'] != 'admin') {
    header("Location: login.php");
    exit();
}

// Function to calculate relative time or show exact time and date
function timeAgo($timestamp) {
    $timeDifference = time() - strtotime($timestamp);

    if ($timeDifference < 60) {
        return $timeDifference . " seconds ago";
    } elseif ($timeDifference < 3600) {
        return floor($timeDifference / 60) . " minutes ago";
    } elseif ($timeDifference < 43200) { // 12 hours = 43200 seconds
        return floor($timeDifference / 3600) . " hours ago";
    } else {
        return date("F j, Y, g:i a", strtotime($timestamp)); // Exact date and time
    }
}

// Fetch log history from the database
$stmt = $pdo->query("SELECT lh.timestamp, u.username, lh.action 
                      FROM log_history lh 
                      JOIN users u ON lh.user_id = u.id 
                      ORDER BY lh.timestamp DESC");
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Add pharmacy name for header
$stmt = $pdo->prepare("SELECT pharmacy_name FROM settings LIMIT 1");
$stmt->execute();
$setting = $stmt->fetch(PDO::FETCH_ASSOC);
$pharmacy_name = $setting['pharmacy_name'] ?? 'Default Pharmacy Name';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Log History - <?= htmlspecialchars($pharmacy_name) ?></title>
    <link rel="stylesheet" href="..\libs\bootsrtap2\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <style>
        .main-content {
            margin-left: 230px;
            padding: 20px;
            transition: all 0.3s ease;
        }

        .log-card {
            border: none;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }

        .log-header {
            background: linear-gradient(135deg, #2c3e50, #3498db);
            color: white;
            padding: 1.5rem;
            border-radius: 8px 8px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .log-filters {
            background: #f8f9fa;
            padding: 1rem;
            border-bottom: 1px solid #eee;
        }

        .log-table {
            margin: 0;
        }

        .log-table th {
            background: #f8f9fa;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85rem;
            padding: 1rem;
            border-bottom: 2px solid #dee2e6;
        }

        .log-table td {
            padding: 1rem;
            vertical-align: middle;
        }

        .log-action {
            display: inline-flex;
            align-items: center;
            padding: 0.35rem 0.75rem;
            border-radius: 50px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .log-action.login { background: #e3fcef; color: #0a6c3b; }
        .log-action.logout { background: #fff3cd; color: #997404; }
        .log-action.update { background: #cff4fc; color: #055160; }
        .log-action.delete { background: #f8d7da; color: #842029; }
        .log-action.create { background: #d1e7dd; color: #0a3622; }

        .log-time {
            font-size: 0.85rem;
            color: #6c757d;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .log-user {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            color: #495057;
        }

        @media (max-width: 768px) {
            .main-content {
                margin-left: 0;
            }
            
            .log-header {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }
            
            .log-table {
                font-size: 0.9rem;
            }
        }
    </style>
</head>
<body class="bg-light">
    <?php include '../includes/side_bar.php'; ?>

    <div class="main-content">
        <div class="log-card">
            <div class="log-header">
                <h4 class="mb-0">
                    <i class="fas fa-history me-2"></i>
                    Activity Log
                </h4>
                <div>
                    <button class="btn btn-light" onclick="window.location.reload()">
                        <i class="fas fa-sync-alt me-2"></i>Refresh
                    </button>
                </div>
            </div>

            <div class="log-filters">
                <div class="row g-3">
                    <div class="col-md-4">
                        <input type="text" class="form-control" id="searchLog" 
                               placeholder="Search logs...">
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" id="filterAction">
                            <option value="">All Actions</option>
                            <option value="login">Login</option>
                            <option value="logout">Logout</option>
                            <option value="update">Update</option>
                            <option value="delete">Delete</option>
                            <option value="create">Create</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table log-table">
                    <thead>
                        <tr>
                            <th>User</th>
                            <th>Action</th>
                            <th>Time</th>
                            <th>Details</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($logs as $log): 
                            $actionType = strtolower(explode(' ', $log['action'])[0]);
                        ?>
                            <tr>
                                <td>
                                    <div class="log-user">
                                        <div class="user-avatar">
                                            <i class="fas fa-user"></i>
                                        </div>
                                        <span><?= htmlspecialchars($log['username']) ?></span>
                                    </div>
                                </td>
                                <td>
                                    <span class="log-action <?= $actionType ?>">
                                        <?= htmlspecialchars($log['action']) ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="log-time">
                                        <i class="far fa-clock"></i>
                                        <?= htmlspecialchars(timeAgo($log['timestamp'])) ?>
                                    </div>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-light" 
                                            data-bs-toggle="tooltip" 
                                            title="View Details">
                                        <i class="fas fa-info-circle"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap2\js\bootstrap.bundle.min.js"></script>
    
    <script>
        // Initialize tooltips and other functionality
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize tooltips
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl)
            });

            // Search functionality
            document.getElementById('searchLog').addEventListener('keyup', function() {
                let search = this.value.toLowerCase();
                let rows = document.querySelectorAll('.log-table tbody tr');
                
                rows.forEach(row => {
                    let text = row.textContent.toLowerCase();
                    row.style.display = text.includes(search) ? '' : 'none';
                });
            });

            // Filter by action
            document.getElementById('filterAction').addEventListener('change', function() {
                let filter = this.value.toLowerCase();
                let rows = document.querySelectorAll('.log-table tbody tr');
                
                rows.forEach(row => {
                    let action = row.querySelector('.log-action').textContent.toLowerCase();
                    row.style.display = !filter || action.includes(filter) ? '' : 'none';
                });
            });
        });
    </script>
</body>
</html>
