<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config/database.php';
require_once '../includes/functions.php';

if (!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'admin') {
    header('Location: ../index.php');
    exit;
}

// ========== دریافت پارامترهای فیلتر ==========
$filter_user = $_GET['filter_user'] ?? '';
$filter_event = $_GET['filter_event'] ?? '';
$filter_from = $_GET['filter_from'] ?? '';
$filter_to = $_GET['filter_to'] ?? '';

// ========== ساخت کوئری ==========
$query = "SELECT sl.*, u.fullname as user_name 
          FROM system_logs sl 
          LEFT JOIN users u ON sl.user_id = u.id 
          WHERE 1=1";

$params = [];

if (!empty($filter_user)) {
    $query .= " AND sl.user_id = ?";
    $params[] = $filter_user;
}
if (!empty($filter_event)) {
    $query .= " AND sl.event_type LIKE ?";
    $params[] = "%$filter_event%";
}
if (!empty($filter_from)) {
    $query .= " AND DATE(sl.created_at) >= ?";
    $params[] = $filter_from;
}
if (!empty($filter_to)) {
    $query .= " AND DATE(sl.created_at) <= ?";
    $params[] = $filter_to;
}

$query .= " ORDER BY sl.created_at DESC LIMIT 200";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$logs = $stmt->fetchAll();

// ========== دریافت لیست کاربران برای فیلتر ==========
$users = $pdo->query("SELECT id, fullname FROM users ORDER BY fullname")->fetchAll();
?>
<?php include '../includes/header.php'; ?>

<style>
.filter-section {
    background: #f8fafc;
    border-radius: 12px;
    padding: 18px 20px;
    border: 1px solid #e9edf2;
    margin-bottom: 20px;
}
.filter-section .filter-title {
    font-weight: 600;
    font-size: 0.9rem;
    color: #0f172a;
    margin-bottom: 12px;
}
.table-modern {
    font-size: 0.85rem;
}
.table-modern thead th {
    background: #f8fafc;
    color: #475569;
    font-weight: 600;
    font-size: 0.7rem;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    padding: 10px 14px;
    border-bottom: 2px solid #e9edf2;
}
.table-modern tbody td {
    padding: 10px 14px;
    border-bottom: 1px solid #f1f5f9;
    vertical-align: middle;
}
.table-modern tbody tr:hover {
    background: #f8fafc;
}
.event-badge {
    padding: 3px 12px;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 600;
}
.event-badge.login { background: #dcfce7; color: #16a34a; }
.event-badge.logout { background: #fee2e2; color: #dc2626; }
.event-badge.create { background: #dbeafe; color: #2563eb; }
.event-badge.edit { background: #fef3c7; color: #d97706; }
.event-badge.delete { background: #fecaca; color: #dc2626; }
.event-badge.archive { background: #e0e7ff; color: #4f46e5; }
.event-badge.restore { background: #dcfce7; color: #16a34a; }
</style>

<!-- ============================================================
بخش فیلترها
============================================================ -->
<div class="filter-section">
    <div class="filter-title"><i class="bi bi-funnel me-2"></i>فیلترهای جستجو</div>
    <form method="GET" class="row g-2">
        <div class="col-md-3">
            <select name="filter_user" class="form-select">
                <option value="">همه کاربران</option>
                <?php foreach($users as $user): ?>
                    <option value="<?php echo $user['id']; ?>" <?php echo $filter_user == $user['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($user['fullname']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <input type="text" name="filter_event" class="form-control" placeholder="نوع رویداد (login, edit, ...)" value="<?php echo htmlspecialchars($filter_event); ?>">
        </div>
        <div class="col-md-2">
            <input type="date" name="filter_from" class="form-control" placeholder="از تاریخ" value="<?php echo $filter_from; ?>">
        </div>
        <div class="col-md-2">
            <input type="date" name="filter_to" class="form-control" placeholder="تا تاریخ" value="<?php echo $filter_to; ?>">
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-pastel w-100"><i class="bi bi-search"></i> فیلتر</button>
        </div>
    </form>
</div>

<!-- ============================================================
جدول لاگ‌ها
============================================================ -->
<div class="card">
    <div class="card-header">
        <i class="bi bi-clock-history"></i> لاگ سیستم
        <span class="badge bg-primary ms-2"><?php echo toPersianNumbers(count($logs)); ?></span>
        <a href="system_logs.php" class="btn btn-sm btn-secondary float-start">🔄 نمایش همه</a>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern mb-0">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>تاریخ</th>
                        <th>کاربر</th>
                        <th>رویداد</th>
                        <th>توضیحات</th>
                        <th>IP</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($logs) > 0): ?>
                        <?php $counter = 1; ?>
                        <?php foreach ($logs as $log): ?>
                        <tr>
                            <td><?php echo toPersianNumbers($counter++); ?></td>
                            <td><?php echo convertToPersianDateFa($log['created_at']); ?></td>
                            <td><?php echo htmlspecialchars($log['user_name'] ?? 'سیستم'); ?></td>
                            <td>
                                <span class="event-badge <?php 
                                    $eventClass = '';
                                    if (strpos($log['event_type'], 'login') !== false) $eventClass = 'login';
                                    elseif (strpos($log['event_type'], 'logout') !== false) $eventClass = 'logout';
                                    elseif (strpos($log['event_type'], 'create') !== false) $eventClass = 'create';
                                    elseif (strpos($log['event_type'], 'edit') !== false) $eventClass = 'edit';
                                    elseif (strpos($log['event_type'], 'delete') !== false) $eventClass = 'delete';
                                    elseif (strpos($log['event_type'], 'archive') !== false) $eventClass = 'archive';
                                    elseif (strpos($log['event_type'], 'restore') !== false) $eventClass = 'restore';
                                ?>">
                                    <?php echo htmlspecialchars($log['event_type']); ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($log['description'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars($log['ip_address'] ?? '-'); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" class="text-center py-4 text-muted">
                                <i class="bi bi-inbox" style="font-size: 2rem; display: block; margin-bottom: 8px;"></i>
                                هیچ لاگی یافت نشد
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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