<?php
/**
 * ============================================================
 * Plugin settings
 * ============================================================
 */
add_action('wp_ajax_mpvw_get_post_types', 'mpvw_get_post_types');

function mpvw_get_post_types(): void
{
    $disabled_post_types = [
        'attachment',
        'shop_order',
        'product',
        'shop_coupon',
        'wp_block',
        'wp_navigation',
        'acf-post-type',
        'acf-taxonomy',
        'acf-field-group'
    ];

    $post_types = get_post_types(['show_ui' => true], 'objects');
    $post_types = array_filter($post_types, function ($post_type) use ($disabled_post_types) {
        return !in_array($post_type->name, $disabled_post_types, true);
    });
    $post_types = array_map(function ($post_type) {
        return ['label' => $post_type->labels->name, 'name' => $post_type->name];
    }, $post_types);
    $post_types = array_values($post_types);
    wp_send_json_success($post_types);
}

add_action('wp_ajax_mpvw_get_plugin_settings', 'mpvw_get_plugin_settings');

function mpvw_get_plugin_settings(): void
{
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), MPVW_ADMIN_NONCE)) {
        wp_send_json_error(array('message' => _x('Nonce verification failed.', 'ajax', 'magic-product-video-for-woocommerce')), 403);
    }

    if (!current_user_can('manage_options'))
        wp_send_json_error(array('message' => _x('Permission denied.', 'ajax', 'magic-product-video-for-woocommerce')), 403);

    $plugin_settings_default = mpvw_get_default_plugin_settings();
    $plugin_settings_values = get_option(MPVW_PLUGIN_OPTIONS['plugin_settings'], $plugin_settings_default);
    if (!is_array($plugin_settings_values)) $plugin_settings_values = json_decode($plugin_settings_values, true);
    wp_send_json_success($plugin_settings_values);
}

add_action('wp_ajax_mpvw_save_plugin_settings', 'mpvw_save_plugin_settings');

function mpvw_save_plugin_settings(): void
{
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), MPVW_ADMIN_NONCE)) {
        wp_send_json_error(array('message' => _x('Nonce verification failed.', 'ajax', 'magic-product-video-for-woocommerce')), 403);
    }

    if (!current_user_can('manage_options'))
        wp_send_json_error(array('message' => _x('Permission denied.', 'ajax', 'magic-product-video-for-woocommerce')));

    $settings = isset($_POST['settings']) ? json_decode(sanitize_text_field(wp_unslash($_POST['settings'])), true) : false;
    $update = update_option(MPVW_PLUGIN_OPTIONS['plugin_settings'], $settings);
    wp_send_json_success($update);
}

/**
 * ============================================================
 * Settings
 * ============================================================
 */
add_action('wp_ajax_mpvw_get_settings', 'mpvw_get_settings');

function mpvw_get_settings(): void
{
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), MPVW_ADMIN_NONCE)) {
        wp_send_json_error(array('message' => _x('Nonce verification failed.', 'ajax', 'magic-product-video-for-woocommerce')), 403);
    }

    if (!current_user_can('manage_options'))
        wp_send_json_error(array('message' => _x('Permission denied.', 'ajax', 'magic-product-video-for-woocommerce')), 403);

    $settings_default = mpvw_get_default_settings();
    $settings_values = get_option(MPVW_PLUGIN_OPTIONS['settings'], $settings_default);
    if (!is_array($settings_values)) $settings_values = json_decode($settings_values, true);
    // Migration to new fields set
    $settings_values = array_merge($settings_default, $settings_values);
    wp_send_json_success($settings_values);
}

add_action('wp_ajax_mpvw_save_settings', 'mpvw_save_settings');

function mpvw_save_settings(): void
{
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), MPVW_ADMIN_NONCE)) {
        wp_send_json_error(array('message' => _x('Nonce verification failed.', 'ajax', 'magic-product-video-for-woocommerce')), 403);
    }

    if (!current_user_can('manage_options'))
        wp_send_json_error(array('message' => _x('Permission denied.', 'ajax', 'magic-product-video-for-woocommerce')));

    $settings = isset($_POST['settings']) ? json_decode(sanitize_text_field(wp_unslash($_POST['settings'])), true) : false;
    $update = update_option(MPVW_PLUGIN_OPTIONS['settings'], $settings);
    wp_send_json_success($update);
}

/**
 * ============================================================
 * Player configurations
 * ============================================================
 */
add_action('wp_ajax_mpvw_get_player_configs', 'mpvw_get_player_configs');

