<?php

namespace Core\App\Controllers;

use Core\App\Models\SystemCleanup;
use Core\System\Response;

class SystemCleanupController
{
    public function index()
    {
        $model = new SystemCleanup();

        $stats = [
            'admin_notifications'  => $model->countRows('admin_notifications'),
            'admin_activity_log'   => $model->countRows('admin_activity_log'),
            'admin_password_resets'=> $model->countRows('admin_password_resets'),
            'page_views'           => $model->countRows('page_views'),
            'security_logs'        => $model->countRows('security_logs'),
            'security_rate_limits' => $model->countRows('security_rate_limits'),
            'fraud_attempts'       => $model->countRows('fraud_attempts'),
            'safe_updater_jobs'    => $model->countRows('safe_updater_jobs'),
            'whatsapp_messages'    => $model->countRows('whatsapp_messages'),
            'ai_landing_pages'     => $model->countRows('ai_landing_pages'),
        ];

        extract(['stats' => $stats]);

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/system/cleanup.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    public function run()
    {
        $model = new SystemCleanup();

        $action = trim((string)($_POST['action'] ?? ''));
        $days   = (int)($_POST['days'] ?? 30);
        if ($days <= 0) {
            $days = 30;
        }

        $deleted = 0;

        switch ($action) {
            case 'purge_notifications_all':
                $model->purgeNotificationsAll();
                Response::redirect('/admin/system/cleanup?done=1&type=notifications_all');
                break;
            case 'purge_notifications_old':
                $deleted = $model->purgeNotificationsOlderThan($days);
                Response::redirect('/admin/system/cleanup?done=1&type=notifications_old&rows=' . $deleted);
                break;
            case 'purge_page_views_old':
                $deleted = $model->purgePageViewsOlderThan($days);
                Response::redirect('/admin/system/cleanup?done=1&type=page_views&rows=' . $deleted);
                break;
            case 'purge_page_views_all':
                $model->purgePageViewsAll();
                Response::redirect('/admin/system/cleanup?done=1&type=page_views_all');
                break;
            case 'purge_security_logs_old':
                $deleted = $model->purgeSecurityLogsOlderThan($days);
                Response::redirect('/admin/system/cleanup?done=1&type=security_logs&rows=' . $deleted);
                break;
            case 'purge_security_logs_all':
                $model->purgeSecurityLogsAll();
                Response::redirect('/admin/system/cleanup?done=1&type=security_logs_all');
                break;
            case 'purge_security_404_7':
                $deleted = $model->purgeSecurityLogsByTypeOlderThan('404', 7);
                Response::redirect('/admin/system/cleanup?done=1&type=security_404&rows=' . $deleted);
                break;
            case 'purge_security_warning_30':
                $deleted = $model->purgeSecurityLogsByTypeOlderThan('warning', 30);
                Response::redirect('/admin/system/cleanup?done=1&type=security_warning&rows=' . $deleted);
                break;
            case 'purge_security_error_30':
                $deleted = $model->purgeSecurityLogsByTypeOlderThan('error', 30);
                Response::redirect('/admin/system/cleanup?done=1&type=security_error&rows=' . $deleted);
                break;
            case 'purge_rate_limits_old':
                $deleted = $model->purgeRateLimitsOlderThan($days);
                Response::redirect('/admin/system/cleanup?done=1&type=rate_limits&rows=' . $deleted);
                break;
            case 'purge_rate_limits_all':
                $model->purgeRateLimitsAll();
                Response::redirect('/admin/system/cleanup?done=1&type=rate_limits_all');
                break;
            case 'purge_fraud_attempts_old':
                $deleted = $model->purgeFraudAttemptsOlderThan($days);
                Response::redirect('/admin/system/cleanup?done=1&type=fraud_attempts&rows=' . $deleted);
                break;
            case 'purge_fraud_attempts_all':
                $model->purgeFraudAttemptsAll();
                Response::redirect('/admin/system/cleanup?done=1&type=fraud_attempts_all');
                break;
            case 'purge_admin_activity_old':
                $deleted = $model->purgeAdminActivityOlderThan($days);
                Response::redirect('/admin/system/cleanup?done=1&type=admin_activity&rows=' . $deleted);
                break;
            case 'purge_admin_activity_all':
                $model->purgeAdminActivityAll();
                Response::redirect('/admin/system/cleanup?done=1&type=admin_activity_all');
                break;
            case 'purge_password_resets_expired':
                $deleted = $model->purgeExpiredPasswordResets();
                Response::redirect('/admin/system/cleanup?done=1&type=password_resets_expired&rows=' . $deleted);
                break;
            case 'purge_password_resets_old':
                $deleted = $model->purgePasswordResetsOlderThan($days);
                Response::redirect('/admin/system/cleanup?done=1&type=password_resets_old&rows=' . $deleted);
                break;
            case 'purge_updater_jobs_old':
                $deleted = $model->purgeUpdaterJobsOlderThan($days);
                Response::redirect('/admin/system/cleanup?done=1&type=updater_jobs_old&rows=' . $deleted);
                break;
            case 'purge_updater_jobs_finished':
                $deleted = $model->purgeUpdaterJobsAllFinished();
                Response::redirect('/admin/system/cleanup?done=1&type=updater_jobs_finished&rows=' . $deleted);
                break;
            case 'purge_whatsapp_messages_old':
                $deleted = $model->purgeWhatsappMessagesOlderThan($days);
                Response::redirect('/admin/system/cleanup?done=1&type=whatsapp_old&rows=' . $deleted);
                break;
            case 'purge_whatsapp_messages_all':
                $model->purgeWhatsappMessagesAll();
                Response::redirect('/admin/system/cleanup?done=1&type=whatsapp_all');
                break;
            case 'purge_ai_landing_drafts_old':
                $deleted = $model->purgeAiLandingDraftsOlderThan($days);
                Response::redirect('/admin/system/cleanup?done=1&type=ai_landing_drafts&rows=' . $deleted);
                break;
            default:
                Response::redirect('/admin/system/cleanup?error=1');
        }
    }

    public function clearCache()
    {
        \Core\System\Csrf::check();
        \Core\System\PageCache::clear();
        $_SESSION['success'] = __('system.cache_cleared', '✅ تم مسح ذاكرة التخزين (الكاش) بنجاح');
        \Core\System\Response::back('/admin/dashboard');
    }
}
