<?php
// این فایل فقط در صفحهٔ ویرایش پست (سریال) لود می‌شود

function mhp_add_series_link_meta_box() {
    // فقط برای پست‌هایی که imdbid_movie دارند (سریال‌ها)
    add_meta_box(
        'mhp_series_link_manager',
        'مدیریت لینک سریال (Media Hub Pro)',
        'mhp_render_series_link_meta_box',
        null, // همهٔ post typeها
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'mhp_add_series_link_meta_box');

function mhp_render_series_link_meta_box($post) {
    // بررسی اینکه آیا این پست یک سریال است (دارای imdbid_movie)
    $imdb_id = get_post_meta($post->ID, 'imdbid_movie', true);
    if (!$imdb_id) {
        echo '<p>این پست یک سریال نیست (فاقد IMDB ID).</p>';
        return;
    }

    // دریافت Base URL ذخیره‌شده (اگر وجود داشت)
    $saved_base_url = get_post_meta($post->ID, '_mhp_series_base_url', true);

    // توکن امنیتی
    wp_nonce_field('mhp_series_link_action', 'mhp_series_link_nonce');
    ?>
    <style>
        .mhp-codes-hidden { display: none; }
        .mhp-show-more { margin-top: 8px; font-size: 0.9em; color: #0073aa; cursor: pointer; }
    </style>

    <table class="form-table">
        <tr>
            <th>ID سریال (خوانا):</th>
            <td><code><?= esc_html($imdb_id) ?></code></td>
        </tr>
        <tr>
            <th>آدرس لینک (Base URL):</th>
            <td>
                <input type="text" name="mhp_series_base_url" value="<?= esc_attr($saved_base_url) ?>" style="width:100%" placeholder="https://example.com/series/NAME/">
                <p class="description">مثال: https://dls5.iran-gamecenter-host.com/DonyayeSerial/series/PrisonBreak/</p>
            </td>
        </tr>
        <tr>
            <th>انتخاب کد:</th>
            <td>
                <label><input type="radio" name="mhp_series_code" value="code-1" checked> کد ۱ (DLBox - اسکن خودکار)</label><br>
                <div class="mhp-codes-hidden" id="extra-codes">
                    <label><input type="radio" name="mhp_series_code" value="code-2"> کد ۲</label><br>
                    <label><input type="radio" name="mhp_series_code" value="code-3"> کد ۳</label><br>
                    <label><input type="radio" name="mhp_series_code" value="code-4"> کد ۴</label><br>
                    <label><input type="radio" name="mhp_series_code" value="code-5"> کد ۵</label>
                </div>
                <div class="mhp-show-more" onclick="document.getElementById('extra-codes').style.display='block'; this.style.display='none';">
                    نمایش گزینه‌های بیشتر
                </div>
            </td>
        </tr>
    </table>

    <button type="button" class="button button-primary" onclick="mhp_run_series_code(<?= (int)$post->ID ?>)">
        اجرای کد
    </button>
    <span id="mhp-loader" style="display:none; margin-left:10px;">در حال پردازش...</span>
    <div id="mhp-result" style="margin-top:10px;"></div>

    <script>
    function mhp_run_series_code(postId) {
        const baseUrl = document.querySelector('input[name="mhp_series_base_url"]').value;
        const code = document.querySelector('input[name="mhp_series_code"]:checked').value;
        const nonce = document.getElementById('mhp_series_link_nonce').value;

        if (!baseUrl) {
            alert('لطفاً آدرس لینک را وارد کنید.');
            return;
        }

        document.getElementById('mhp-loader').style.display = 'inline';
        document.getElementById('mhp-result').innerHTML = '';

        const formData = new FormData();
        formData.append('action', 'mhp_run_series_code_ajax');
        formData.append('post_id', postId);
        formData.append('base_url', baseUrl);
        formData.append('code', code);
        formData.append('nonce', nonce);

        fetch(ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            document.getElementById('mhp-loader').style.display = 'none';
            if (data.success) {
                document.getElementById('mhp-result').innerHTML = '<div class="notice notice-success"><p>✅ ' + data.message + '</p></div>';
                // ذخیرهٔ Base URL در متا
                const input = document.querySelector('input[name="mhp_series_base_url"]');
                input.value = baseUrl;
            } else {
                document.getElementById('mhp-result').innerHTML = '<div class="notice notice-error"><p>❌ ' + data.message + '</p></div>';
            }
        })
        .catch(err => {
            document.getElementById('mhp-loader').style.display = 'none';
            document.getElementById('mhp-result').innerHTML = '<div class="notice notice-error"><p>خطا در ارتباط.</p></div>';
        });
    }
    </script>
    <?php
}

// ذخیرهٔ Base URL هنگام ذخیرهٔ پست (اختیاری)
function mhp_save_series_base_url($post_id) {
    if (!isset($_POST['mhp_series_link_nonce']) || !wp_verify_nonce($_POST['mhp_series_link_nonce'], 'mhp_series_link_action')) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    if (isset($_POST['mhp_series_base_url'])) {
        update_post_meta($post_id, '_mhp_series_base_url', sanitize_text_field($_POST['mhp_series_base_url']));
    }
}
add_action('save_post', 'mhp_save_series_base_url');

// AJAX Handler
function mhp_handle_series_code_ajax() {
    check_ajax_referer('mhp_series_link_action', 'nonce');

    if (!current_user_can('edit_posts')) {
        wp_send_json_error('دسترسی غیرمجاز.');
    }

    $post_id = intval($_POST['post_id']);
    $base_url = sanitize_text_field($_POST['base_url']);
    $code = sanitize_text_field($_POST['code']);

    if (!$post_id || !$base_url || !$code) {
        wp_send_json_error('داده‌های ناقص.');
    }

    // دریافت IMDB ID از متادیتا
    $imdb_id = get_post_meta($post_id, 'imdbid_movie', true);
    if (!$imdb_id) {
        wp_send_json_error('این پست یک سریال نیست.');
    }

    // ذخیره Base URL
    update_post_meta($post_id, '_mhp_series_base_url', $base_url);

    // اجرای کد انتخاب‌شده
    $handler_file = MHP_DIR . "handlers/series/{$code}.php";

    if (!file_exists($handler_file)) {
        wp_send_json_error('کد انتخاب‌شده یافت نشد.');
    }

    // تنظیم $_POST برای سازگاری با هندلرهای قبلی
    $_POST['seriesId'] = $imdb_id;
    $_POST['seriesLink'] = $base_url;

    ob_start();
    include $handler_file;
    $output = ob_get_clean();

    // پاسخ موفقیت‌آمیز
    wp_send_json_success('کد اجرا شد.');
}
add_action('wp_ajax_mhp_run_series_code_ajax', 'mhp_handle_series_code_ajax');