<?php
// IV1 WP Tools – Custom CSS/JS Code Editor
defined('ABSPATH') || exit;

define('IV1WPT_CUSTOM_CSS_FILE', WP_CONTENT_DIR . '/iv1-custom.css');
define('IV1WPT_CUSTOM_JS_FILE',  WP_CONTENT_DIR . '/iv1-custom.js');
define('IV1WPT_CODEEDITOR_OPTION', 'iv1wpt_codeeditor_settings');

/**
 * Standardeinstellungen für den Code Editor.
 */
function iv1wpt_codeeditor_defaults(): array {
    return [
        'css_enabled'    => false,
        'css_position'   => 'header', // header | footer
        'js_enabled'     => false,
        'js_position'    => 'footer', // header | footer
        'css_content'    => '',
        'js_content'     => '',
    ];
}

/**
 * Custom CSS/JS im Frontend einbinden.
 */
add_action('init', 'iv1wpt_codeeditor_enqueue_frontend', 5);
function iv1wpt_codeeditor_enqueue_frontend(): void {
    if (is_admin()) return;

    $opts = get_option(IV1WPT_CODEEDITOR_OPTION, iv1wpt_codeeditor_defaults());

    // CSS – Header (Standard) oder Footer
    if (!empty($opts['css_enabled']) && file_exists(IV1WPT_CUSTOM_CSS_FILE) && filesize(IV1WPT_CUSTOM_CSS_FILE) > 0) {
        $css_in_footer = ($opts['css_position'] ?? 'header') === 'footer';
        add_action('wp_enqueue_scripts', function () use ($css_in_footer) {
            wp_enqueue_style(
                'iv1-custom-css',
                content_url('iv1-custom.css'),
                [],
                filemtime(IV1WPT_CUSTOM_CSS_FILE),
                $css_in_footer ? false : 'all'
            );
        }, 100);
    }

    // JS – Header oder Footer
    if (!empty($opts['js_enabled']) && file_exists(IV1WPT_CUSTOM_JS_FILE) && filesize(IV1WPT_CUSTOM_JS_FILE) > 0) {
        $in_footer = ($opts['js_position'] ?? 'footer') === 'footer';
        add_action('wp_enqueue_scripts', function () use ($in_footer) {
            wp_enqueue_script(
                'iv1-custom-js',
                content_url('iv1-custom.js'),
                [],
                filemtime(IV1WPT_CUSTOM_JS_FILE),
                $in_footer
            );
        }, 100);
    }
}

/**
 * AJAX: Code Editor Einstellungen und Inhalte laden.
 */
add_action('wp_ajax_iv1wpt_codeeditor_load', 'iv1wpt_codeeditor_load_ajax');
function iv1wpt_codeeditor_load_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    $opts = get_option(IV1WPT_CODEEDITOR_OPTION, iv1wpt_codeeditor_defaults());

    // Dateiihalte lesen (Datenbank hat Vorrang, Datei als Fallback)
    $css_content = $opts['css_content'] ?? '';
    $js_content  = $opts['js_content']  ?? '';

    // Dateigrößen
    $css_size = file_exists(IV1WPT_CUSTOM_CSS_FILE) ? filesize(IV1WPT_CUSTOM_CSS_FILE) : 0;
    $js_size  = file_exists(IV1WPT_CUSTOM_JS_FILE)  ? filesize(IV1WPT_CUSTOM_JS_FILE)  : 0;

    wp_send_json_success([
        'css_enabled'  => !empty($opts['css_enabled']),
        'css_position' => $opts['css_position'] ?? 'header',
        'js_enabled'   => !empty($opts['js_enabled']),
        'js_position'  => $opts['js_position'] ?? 'footer',
        'css_content'  => $css_content,
        'js_content'   => $js_content,
        'css_file'     => IV1WPT_CUSTOM_CSS_FILE,
        'js_file'      => IV1WPT_CUSTOM_JS_FILE,
        'css_url'      => content_url('iv1-custom.css'),
        'js_url'       => content_url('iv1-custom.js'),
        'css_size'     => $css_size,
        'js_size'      => $js_size,
    ]);
}

/**
 * AJAX: CSS speichern.
 */
