<?php
namespace orderflow\Admin;
use orderflow\Traits\Core;
class Fb_Settings {
    use Core;
    public static function render_settings() {
        $current_tab = isset($_GET['tab']) ? $_GET['tab'] : 'general';
        $base_url = admin_url('admin.php?page=orderflow-fb-settings');
        echo "<div class='order-flow-main-box'>";
        require_once __DIR__ . "/promo.php";
        ?>
        <div class="orderflow-settings-container">
            <div class="orderflow-settings-nav">
                <nav class="nav-tab-wrapper">
                    <a href="<?= esc_url($base_url . '&tab=general'); ?>"
                       class="nav-tab <?= $current_tab === 'general' ? 'nav-tab-active' : ''; ?>">
                        General
                    </a>
                    <a href="<?= esc_url($base_url . '&tab=custom-events'); ?>"
                       class="nav-tab <?= $current_tab === 'custom-events' ? 'nav-tab-active' : ''; ?>">
                        Custom Events
                    </a>
                </nav>
            </div>
            <div class="orderflow-settings-wrapper">
                <div class="orderflow-settings-content">
                    <?php
                    $tabs = [
                        'general' => 'render_fb_general_settings',
                        'custom-events' => 'render_fb_custom_events_settings',
                    ];
                    $method = $tabs[$current_tab] ?? 'render_fb_general_settings';
                    if (method_exists(__CLASS__, $method)) {
                        self::$method();
                    }
                    ?>
                </div>
            </div>
        </div>
        <?php
        echo "</div>";
    }

    public static function submit_fb_general_settings() {
        if( ! self::is_license_active() ) {
            return ;
        }
        // Handle form submission for Facebook Pixel Settings
        if (isset($_POST['pys_save_settings']) && check_admin_referer('pys_save_settings')) {
            if (isset($_POST['pys']) && is_array($_POST['pys'])) {
                $facebook = \orderflow\Facebook\Facebook();
                // Pass null to let Facebook class handle the POST data itself
                $facebook->updateOptions(null);
            }
        }
    }

    public static function render_fb_general_settings() {
        // Handle form submission
        if (isset($_POST['pys_save_settings']) && check_admin_referer('pys_save_settings')) {
            if (isset($_POST['pys']) && is_array($_POST['pys'])) {
                $facebook = \orderflow\Facebook\Facebook();
                // Pass null to let Facebook class handle the POST data itself
                $facebook->updateOptions(null);
                echo '<div class="notice notice-success"><p>Settings saved successfully!</p></div>';
            }
        }

        $facebook = \orderflow\Facebook\Facebook();
        ?>
        <div class="orderflow-section">
            <div class="orderflow-option-heading">
                <h2 class="orderflow-section-title">Facebook General Settings</h2>
                <p class="orderflow-subtitle">Manage your Facebook Pixel settings.</p>
            </div>
            <form method="post" enctype="multipart/form-data" id="pys-form">
                <?php wp_nonce_field('pys_save_settings'); ?>
                <div class="orderflow-form-container">
                    <!-- Enable Pixel -->
                    <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Enable Pixel</div>
                        <div class="orderflow-field-input">
                            <label class="orderflow-toggle-switch">
                                <input type="hidden" name="pys[orderflow_facebook][of_enabled]" value="0">
                                <input type="checkbox" name="pys[orderflow_facebook][of_enabled]" value="1" <?php checked( $facebook->getOption( 'of_enabled' ), true ); ?>>
                                <span class="orderflow-slider"></span>
                            </label>
                        </div>
                    </div>

                    <!-- Enable Conversion API -->
                        <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Enable Conversion API</div>
                            <div class="orderflow-field-input">
                            <label class="orderflow-toggle-switch">
                                <input type="hidden" name="pys[orderflow_facebook][of_use_server_api]" value="0">
                                <input type="checkbox" name="pys[orderflow_facebook][of_use_server_api]" value="1" <?php checked( $facebook->getOption( 'of_use_server_api' ), true ); ?>>
                                <span class="orderflow-slider"></span>
                            </label>
                            </div>
                        </div>

                    <!-- Enable Advanced Matching -->
                        <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Enable Advanced Matching</div>
                            <div class="orderflow-field-input">
                            <label class="orderflow-toggle-switch">
                                <input type="hidden" name="pys[orderflow_facebook][of_advanced_matching_enabled]" value="0">
                                <input type="checkbox" name="pys[orderflow_facebook][of_advanced_matching_enabled]" value="1" <?php checked( $facebook->getOption( 'of_advanced_matching_enabled' ), true ); ?>>
                                <span class="orderflow-slider"></span>
                            </label>
                            </div>
                        </div>

                    <!-- Meta Pixel ID -->
                        <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Meta Pixel ID</div>
                            <div class="orderflow-field-input">
                            <?php $facebook->render_pixel_id( 'of_pixel_id', 'Meta Pixel ID' ); ?>
                            </div>
                        </div>

                    <!-- Conversion API Token -->
                        <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Conversion API Token</div>
                            <div class="orderflow-field-input">
                            <?php $facebook->render_text_area_array_item( "of_server_access_api_token", "Api token" ); ?>
                            </div>
                        </div>

                    <!-- Test Event Code -->
                        <div class="orderflow-field-row">
                        <div class="orderflow-field-label">Test Event Code</div>
                            <div class="orderflow-field-input">
                            <?php $facebook->render_text_input_array_item( "of_test_api_event_code", "Code" ); ?>
                            <?php $facebook->render_text_input_array_item( "of_test_api_event_code_expiration_at", "", 0, true ); ?>
                            </div>
                        </div>

                    <!-- Domain Verification -->
                    <?php self::addMetaTagFields( $facebook, "https://www.pixelyoursite.com/verify-domain-facebook" ); ?>
                    
                    <!-- Additional Facebook Settings (from html-settings.php) -->
                    <?php
                    if (file_exists(ADS_PLUGIN_PATH . '/includes/facebook/modules/facebook/views/html-settings.php')) {
                        include ADS_PLUGIN_PATH . '/includes/facebook/modules/facebook/views/html-settings.php';
                    }
                    ?>
                            </div>
                <button type="submit" class="orderflow-submit-button" name="pys_save_settings">
                    Save Settings
                </button>
            </form>
        </div>
        <?php
    }

