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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit();
}

// Check if user is admin
if (!checkPermission('admin', $_SESSION['role'])) {
    echo json_encode(['success' => false, 'error' => 'Access denied']);
    exit();
}

$input = json_decode(file_get_contents('php://input'), true);
$days = (int)($input['days'] ?? 30);

if ($days <= 0) {
    echo json_encode(['success' => false, 'error' => 'Invalid days parameter']);
    exit();
}

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

try {
    // Delete old activity logs
    $stmt = $conn->prepare("DELETE FROM activity_log WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)");
    $stmt->execute([$days]);
    $deleted_count = $stmt->rowCount();
    
    // Log this activity
    logActivity($conn, $_SESSION['user_id'], "تنظيف سجلات النشاط (حذف السجلات الأقدم من $days يوم)", 'activity_log', null);
    
    // Create notification
    createNotification($conn, $_SESSION['user_id'], 'تنظيف السجلات', "تم حذف $deleted_count سجل من سجلات النشاط", 'success');
    
    echo json_encode([
        'success' => true,
        'deleted_count' => $deleted_count,
        'message' => "تم حذف $deleted_count سجل بنجاح"
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