function mpvw_get_player_configs(): void
{
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), MPVW_ADMIN_NONCE)) {
        wp_send_json_error(array('message' => _x('Nonce verification failed.', 'ajax', 'magic-product-video-for-woocommerce')), 403);
    }

    if (!current_user_can('manage_options'))
        wp_send_json_error(array('message' => _x('Permission denied.', 'ajax', 'magic-product-video-for-woocommerce')), 403);

    $configs_values = get_option(MPVW_PLUGIN_OPTIONS['player_configs']);
    if (!is_array($configs_values)) $configs_values = json_decode($configs_values, true);
    wp_send_json_success($configs_values);
}

add_action('wp_ajax_mpvw_save_player_configs', 'mpvw_save_player_configs');

function mpvw_save_player_configs(): void
{
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), MPVW_ADMIN_NONCE)) {
        wp_send_json_error(array('message' => _x('Nonce verification failed.', 'ajax', 'magic-product-video-for-woocommerce')), 403);
    }

    if (!current_user_can('manage_options'))
        wp_send_json_error(array('message' => _x('Permission denied.', 'ajax', 'magic-product-video-for-woocommerce')));

    $configs = isset($_POST['configs']) ? json_decode(sanitize_text_field(wp_unslash($_POST['configs'])), true) : false;
    $update = update_option(MPVW_PLUGIN_OPTIONS['player_configs'], $configs);
    wp_send_json_success($update);
}

/**
 * ============================================================
 * FFmpeg settings
 * ============================================================
 */
function get_default_ffmpeg_settings(): array
{
    return [
        'videoCodecMp4'    => 'libx264',
        'videoCodecWebm'   => 'libvpx-vp9',
        'crf'              => 21,
        'preset'           => 'slow',
        'resolution'       => 'original',
        'resolutionWidth'  => -1,
        'resolutionHeight' => -1,
        'scalingMode'      => 'contain',
        'withoutAudio'     => true,
        'audioCodecMp4'    => 'aac',
        'audioCodecWebm'   => 'libopus'
    ];
}

add_action('wp_ajax_mpvw_check_ffmpeg_availability', 'mpvw_check_ffmpeg_availability');

function mpvw_check_ffmpeg_availability(): void
{
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), MPVW_ADMIN_NONCE)) {
        wp_send_json_error(array('message' => _x('Nonce verification failed.', 'ajax', 'magic-product-video-for-woocommerce')), 403);
    }

    if (!current_user_can('manage_options'))
        wp_send_json_error(array('message' => _x('Permission denied.', 'ajax', 'magic-product-video-for-woocommerce')), 403);

    $ffmpeg = exec('which ffmpeg');
    $ffmpeg = trim($ffmpeg);
    update_option(MPVW_PLUGIN_OPTIONS['ffmpeg_availability'], $ffmpeg !== '');
    $isFfmpegAvailable = get_option(MPVW_PLUGIN_OPTIONS['ffmpeg_availability']);

    $output = shell_exec('ffmpeg -version');
    preg_match('/ffmpeg version ([\S]+)/', $output, $matches);
    $version = $matches[1] ?? null;
    update_option(MPVW_PLUGIN_OPTIONS['ffmpeg_version'], $ffmpeg !== '');

    wp_send_json_success([
                             'available' => (bool)$isFfmpegAvailable,
                             'version'   => $version
                         ]);
}

add_action('wp_ajax_mpvw_get_ffmpeg_settings', 'mpvw_get_ffmpeg_settings');

function mpvw_get_ffmpeg_settings(): void
{
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), MPVW_ADMIN_NONCE)) {
        wp_send_json_error(array('message' => _x('Nonce verification failed.', 'ajax', 'magic-product-video-for-woocommerce')), 403);
    }

    if (!current_user_can('manage_options'))
        wp_send_json_error(array('message' => _x('Permission denied.', 'ajax', 'magic-product-video-for-woocommerce')), 403);

    $settings_values = get_option(MPVW_PLUGIN_OPTIONS['ffmpeg_settings']);
    $settings_values = $settings_values ? $settings_values : get_default_ffmpeg_settings();
    if (!is_array($settings_values)) $settings_values = json_decode($settings_values, true);
    wp_send_json_success($settings_values);
}

add_action('wp_ajax_mpvw_save_ffmpeg_settings', 'mpvw_save_ffmpeg_settings');

function mpvw_save_ffmpeg_settings(): void
{
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), MPVW_ADMIN_NONCE)) {
        wp_send_json_error(array('message' => _x('Nonce verification failed.', 'ajax', 'magic-product-video-for-woocommerce')), 403);
    }

    if (!current_user_can('manage_options'))
        wp_send_json_error(array('message' => _x('Permission denied.', 'ajax', 'magic-product-video-for-woocommerce')));

    $settings = isset($_POST['settings']) ? json_decode(sanitize_text_field(wp_unslash($_POST['settings'])), true) : get_default_ffmpeg_settings();
    $update = update_option(MPVW_PLUGIN_OPTIONS['ffmpeg_settings'], $settings);
    wp_send_json_success($update);
}