add_action('wp_ajax_iv1wpt_codeeditor_save_css', 'iv1wpt_codeeditor_save_css_ajax');
function iv1wpt_codeeditor_save_css_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    $content  = wp_unslash($_POST['content'] ?? '');
    $enabled  = !empty($_POST['enabled']);
    $position = sanitize_text_field($_POST['position'] ?? 'header');
    if (!in_array($position, ['header', 'footer'], true)) {
        $position = 'header';
    }

    // In Datei schreiben
    if (file_put_contents(IV1WPT_CUSTOM_CSS_FILE, $content) === false) {
        wp_send_json_error(__('CSS file could not be written. Check wp-content folder permissions.', 'iv1-wp-tools'));
    }

    // Einstellungen speichern
    $opts = get_option(IV1WPT_CODEEDITOR_OPTION, iv1wpt_codeeditor_defaults());
    $opts['css_enabled']  = $enabled;
    $opts['css_position'] = $position;
    $opts['css_content']  = $content;
    update_option(IV1WPT_CODEEDITOR_OPTION, $opts);

    wp_send_json_success([
        'message' => sprintf(
            /* translators: %s: header or footer */
            __('CSS saved successfully. Loaded in: %s', 'iv1-wp-tools'),
            $position
        ),
        'size' => strlen($content),
    ]);
}

/**
 * AJAX: JS speichern.
 */
add_action('wp_ajax_iv1wpt_codeeditor_save_js', 'iv1wpt_codeeditor_save_js_ajax');
function iv1wpt_codeeditor_save_js_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    if (!iv1wpt_has_pro()) {
        wp_send_json_error(__('This feature requires IV1 WP Tools Pro.', 'iv1-wp-tools'));
    }

    $content  = wp_unslash($_POST['content'] ?? '');
    $enabled  = !empty($_POST['enabled']);
    $position = sanitize_text_field($_POST['position'] ?? 'footer');
    if (!in_array($position, ['header', 'footer'], true)) {
        $position = 'footer';
    }

    // In Datei schreiben
    if (file_put_contents(IV1WPT_CUSTOM_JS_FILE, $content) === false) {
        wp_send_json_error(__('JS file could not be written. Check wp-content folder permissions.', 'iv1-wp-tools'));
    }

    // Einstellungen speichern
    $opts = get_option(IV1WPT_CODEEDITOR_OPTION, iv1wpt_codeeditor_defaults());
    $opts['js_enabled']  = $enabled;
    $opts['js_position'] = $position;
    $opts['js_content']  = $content;
    update_option(IV1WPT_CODEEDITOR_OPTION, $opts);

    wp_send_json_success([
        'message' => sprintf(
            /* translators: %s: header or footer */
            __('JavaScript saved successfully. Loaded in: %s', 'iv1-wp-tools'),
            $position
        ),
        'size' => strlen($content),
    ]);
}

/**
 * AJAX: CSS oder JS deaktivieren (Datei bleibt erhalten).
 */
add_action('wp_ajax_iv1wpt_codeeditor_toggle', 'iv1wpt_codeeditor_toggle_ajax');
function iv1wpt_codeeditor_toggle_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    if (!iv1wpt_has_pro()) {
        wp_send_json_error(__('This feature requires IV1 WP Tools Pro.', 'iv1-wp-tools'));
    }

    $type    = sanitize_text_field($_POST['type'] ?? '');
    $enabled = !empty($_POST['enabled']);

    if (!in_array($type, ['css', 'js'], true)) {
        wp_send_json_error(__('Invalid type.', 'iv1-wp-tools'));
    }

    $opts = get_option(IV1WPT_CODEEDITOR_OPTION, iv1wpt_codeeditor_defaults());
    $opts[$type . '_enabled'] = $enabled;
    update_option(IV1WPT_CODEEDITOR_OPTION, $opts);

	wp_send_json_success([
		'message' => $enabled
			? sprintf(
				/* translators: %s: code type, e.g. CSS or JS */
				__('%s enabled.', 'iv1-wp-tools'),
				strtoupper($type)
			)
			: sprintf(
				/* translators: %s: code type, e.g. CSS or JS */
				__('%s disabled.', 'iv1-wp-tools'),
				strtoupper($type)
			),
	]);
}