    /**
     * Add Meta Tag Fields (from functions-admin.php)
     */
    private static function addMetaTagFields($pixel, $url) { 
        $metaTags = (array) $pixel->getOption( 'verify_meta_tag' );
        ?>
        <div class="orderflow-field-row">
            <div class="orderflow-field-label">Domain Verification
                <p class="ads-settings-description">Enter the verification meta-tag provided by Facebook for domain verification</p>
            </div>
            <div class="orderflow-field-input">
                <?php $pixel->render_text_input_array_item( 'verify_meta_tag', 'Add the verification meta-tag there' ); ?>
            </div>
        </div>

        <?php
        foreach ( $metaTags as $index => $val ) :
            if ( $index == 0 ) continue; ?>
            <div class="orderflow-field-row">
                <div class="orderflow-field-label"></div>
                <div class="orderflow-field-input">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <div style="flex: 1;">
                            <?php $pixel->render_text_input_array_item( 'verify_meta_tag', 'Add the verification meta-tag there', $index ); ?>
                        </div>
                        <button type="button" class="button remove-meta-row" data-index="<?php echo esc_attr($index); ?>">Remove</button>
                    </div>
                </div>
            </div>
        <?php
        endforeach;
        ?>

        <div class="orderflow-field-row">
            <div class="orderflow-field-label"></div>
            <div class="orderflow-field-input">
                <button type="button" class="button" id="pys_add_<?= $pixel->getSlug() ?>_meta_tag">
                    Add another verification meta-tag
                </button>
            </div>
        </div>

        <script>
            jQuery( document ).ready( function ( $ ) {
                $( '#pys_add_<?=$pixel->getSlug()?>_meta_tag' ).click( function ( e ) {
                    e.preventDefault();
                    let newField = '<div class="orderflow-field-row"><div class="orderflow-field-label"></div><div class="orderflow-field-input"><div style="display: flex; align-items: center; gap: 10px;"><div style="flex: 1;"><input type="text" placeholder="Add the verification meta-tag there" name="pys[<?=$pixel->getSlug()?>][verify_meta_tag][]" value="" class="input-standard"></div><button type="button" class="button remove-meta-row">Remove</button></div></div></div>';
                    $( '#pys_add_<?=$pixel->getSlug()?>_meta_tag' ).closest('.orderflow-field-row').before( newField );
                } );
                $( document ).on( 'click', '.remove-meta-row', function() {
                    $( this ).closest( '.orderflow-field-row' ).remove();
                } );
            } );
        </script>
        <?php
    }

