<?php
namespace OxygenApp\Hooks;

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

use OxygenApp\Models\BackgroundSound;
use OxygenApp\Models\Background;
use OxygenApp\Utils\Sanitizer;
use OxygenApp\Models\AdminPlaylist;
use OxygenApp\Models\BackgroundCategory;

class ActionSavePost implements IHook {
    static function register() {
        add_action('save_post', [self::class, 'onBackgroundSoundPostSave'], 20);
        add_action('save_post', [self::class, 'onBackgroundPostSave'], 20);
    }


    static function onBackgroundSoundPostSave(?int $post_id) {
        // Check if it's an autosave or a bulk edit
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        //check post revision
        if(wp_is_post_revision($post_id)) {
            return 'revision';
        }

        if (get_post_type($post_id) !== BackgroundSound::POST_TYPE) {
            return;
        }

        // Check current user's permissions
        if (!current_user_can('edit_post', $post_id)) {
            set_transient(BackgroundSound::POST_SAVE_TRANSIENT_KEY, esc_html__('You do not have permission to edit this post', 'oxyleaf-app-working-and-relaxing-app'), 30);
            return;
        }

        if (!current_user_can('edit_page', $post_id)) {
            set_transient(BackgroundSound::POST_SAVE_TRANSIENT_KEY, esc_html__('You do not have permission to edit this page', 'oxyleaf-app-working-and-relaxing-app'), 30);
            return;
        }

        // Verify nonce
        if (!isset($_POST['custom_meta_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['custom_meta_nonce'])), 'save_custom_meta_nonce')) {
            return;
        }

        $labelsData = isset($_POST['labels_' . BackgroundSound::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['labels_' . BackgroundSound::POST_META_KEY])) : [];
        $sanitizedLabels = [];

        foreach ($labelsData as $langKey => $labels) {
            $lngKey = sanitize_text_field(wp_unslash($langKey));
            $sanitizedLabels[$lngKey] = [];
            foreach ($labels as $labelKey => $label) {
                $sanitizedLabels[$lngKey][$labelKey] = sanitize_text_field(wp_unslash($label));
            }
        }

        update_post_meta($post_id, 'labels_' . BackgroundSound::POST_META_KEY, $sanitizedLabels);


        $soundId = isset($_POST['sound_file_id_' . BackgroundSound::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['sound_file_id_' . BackgroundSound::POST_META_KEY])) : '';
        update_post_meta($post_id, 'sound_file_id_' . BackgroundSound::POST_META_KEY, $soundId);

        $soundIconId = isset($_POST['icon_file_id_' . BackgroundSound::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['icon_file_id_' . BackgroundSound::POST_META_KEY])) : '';
        update_post_meta($post_id, 'icon_file_id_' . BackgroundSound::POST_META_KEY, $soundIconId);

        $isPremiumSound = isset($_POST['is_premium_' . BackgroundSound::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['is_premium_' . BackgroundSound::POST_META_KEY])) : null;
        if ($isPremiumSound && $isPremiumSound === 'on') {
            update_post_meta($post_id, 'is_premium_' . BackgroundSound::POST_META_KEY, $isPremiumSound);
        } else {
            delete_post_meta($post_id, 'is_premium_' . BackgroundSound::POST_META_KEY);
        }

        $requiresLogIn = isset($_POST['requires_login_' . BackgroundSound::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['requires_login_' . BackgroundSound::POST_META_KEY])) : null;
        if ($requiresLogIn && $requiresLogIn === 'on') {
            update_post_meta($post_id, 'requires_login_' . BackgroundSound::POST_META_KEY, $requiresLogIn);
        } else {
            delete_post_meta($post_id, 'requires_login_' . BackgroundSound::POST_META_KEY);
        }

        $soundVolume = isset($_POST['sound_volume_' . BackgroundSound::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['sound_volume_' . BackgroundSound::POST_META_KEY])) : 50;
        if (is_numeric($soundVolume)) {
            $soundVolume = absint($soundVolume);
            if ($soundVolume > 100) {
                $soundVolume = 100;
            }
            update_post_meta($post_id, 'sound_volume_' . BackgroundSound::POST_META_KEY, $soundVolume);
        } else {
            delete_post_meta($post_id, 'sound_volume_' . BackgroundSound::POST_META_KEY);
        }

        $playlistTermIds = isset($_POST['playlists_' . BackgroundSound::POST_META_KEY]) ? map_deep(wp_unslash($_POST['playlists_' . BackgroundSound::POST_META_KEY]), 'sanitize_text_field') : [];

        if (is_array($playlistTermIds) && sizeof($playlistTermIds) > 0) {
            $playlistTermIds = Sanitizer::sanitize_data($playlistTermIds);
            $playlistTermIds = array_map('intval', $playlistTermIds);
            wp_set_post_terms($post_id, $playlistTermIds, AdminPlaylist::TAX);
        } else {
            wp_set_post_terms($post_id, [], AdminPlaylist::TAX);
        }
    }

    static function onBackgroundPostSave(?int $post_id) {

        // Check if it's an autosave or a bulk edit
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        //check post revision
        if(wp_is_post_revision($post_id)) {
            return 'revision';
        }

        if (get_post_type($post_id) !== Background::POST_TYPE) {
            return;
        }

        // Check current user's permissions
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        if (!current_user_can('edit_page', $post_id)) {
            return;
        }

        // Verify nonce
        if (!isset($_POST['custom_meta_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['custom_meta_nonce'])), 'save_custom_meta_nonce')) {
            return;
        }

        $type = isset($_POST['type_' . Background::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['type_' . Background::POST_META_KEY])) : '';
        update_post_meta($post_id, 'type_' . Background::POST_META_KEY, $type);


        $videoId = isset($_POST['video_file_id_' . Background::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['video_file_id_' . Background::POST_META_KEY])) : '';
        update_post_meta($post_id, 'video_file_id_' . Background::POST_META_KEY, $videoId);

        $videoIconId = isset($_POST['video_icon_file_id_' . Background::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['video_icon_file_id_' . Background::POST_META_KEY])) : '';
        update_post_meta($post_id, 'video_icon_file_id_' . Background::POST_META_KEY, $videoIconId);

        $bkImageId = isset($_POST['bk_image_file_id_' . Background::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['bk_image_file_id_' . Background::POST_META_KEY])) : '';
        update_post_meta($post_id, 'bk_image_file_id_' . Background::POST_META_KEY, $bkImageId);

        $isPremiumBackground = isset($_POST['is_premium_' . Background::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['is_premium_' . Background::POST_META_KEY])) : null;
        if ($isPremiumBackground && $isPremiumBackground === 'on') {
            update_post_meta($post_id, 'is_premium_' . Background::POST_META_KEY, $isPremiumBackground);
        } else {
            delete_post_meta($post_id, 'is_premium_' . Background::POST_META_KEY);
        }

        $requiresLogIn = isset($_POST['requires_login_' . Background::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['requires_login_' . Background::POST_META_KEY])) : null;
        if ($requiresLogIn && $requiresLogIn === 'on') {
            update_post_meta($post_id, 'requires_login_' . Background::POST_META_KEY, $requiresLogIn);
        } else {
            delete_post_meta($post_id, 'requires_login_' . Background::POST_META_KEY);
        }

        $background_credits_label = isset($_POST['background_credits_label_' . Background::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['background_credits_label_' . Background::POST_META_KEY])) : null;
        update_post_meta($post_id, 'background_credits_label_' . Background::POST_META_KEY, $background_credits_label);

        $background_credits_url = isset($_POST['background_credits_url_' . Background::POST_META_KEY]) ? sanitize_text_field(wp_unslash($_POST['background_credits_url_' . Background::POST_META_KEY])) : null;
        update_post_meta($post_id, 'background_credits_url_' . Background::POST_META_KEY, $background_credits_url);

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Data is sanitized on line 170 with Sanitizer::sanitize_data()
        $categoryTermIds = isset($_POST['categories_' . Background::POST_META_KEY]) ? wp_unslash($_POST['categories_' . Background::POST_META_KEY]) : '';
        if (is_array($categoryTermIds) && sizeof($categoryTermIds) > 0) {
            $categoryTermIds = Sanitizer::sanitize_data($categoryTermIds);
            $categoryTermIds = array_map('intval', $categoryTermIds);
            wp_set_post_terms($post_id, $categoryTermIds, BackgroundCategory::TAX);
        } else {
            wp_set_post_terms($post_id, [], BackgroundCategory::TAX);
        }
    }
}