<?php
namespace OxygenApp\Views\Admin\Sounds;
if ( ! defined( 'ABSPATH' ) ) exit;


use OxygenApp\Views\BaseView;
use OxygenApp\Views\IView;
use OxygenApp\Models\BackgroundSound;
use OxygenApp\Utils\LanguagesHelper;
use OxygenApp\Config\Flags;
use OxygenApp\Models\AdminPlaylist;


class SoundsCptMetabox extends BaseView implements IView {

    public function render(): void {
        global $post;
        if ($post->post_type !== BackgroundSound::POST_TYPE) {
            return;
        }

        $langCodes = LanguagesHelper::getInstance()->getExistingLangCodes();
        $baseFlagsUrl = Flags::getBaseURL();
        $mainMetaKey = BackgroundSound::POST_META_KEY;

        $labelsValue = get_post_meta($post->ID, 'labels_' . BackgroundSound::POST_META_KEY, true);
        $soundFileId = get_post_meta($post->ID, 'sound_file_id_' . BackgroundSound::POST_META_KEY, true);
        $sound_filename = '';
        $attachment_url = '';
        if ($soundFileId && is_numeric($soundFileId)) {
            $attachment_url = wp_get_attachment_url($soundFileId);
            $sound_filename = basename($attachment_url);
        }

        $soundVolume = get_post_meta($post->ID, 'sound_volume_' . BackgroundSound::POST_META_KEY, true);
        $soundVolume = $soundVolume && is_numeric($soundVolume) ? $soundVolume : 50;
        
        ?>
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="mb-4 mt-2">
                        <div><strong><?php esc_html_e('Upload sound (mp3) ', 'oxyleaf-app-working-and-relaxing-app') ?></strong></div>
                        <div class="sound_file_name_ui <?php echo esc_attr(!$soundFileId ? 'd-none' : '') ?>"><strong><?php esc_html_e('Filename: ', 'oxyleaf-app-working-and-relaxing-app') ?></strong> <a href="<?php echo esc_url($attachment_url) ?>" target="_blank" class="sound_file_name"><?php echo esc_html($sound_filename) ?></a></div>
                        <input id="sound_id" type="hidden" name="<?php echo esc_attr("sound_file_id_{$mainMetaKey}") ?>" value="<?php echo esc_attr($soundFileId) ?>">
                        <div class="my-3">
                            <button id="upload_sound_btn" type="button" class="btn btn-outline-primary" style="margin-right: 10px;"><?php esc_html_e('Upload sound', 'oxyleaf-app-working-and-relaxing-app') ?></button>
                            <button id="remove_sound_btn" type="button" class="btn btn-outline-danger <?php echo esc_attr(!$soundFileId ? 'd-none' : '') ?>"><?php esc_html_e('Remove sound', 'oxyleaf-app-working-and-relaxing-app') ?></button>
                        </div>
                    </div>
                    <div><hr></div>
                    <div class="mb-4">
                        <?php
                        $adminPlaylists = AdminPlaylist::getAll();
                        $existingPosttermIds = wp_get_post_terms($post->ID, AdminPlaylist::TAX, [
                            'fields' => 'ids'
                        ]);
                        ?>
                        <div class="row">
                            <div class="col-md-6">
                                
                                <label class="form-label w-100"><strong><?php esc_html_e('Select playlists', 'oxyleaf-app-working-and-relaxing-app') ?></strong></label>
                                <select class="form-select playlist-select" name="<?php echo esc_attr("playlists_{$mainMetaKey}[]") ?>">
                                    <?php if (is_array($adminPlaylists)): ?>
                                        <option value=""><?php esc_html_e('-- Select a playlist --', 'oxyleaf-app-working-and-relaxing-app') ?></option>
                                        <?php foreach ($adminPlaylists as $key => $playlistTerm): ?>
                                            <?php
                                            $isSelected = in_array($playlistTerm->term_id, $existingPosttermIds);
                                            ?>
                                            <option value="<?php echo esc_attr($playlistTerm->term_id) ?>" <?php echo $isSelected ? esc_attr('selected') : '' ?>><?php echo esc_html($playlistTerm->name) ?></option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>  
                            </div>
                            <div class="col-md-6">
                                <?php if (is_array($adminPlaylists) && sizeof($adminPlaylists) === 0): ?>
                                    <div class="alert alert-warning" role="alert">
                                        <?php esc_html_e('There are no admin playlists added. To add a playlist, use the left main menu > Background sounds > Playlists.', 'oxyleaf-app-working-and-relaxing-app') ?>
                                    </div>
                                <?php else: ?>
                                    <div class="alert alert-info" role="alert">
                                        <?php esc_html_e('Selecting a playlist is just a way to order the sounds shown in the frontend, remember you can re-order playlists using this plugin:', 'oxyleaf-app-working-and-relaxing-app') ?> <a target="_blank" href="https://wordpress.org/plugins/custom-taxonomy-order-ne/"><?php esc_html_e("Custom Taxonomy Order", 'oxyleaf-app-working-and-relaxing-app') ?></a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div><hr></div>
                    <div class="mb-4">
                        <label class="sound-volume mb-2" for="sound-volume"> <strong><?php esc_html_e('Default sound volume', 'oxyleaf-app-working-and-relaxing-app'); ?></strong></label><br>
                        <input type="number" min="0" max="100" step="1" id="sound-volume" value="<?php echo esc_attr($soundVolume) ?>" name="<?php echo esc_attr("sound_volume_{$mainMetaKey}") ?>">
                    </div>
                    <div><hr></div>
                    <?php
                        $soundIconId = get_post_meta($post->ID, 'icon_file_id_' . BackgroundSound::POST_META_KEY, true);
                        $sound_icon_filename = '';
                        $attachment_icon_url = '';
                        $iconUrl = '';
                        if ($soundIconId && is_numeric($soundIconId)) {
                            $icon_file_url = wp_get_attachment_url($soundIconId);
                            $sound_icon_filename = basename($icon_file_url);
                            $attachment_icon_url = wp_get_attachment_url($soundIconId);
                            $iconUrl = wp_get_attachment_image_url($soundIconId);
                        }
                    ?>
                    <div class="mb-4 mt-2">
                        <div><strong><?php esc_html_e('Upload sound icon', 'oxyleaf-app-working-and-relaxing-app') ?></strong></div>
                        <div class="sound_icon_filename_ui my-2 <?php echo esc_attr(!$soundIconId ? 'd-none' : '') ?>"><strong><?php esc_html_e('Filename: ', 'oxyleaf-app-working-and-relaxing-app') ?></strong> <a href="<?php echo esc_url($attachment_icon_url) ?>" target="_blank" class="sound_icon_filename"><?php echo esc_html($sound_icon_filename) ?></a></div>
                        <div class="icon_preview_ui hidden">
                            <img class="icon_preview" style="max-width: 100px;" src="<?php echo esc_url($iconUrl) ?>" alt="">
                        </div>
                        <input id="icon_id" type="hidden" name="<?php echo esc_attr("icon_file_id_{$mainMetaKey}") ?>" value="<?php echo esc_attr($soundIconId) ?>">
                        <div class="my-3">
                            <button id="upload_sound_icon_btn" type="button" class="btn btn-outline-primary" style="margin-right: 10px;"><?php esc_html_e('Upload sound icon', 'oxyleaf-app-working-and-relaxing-app') ?></button>
                            <button id="remove_sound_icon_btn" type="button" class="btn btn-outline-danger <?php echo esc_attr(!$soundIconId ? 'd-none' : '') ?>"><?php esc_html_e('Remove sound icon', 'oxyleaf-app-working-and-relaxing-app') ?></button>
                        </div>
                    </div>
                    <div><hr></div>
                    <?php foreach ($langCodes as $key => $langCode): ?>
                        <?php 
                            $langData = Flags::findLangByCode($langCode);
                            $flagIcon = $langData['flag_4x3'] ?? '';
                            $labelValue = $labelsValue[$langCode]['sound_name'] ?? '';
                            self::renderTextInput(langCode: $langCode, baseFlagsUrl: $baseFlagsUrl, 
                            flagIcon: $flagIcon, mainMetaKey: $mainMetaKey, metaKey: 'sound_name', value: $labelValue, label: esc_html__('Sound name', 'oxyleaf-app-working-and-relaxing-app'));
                        ?>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php wp_nonce_field('save_custom_meta_nonce', 'custom_meta_nonce'); ?>
        </div>
        <?php
    }

    private static function renderTextInput(string $langCode, string $baseFlagsUrl, string $flagIcon, 
    string $mainMetaKey, string $metaKey, string $value = '', string $label = '', string $info = '') {
        $feId = uniqid();
        ?>
            <div class="mb-3">
                <label for="<?php esc_attr($feId) ?>" class="form-label w-100">
                    <span class="skl-flag" style="width: 30px"><img style="max-height: 15px;" src="<?php echo esc_url($baseFlagsUrl . $flagIcon) ?>" alt=""></span>
                    <strong>
                        <span>(<?php echo esc_html(strtoupper($langCode)) ?>) </span>
                        <?php echo esc_html($label) ?>
                    </strong>
                </label>
                <input type="text" 
                    value="<?php echo esc_attr($value) ?>" 
                    name="<?php echo esc_attr("labels_{$mainMetaKey}[{$langCode}][{$metaKey}]") ?>" 
                    class="form-control" id="<?php echo esc_attr($feId) ?>">
                <?php if ($info): ?>
                    <div class="fst-italic">
                        <?php echo esc_html($info) ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php
    }
}