<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'includes/translation.php';
require_once 'includes/page_permissions_helper.php';

if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

// Set current page for permissions
$currentPage = 'activity_log';

// Check page access permission
PagePermissions::requirePageAccess($currentPage);

$db = new Database();
$conn = $db->getConnection();

// Handle filters
$user_filter = $_GET['user_id'] ?? '';
$action_filter = $_GET['action'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 50;
$offset = ($page - 1) * $per_page;

// Build query
$where_conditions = [];
$params = [];

if (!empty($user_filter)) {
    $where_conditions[] = "al.user_id = ?";
    $params[] = $user_filter;
}

if (!empty($action_filter)) {
    $where_conditions[] = "al.action LIKE ?";
    $params[] = "%$action_filter%";
}

if (!empty($date_from)) {
    $where_conditions[] = "DATE(al.created_at) >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(al.created_at) <= ?";
    $params[] = $date_to;
}

$where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";

// Get total count
$count_sql = "
    SELECT COUNT(*) as total
    FROM activity_log al
    JOIN users u ON al.user_id = u.id
    $where_clause
";
$stmt = $conn->prepare($count_sql);
$stmt->execute($params);
$total_records = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
$total_pages = ceil($total_records / $per_page);

// Get activities
$sql = "
    SELECT 
        al.*,
        u.full_name as user_name,
        u.username
    FROM activity_log al
    JOIN users u ON al.user_id = u.id
    $where_clause
    ORDER BY al.created_at DESC
    LIMIT $per_page OFFSET $offset
";
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$activities = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get users for filter
$users = $conn->query("SELECT id, full_name, username FROM users ORDER BY full_name")->fetchAll(PDO::FETCH_ASSOC);

// Set page title
$page_title = __('activity_log_page') . ' - ' . __('system_name');

// Include header
include 'includes/header.php';
?>

<style>
.activity-item {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 15px;
    transition: all 0.3s ease;
    background: white;
}

.activity-item:hover {
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    transform: translateY(-2px);
}

.activity-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.3rem;
    margin-left: 20px;
}

