<?php

if (!defined('ABSPATH')) {
    exit;
}

add_action('wp_ajax_ss_download_all_css_files', 'ss_download_all_css_files_handler');

function ss_download_all_css_files_handler() {
    check_ajax_referer('ss-export-css-files', 'nonce');

    $css_dir = WP_CONTENT_DIR . '/ss-css';
    $upload_dir = wp_upload_dir();
    $base_upload_dir = $upload_dir['basedir'];
    $base_upload_url = $upload_dir['baseurl'];
    $export_dir = $base_upload_dir . '/ss-exports';

    if (!file_exists($css_dir) || !is_dir($css_dir)) {
        wp_send_json_error(['message' => 'CSS directory not found.']);
		return;
    }

    if (!file_exists($export_dir)) {
        mkdir($export_dir, 0755, true);
    }

    $timestamp = time();
    $zip_file_name = "ss-all-super-style-{$timestamp}.zip";
    $zip_file_path = "{$export_dir}/{$zip_file_name}";

    $zip = new ZipArchive();
    if ($zip->open($zip_file_path, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
        wp_send_json_error(['message' => 'Failed to create ZIP archive.']);
		return;
    }

    $files = array_merge(
        glob("{$css_dir}/*.css"),
        glob("{$css_dir}/*.js")
    );
    foreach ($files as $file) {
        $zip->addFile($file, basename($file));
    }

    if (!$zip->close()) {
        wp_send_json_error(['message' => 'Failed to close ZIP archive.']);
        return;
    }

    $zip_file_url = "{$base_upload_url}/ss-exports/{$zip_file_name}";

    wp_send_json_success(['message' => 'Archive created successfully.', 'zip_url' => $zip_file_url]);
}

add_action('ss_cleanup_old_exports', 'ss_cleanup_old_exports_handler');

function ss_cleanup_old_exports_handler() {
    $export_dir = WP_CONTENT_DIR . '/uploads/ss-exports';

    if (!file_exists($export_dir) || !is_dir($export_dir)) {
        return;
    }

    $files = glob("{$export_dir}/*.zip");
    $now = time();
    foreach ($files as $file) {
        if ($now - filemtime($file) > 3600) {
            unlink($file);
        }
    }
}

if (!wp_next_scheduled('ss_cleanup_old_exports')) {
    wp_schedule_event(time(), 'hourly', 'ss_cleanup_old_exports');
}