<?php
// IV1 WP Tools – Settings AJAX & Funktionen
defined("ABSPATH") || exit;

// ═══════════════════════════════════════════
// Tab: Schedule Settings
// ═══════════════════════════════════════════
add_action('wp_ajax_iv1wpt_save_schedule', 'iv1wpt_ajax_save_schedule');
function iv1wpt_ajax_save_schedule(): void {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');

    $schedules_available = iv1wpt_get_available_schedules();

    $schedule_opts = [
        'files_schedule'   => sanitize_text_field($_POST['files_schedule'] ?? 'off'),
        'db_schedule'      => sanitize_text_field($_POST['db_schedule'] ?? 'off'),
        'files_hour'       => min(23, max(0, absint($_POST['files_hour'] ?? 3))),
        'db_hour'          => min(23, max(0, absint($_POST['db_hour'] ?? 4))),
        'retention_files'  => max(1, absint($_POST['retention_files'] ?? 7)),
        'retention_db'     => max(1, absint($_POST['retention_db'] ?? 7)),
        'exclude_patterns' => sanitize_textarea_field($_POST['exclude_patterns'] ?? ''),
    ];

    if (!array_key_exists($schedule_opts['files_schedule'], $schedules_available)) {
        $schedule_opts['files_schedule'] = 'off';
    }

    if (!array_key_exists($schedule_opts['db_schedule'], $schedules_available)) {
        $schedule_opts['db_schedule'] = 'off';
    }

    $old_opts = get_option(IV1WPT_SCHEDULE_OPTION, iv1wpt_default_schedule());
    update_option(IV1WPT_SCHEDULE_OPTION, $schedule_opts);

    // Cron neu planen wenn Stunde oder Intervall geändert wurde
    $hour_changed = ($old_opts['files_hour'] ?? 3) !== $schedule_opts['files_hour']
                 || ($old_opts['db_hour']    ?? 4) !== $schedule_opts['db_hour'];

    if ($hour_changed) {
        // Bei Stunden-Änderung: bestehende Events löschen damit iv1wpt_sync_cron_events neu plant
        wp_clear_scheduled_hook('iv1wpt_cron_files');
        wp_clear_scheduled_hook('iv1wpt_cron_db');
    }

    iv1wpt_sync_cron_events();

    // Aktuell geplante Zeiten für Live-Update im Status-Widget zurückgeben
    $next_files_ts = wp_next_scheduled('iv1wpt_cron_files');
    $next_db_ts    = wp_next_scheduled('iv1wpt_cron_db');

    $schedules_available = iv1wpt_get_available_schedules();

    wp_send_json_success([
        'message'        => __('Schedule settings saved.', 'iv1-wp-tools'),
        'next_files_str' => $next_files_ts ? wp_date('d.m.Y H:i', $next_files_ts) : '—',
        'next_db_str'    => $next_db_ts    ? wp_date('d.m.Y H:i', $next_db_ts)    : '—',
        'files_schedule' => $schedule_opts['files_schedule'],
        'db_schedule'    => $schedule_opts['db_schedule'],
        'files_label'    => $schedules_available[ $schedule_opts['files_schedule'] ] ?? '',
        'db_label'       => $schedules_available[ $schedule_opts['db_schedule'] ]    ?? '',
    ]);
}

// ═══════════════════════════════════════════
// Tab: FTP Settings
// ═══════════════════════════════════════════
add_action('wp_ajax_iv1wpt_save_ftp', 'iv1wpt_ajax_save_ftp');
function iv1wpt_ajax_save_ftp(): void {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');

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

    $old_ftp = get_option(IV1WPT_FTP_OPTION, iv1wpt_default_ftp());

    $new_ftp = [
        'enabled'    => !empty($_POST['ftp_enabled']),
        'host'       => sanitize_text_field($_POST['ftp_host'] ?? ''),
        'port'       => absint($_POST['ftp_port'] ?? 21),
        'username'   => sanitize_text_field($_POST['ftp_username'] ?? ''),
        'password'   => !empty($_POST['ftp_password'])
            ? sanitize_text_field(wp_unslash($_POST['ftp_password']))
            : ($old_ftp['password'] ?? ''),
        'remote_dir' => trailingslashit(sanitize_text_field($_POST['ftp_remote_dir'] ?? '/backups/')),
        'use_ftps'   => !empty($_POST['use_ftps']),
        'passive'    => !empty($_POST['ftp_passive']),
    ];

    update_option(IV1WPT_FTP_OPTION, $new_ftp);

    wp_send_json_success([
        'message' => __('FTP/FTPS settings saved.', 'iv1-wp-tools')
    ]);
}


// ═══════════════════════════════════════════
// Tab: Email Settings
// ═══════════════════════════════════════════
add_action('wp_ajax_iv1wpt_save_email', 'iv1wpt_ajax_save_email');
function iv1wpt_ajax_save_email(): void {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');

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

    $email_settings = [
        'enabled'    => !empty($_POST['email_enabled']),
        'recipient'  => sanitize_email($_POST['email_recipient'] ?? ''),
        'on_success' => !empty($_POST['email_on_success']),
        'on_error'   => !empty($_POST['email_on_error']),
    ];

    update_option(IV1WPT_EMAIL_OPTION, $email_settings);

    wp_send_json_success([
        'message' => __('Email settings saved.', 'iv1-wp-tools')
    ]);
}