.activity-icon.create { background-color: #d4edda; color: #155724; }
.activity-icon.update { background-color: #fff3cd; color: #856404; }
.activity-icon.delete { background-color: #f8d7da; color: #721c24; }
.activity-icon.login { background-color: #d1ecf1; color: #0c5460; }
.activity-icon.logout { background-color: #f8d7da; color: #721c24; }
.activity-icon.view { background-color: #e2e3e5; color: #383d41; }

.filter-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 15px;
    padding: 25px;
    margin-bottom: 25px;
}

.filter-card .form-label {
    color: white;
    font-weight: 500;
}

.filter-card .form-control,
.filter-card .form-select {
    border: none;
    border-radius: 8px;
}

.pagination-custom .page-link {
    border-radius: 8px;
    margin: 0 2px;
    border: none;
    color: #495057;
}

.pagination-custom .page-item.active .page-link {
    background-color: #007bff;
    border-color: #007bff;
}

.json-viewer {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 5px;
    padding: 10px;
    font-family: 'Courier New', monospace;
    font-size: 0.85rem;
    max-height: 200px;
    overflow-y: auto;
}
</style>

<!-- Main Content -->

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0"><?php echo __('activity_log_page'); ?></h1>
        <div>
            <?php if (PagePermissions::hasPermission($currentPage, 'export_activity_log')): ?>
            <button type="button" class="btn btn-outline-success me-2" onclick="exportLog()">
                <i class="fas fa-file-excel"></i> <?php echo __('export'); ?>
            </button>
            <?php endif; ?>
            
            <?php if (PagePermissions::hasPermission($currentPage, 'clear_activity_log')): ?>
            <button type="button" class="btn btn-outline-danger me-2" onclick="clearOldLogs()">
                <i class="fas fa-trash"></i> <?php echo __('clear_old_logs'); ?>
            </button>
            <?php endif; ?>
            
            <a href="admin_dashboard.php" class="btn btn-secondary">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?>"></i> <?php echo __('back_to_admin_dashboard'); ?>
            </a>
        </div>
    </div>

    <!-- Filters -->
    <div class="filter-card">
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <label for="user_id" class="form-label"><?php echo __('user'); ?></label>
                <select class="form-select" id="user_id" name="user_id">
                    <option value=""><?php echo __('all_users'); ?></option>
                    <?php foreach ($users as $user): ?>
                        <option value="<?php echo $user['id']; ?>" <?php echo $user_filter == $user['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($user['full_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-3">
                <label for="action" class="form-label">النشاط</label>
                <input type="text" class="form-control" id="action" name="action" 
                       placeholder="البحث في النشاط..." value="<?php echo htmlspecialchars($action_filter); ?>">
            </div>
            
            <div class="col-md-2">
                <label for="date_from" class="form-label">من تاريخ</label>
                <input type="date" class="form-control" id="date_from" name="date_from" 
                       value="<?php echo htmlspecialchars($date_from); ?>">
            </div>
            
            <div class="col-md-2">
                <label for="date_to" class="form-label">إلى تاريخ</label>
                <input type="date" class="form-control" id="date_to" name="date_to" 
                       value="<?php echo htmlspecialchars($date_to); ?>">
            </div>
            
            <div class="col-md-2 d-flex align-items-end">
                <button type="submit" class="btn btn-light me-2">
                    <i class="fas fa-search"></i> بحث
                </button>
                <a href="activity_log.php" class="btn btn-outline-light">
                    <i class="fas fa-times"></i> مسح
                </a>
            </div>
        </form>
    </div>

    <!-- Statistics -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h4 class="text-primary"><?php echo number_format($total_records); ?></h4>
                    <small class="text-muted">إجمالي النشاطات</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h4 class="text-success"><?php echo count($activities); ?></h4>
                    <small class="text-muted">في هذه الصفحة</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h4 class="text-info"><?php echo $total_pages; ?></h4>
                    <small class="text-muted">إجمالي الصفحات</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center">
                <div class="card-body">
                    <h4 class="text-warning"><?php echo $page; ?></h4>
                    <small class="text-muted">الصفحة الحالية</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Activities List -->
    <?php if (empty($activities)): ?>
        <div class="text-center py-5">
            <i class="fas fa-history fa-3x text-muted mb-3"></i>
            <h5 class="text-muted">لا توجد نشاطات</h5>
            <p class="text-muted">لم يتم العثور على نشاطات تطابق المعايير المحددة</p>
        </div>
    <?php else: ?>
        <div class="activities-list">
            <?php foreach ($activities as $activity): ?>
                <div class="activity-item">
                    <div class="d-flex align-items-start">
                        <div class="activity-icon <?php 
                            echo strpos($activity['action'], 'إضافة') !== false ? 'create' : 
                                (strpos($activity['action'], 'تعديل') !== false ? 'update' : 
                                (strpos($activity['action'], 'حذف') !== false ? 'delete' : 
                                (strpos($activity['action'], 'دخول') !== false ? 'login' : 
                                (strpos($activity['action'], 'خروج') !== false ? 'logout' : 'view')))); 
                        ?>">
                            <i class="fas fa-<?php 
                                echo strpos($activity['action'], 'إضافة') !== false ? 'plus' : 
                                    (strpos($activity['action'], 'تعديل') !== false ? 'edit' : 
                                    (strpos($activity['action'], 'حذف') !== false ? 'trash' : 
                                    (strpos($activity['action'], 'دخول') !== false ? 'sign-in-alt' : 
                                    (strpos($activity['action'], 'خروج') !== false ? 'sign-out-alt' : 'eye')))); 
                            ?>"></i>
                        </div>
                        
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <div>
                                    <h6 class="mb-1"><?php echo htmlspecialchars($activity['user_name']); ?></h6>
                                    <p class="mb-1 text-primary"><?php echo htmlspecialchars($activity['action']); ?></p>
                                </div>
                                <small class="text-muted">
                                    <i class="fas fa-clock me-1"></i>
                                    <?php echo formatTimeAgo($activity['created_at']); ?>
                                </small>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <?php if ($activity['table_name']): ?>
                                        <p class="mb-1"><strong>الجدول:</strong> <?php echo htmlspecialchars($activity['table_name']); ?></p>
                                    <?php endif; ?>
                                    
                                    <?php if ($activity['record_id']): ?>
                                        <p class="mb-1"><strong>معرف السجل:</strong> <?php echo $activity['record_id']; ?></p>
                                    <?php endif; ?>
                                    
                                    <?php if ($activity['ip_address']): ?>
                                        <p class="mb-1"><strong>عنوان IP:</strong> <?php echo htmlspecialchars($activity['ip_address']); ?></p>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="col-md-6">
                                    <p class="mb-1"><strong>التاريخ الكامل:</strong> <?php echo date('Y-m-d H:i:s', strtotime($activity['created_at'])); ?></p>
                                    <p class="mb-1"><strong>المستخدم:</strong> <?php echo htmlspecialchars($activity['username']); ?></p>
                                </div>
                            </div>
                            
                            <?php if ($activity['old_values'] || $activity['new_values']): ?>
                                <div class="mt-3">
                                    <button class="btn btn-sm btn-outline-info" type="button" data-bs-toggle="collapse" 
                                            data-bs-target="#details_<?php echo $activity['id']; ?>">
                                        <i class="fas fa-info-circle"></i> عرض التفاصيل
                                    </button>
                                    
                                    <div class="collapse mt-2" id="details_<?php echo $activity['id']; ?>">
                                        <?php if ($activity['old_values']): ?>
                                            <div class="mb-2">
                                                <strong>القيم القديمة:</strong>
                                                <div class="json-viewer"><?php echo htmlspecialchars($activity['old_values']); ?></div>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($activity['new_values']): ?>
                                            <div class="mb-2">
                                                <strong>القيم الجديدة:</strong>
                                                <div class="json-viewer"><?php echo htmlspecialchars($activity['new_values']); ?></div>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($activity['user_agent']): ?>
                                            <div class="mb-2">
                                                <strong>متصفح المستخدم:</strong>
                                                <small class="text-muted"><?php echo htmlspecialchars($activity['user_agent']); ?></small>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <nav aria-label="صفحات سجل النشاطات">
                <ul class="pagination pagination-custom justify-content-center">
                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">
                                <i class="fas fa-chevron-right"></i>
                            </a>
                        </li>
                    <?php endif; ?>
                    
                    <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>">
                                <?php echo $i; ?>
                            </a>
                        </li>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">
                                <i class="fas fa-chevron-left"></i>
                            </a>
                        </li>
                    <?php endif; ?>
                </ul>
            </nav>
        <?php endif; ?>
    <?php endif; ?>
</div>

<script>
function clearOldLogs() {
    const days = prompt('كم يوماً تريد الاحتفاظ بالسجلات؟ (سيتم حذف السجلات الأقدم)', '30');
    
    if (days && !isNaN(days) && days > 0) {
        if (confirm(`هل أنت متأكد من حذف السجلات الأقدم من ${days} يوم؟`)) {
            fetch('api/clear_logs.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ days: parseInt(days) })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(`تم حذف ${data.deleted_count} سجل بنجاح`);
                    location.reload();
                } else {
                    alert('حدث خطأ: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('حدث خطأ في العملية');
            });
        }
    }
}

// Auto-refresh every 30 seconds
setInterval(function() {
    // Only refresh if we're on the first page and no filters are applied
    const urlParams = new URLSearchParams(window.location.search);
    if (!urlParams.has('page') && !urlParams.has('user_id') && !urlParams.has('action')) {
        location.reload();
    }
}, 30000);
</script>

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