<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/auth.php';
requirePermission('log_delete');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: logs.php');
    exit;
}
requireCsrfToken();

try {
    $action = (string)($_POST['action'] ?? '');
    if ($action !== 'cleanup_old') throw new Exception('알 수 없는 로그 정리 작업입니다.');
    if (trim((string)($_POST['confirm_phrase'] ?? '')) !== '삭제합니다') throw new Exception('확인 문구가 일치하지 않습니다.');
    $stmt = getDBConnection()->prepare("DELETE FROM app_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 90 DAY)");
    $stmt->execute();
    logMaintenance('cleanup_app_logs', '오래된 앱 로그 정리: ' . $stmt->rowCount() . '건');
    writeAuditLog('log_cleanup', 'Old app logs cleaned: ' . $stmt->rowCount(), 'success', 'warning', 'app_logs');
    writeAppLog('info', 'maintenance', 'Old app logs cleaned', ['deleted' => $stmt->rowCount()]);
    header('Location: logs.php?status=success&message=' . urlencode('오래된 로그를 정리했습니다: ' . $stmt->rowCount() . '건'));
} catch (Exception $e) {
    writeAppLog('error', 'maintenance', $e->getMessage());
    header('Location: logs.php?status=error&message=' . urlencode($e->getMessage()));
}
exit;