    public static function submit_fb_custom_events_settings() {
        if( ! self::is_license_active() ) {
            return ;
        }
        if (!isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'ads_fb_custom_events_settings_form_nonce')) {
            return;
        }
        $link_selectors = isset($_POST['link_selectors']) ? $_POST['link_selectors'] : [];
        $link_event_names = isset($_POST['link_event_names']) ? $_POST['link_event_names'] : [];
        $link_data = [];
        foreach ($link_selectors as $index => $selector) {
            $event_name = isset($link_event_names[$index]) ? sanitize_text_field($link_event_names[$index]) : '';
            if (!empty($selector) && !empty($event_name)) {
                $link_data[] = [
                    'selector'   => sanitize_text_field($selector),
                    'event_name' => $event_name,
                ];
            }
        }
        $scroll_selectors = isset($_POST['scroll_selectors']) ? $_POST['scroll_selectors'] : [];
        $scroll_event_names = isset($_POST['scroll_event_names']) ? $_POST['scroll_event_names'] : [];
        $scroll_data = [];
        foreach ($scroll_selectors as $index => $selector) {
            $event_name = isset($scroll_event_names[$index]) ? sanitize_text_field($scroll_event_names[$index]) : '';
            if (!empty($selector) && !empty($event_name)) {
                $scroll_data[] = [
                    'selector' => sanitize_text_field($selector),
                    'event_name'    => $event_name,
                ];
            }
        }
        $click_selectors = isset($_POST['click_selectors']) ? $_POST['click_selectors'] : [];
        $click_event_names = isset($_POST['click_event_names']) ? $_POST['click_event_names'] : [];
        $click_data = [];
        foreach ($click_selectors as $index => $selector) {
            $event_name = isset($click_event_names[$index]) ? sanitize_text_field($click_event_names[$index]) : '';
            if (!empty($selector) && !empty($event_name)) {
                $click_data[] = [
                    'selector' => sanitize_text_field($selector),
                    'event_name'    => $event_name,
                ];
            }
        }
        $time_selectors = isset($_POST['time_selectors']) ? $_POST['time_selectors'] : [];
        $time_seconds = isset($_POST['time_seconds']) ? $_POST['time_seconds'] : [];
        $time_event_names = isset($_POST['time_event_names']) ? $_POST['time_event_names'] : [];
        $time_data = [];
        foreach ($time_selectors as $index => $selector) {
            $seconds = isset($time_seconds[$index]) ? sanitize_text_field($time_seconds[$index]) : '';
            $event_name = isset($time_event_names[$index]) ? sanitize_text_field($time_event_names[$index]) : '';
            if (!empty($selector) && !empty($seconds) && !empty($event_name)) {
                $time_data[] = [
                    'selector' => sanitize_text_field($selector),
                    'seconds' => $seconds,
                    'event_name' => $event_name,
                ];
            }
        }
        update_option('ads_fb_link_events', $link_data);
        update_option('ads_fb_scroll_events', $scroll_data);
        update_option('ads_fb_click_events', $click_data);
        update_option('ads_fb_time_events', $time_data);
    }
    public static function render_fb_custom_events_settings() {
        if (isset($_POST['ads_save_fb_custom_events_settings'])) {
            check_admin_referer('ads_fb_custom_events_settings_form_nonce')
                ? self::submit_fb_custom_events_settings()
                : self::render_error('Security check failed');
        }
        $link_events = get_option('ads_fb_link_events', []);
        $scroll_events = get_option('ads_fb_scroll_events', []);
        $click_events = get_option('ads_fb_click_events', []);
        $time_events = get_option('ads_fb_time_events', []);
        ?>
        <div class="orderflow-section">
            <div class="orderflow-option-heading">
                <h2 class="orderflow-section-title">Facebook Custom Events</h2>
                <p class="orderflow-subtitle">Set up tracking for custom events on your website.</p>
            </div>
            <form method="post">
                <?php wp_nonce_field('ads_fb_custom_events_settings_form_nonce'); ?>
                <div class="orderflow-form-container">
                    <!-- Link Events -->
                    <div class="orderflow-event-section">
                        <h3>Link Events (Class/ID)</h3>
                        <div class="event-container">
                            <?php foreach ($link_events as $event): ?>
                                <div class="event-row">
                                    <input type="text" name="link_selectors[]" value="<?= esc_attr($event['selector']) ?>" placeholder=".class / #id">
                                    <input type="text" name="link_event_names[]" value="<?= esc_attr($event['event_name']) ?>" placeholder="Event Name">
                                    <button type="button" class="delete-event-row">Delete</button>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <button type="button" class="button add-event-button orderflow-add-event-button" data-type="link">+ Add Link Event</button>
                    </div>
                    <!-- Scroll Events -->
                    <div class="orderflow-event-section">
                        <h3>Scroll Events</h3>
                        <div class="event-container">
                            <?php foreach ($scroll_events as $event): ?>
                                <div class="event-row">
                                    <input type="text" name="scroll_selectors[]" value="<?= esc_attr($event['selector']) ?>" placeholder=".class or #id">
                                    <input type="text" name="scroll_event_names[]" value="<?= esc_attr($event['event_name']) ?>" placeholder="Event Name">
                                    <button type="button" class="delete-event-row">Delete</button>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <button type="button" class="button add-event-button orderflow-add-event-button" data-type="scroll">+ Add Scroll Event</button>
                    </div>
                    <!-- Click Events -->
                    <div class="orderflow-event-section">
                        <h3>Click Events</h3>
                        <div class="event-container">
                            <?php foreach ($click_events as $event): ?>
                                <div class="event-row">
                                    <input type="text" name="click_selectors[]" value="<?= esc_attr($event['selector']) ?>" placeholder=".class or #id">
                                    <input type="text" name="click_event_names[]" value="<?= esc_attr($event['event_name']) ?>" placeholder="Event Name">
                                    <button type="button" class="delete-event-row">Delete</button>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <button type="button" class="button add-event-button orderflow-add-event-button" data-type="click">+ Add Click Event</button>
                    </div>
                    <!-- Time Events -->
                    <div class="orderflow-event-section">
                        <h3>Time Events</h3>
                        <div class="event-container">
                            <?php foreach ($time_events as $event): ?>
                                <div class="event-row">
                                    <input type="text" name="time_selectors[]" value="<?= esc_attr($event['selector']) ?>" placeholder=".class or #id">
                                    <input type="text" name="time_seconds[]" value="<?= esc_attr($event['seconds']) ?>" placeholder="Time in seconds">
                                    <input type="text" name="time_event_names[]" value="<?= esc_attr($event['event_name']) ?>" placeholder="Event Name">
                                    <button type="button" class="delete-event-row">Delete</button>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <button type="button" class="button add-event-button orderflow-add-event-button" data-type="time">+ Add Time Event</button>
                    </div>
                </div>
                <button type="submit" class="orderflow-submit-button" name="ads_save_fb_custom_events_settings">
                    Save Settings
                </button>
            </form>
        </div>
        <script>
            jQuery(document).ready(function($) {
                // Add event row (delegated to document for robustness)
                $(document).on('click', '.orderflow-add-event-button', function(e) {
                    e.preventDefault();

                    const type = String($(this).data('type') || 'default').trim();
                    const section = $(this).closest('.orderflow-event-section');
                    const container = section.find('.event-container');

                    if (!container.length) {
                        console.warn('No .event-container found inside .orderflow-event-section for button:', this);
                        return;
                    }

                    const row = $('<div/>', { class: 'event-row' });
                    const input1 = $('<input/>', { type: 'text', class: 'orderflow-input', 'aria-label': `${type} selector` });
                    const input2 = $('<input/>', { type: 'text', class: 'orderflow-input', 'aria-label': `${type} event info` });
                    let input3 = null;

                    if (type === 'link') {
                        input1.attr('name', 'link_selectors[]').attr('placeholder', '.class / #id');
                        input2.attr('name', 'link_event_names[]').attr('placeholder', 'Event Name');
                    } else if (type === 'time') {
                        input1.attr('name', 'time_selectors[]').attr('placeholder', '.class or #id');
                        input2.attr('name', 'time_seconds[]').attr('placeholder', 'Time in seconds');
                        input3 = $('<input/>', {
                            type: 'text',
                            class: 'orderflow-input',
                            name: 'time_event_names[]',
                            placeholder: 'Event Name',
                            'aria-label': 'time event name'
                        });
                    } else {
                        // generic fallback for other types (e.g., 'scroll', 'hover', etc.)
                        input1.attr('name', `${type}_selectors[]`).attr('placeholder', '.class or #id');
                        input2.attr('name', `${type}_event_names[]`).attr('placeholder', 'Event Name');
                    }

                    const delBtn = $('<button/>', {
                        type: 'button',
                        class: 'delete-event-row',
                        'aria-label': 'Delete event row'
                    }).text('Delete');

                    // Append inputs in order
                    row.append(input1, input2);
                    if (input3) row.append(input3);
                    row.append(delBtn);

                    container.append(row);

                    // Focus the first input of the newly added row
                    row.find('input:first').focus();
                });

                // Delete event row (delegated)
                $(document).on('click', '.delete-event-row', function(e) {
                    e.preventDefault();
                    $(this).closest('.event-row').remove();
                });
            });
        </script>

        <?php
    }
    private static function render_error($message) {
        echo '<div class="orderflow-error"><p>' . esc_html($message) . '.</p></div>';
    }
}