<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Find first page containing one of the provided shortcodes.
 *
 * @param string[] $shortcodes Shortcode tags.
 * @return int
 */
function stakmv_find_page_with_shortcode(array $shortcodes) {
    $page_ids = get_posts(array(
        'post_type'      => 'page',
        'post_status'    => array('publish', 'draft', 'pending', 'private'),
        'posts_per_page' => -1,
        'fields'         => 'ids',
    ));

    foreach ((array) $page_ids as $page_id) {
        $content = (string) get_post_field('post_content', (int) $page_id);
        if ($content === '') {
            continue;
        }

        foreach ($shortcodes as $shortcode) {
            if (has_shortcode($content, $shortcode)) {
                return (int) $page_id;
            }
        }
    }

    return 0;
}

/**
 * Ensure page exists for a shortcode and save option mapping.
 *
 * @param string   $title      Page title.
 * @param string   $shortcode  Canonical shortcode tag.
 * @param string   $option_key Option storing page ID.
 * @return array{page_id:int,created:bool}
 */
function stakmv_ensure_shortcode_page($title, $shortcode, $option_key) {
    $option_suffix = sanitize_key((string) preg_replace('/^stakmv_/', '', (string) $option_key));

    $page_id = (int) stakmv_get_option($option_suffix, 0);
    if ($page_id > 0 && get_post_type($page_id) === 'page' && get_post_status($page_id) !== 'trash') {
        stakmv_update_option($option_suffix, $page_id);
        return array('page_id' => $page_id, 'created' => false);
    }

    $found_id = stakmv_find_page_with_shortcode(array($shortcode));
    if ($found_id > 0) {
        stakmv_update_option($option_suffix, $found_id);
        return array('page_id' => $found_id, 'created' => false);
    }

    $new_id = wp_insert_post(array(
        'post_type'    => 'page',
        'post_status'  => 'publish',
        'post_title'   => $title,
        'post_content' => '[' . $shortcode . ']',
    ));

    if (is_wp_error($new_id) || $new_id <= 0) {
        return array('page_id' => 0, 'created' => false);
    }

    stakmv_update_option($option_suffix, (int) $new_id);
    return array('page_id' => (int) $new_id, 'created' => true);
}

/**
 * Add labels in Pages admin list for configured Stak pages.
 */
add_filter('display_post_states', function ($post_states, $post) {
    if (!is_admin() || !($post instanceof WP_Post) || $post->post_type !== 'page') {
        return $post_states;
    }

    $vendor_dashboard_id = (int) stakmv_get_option('vendor_dashboard_page', 0);
    $create_listing_id   = (int) stakmv_get_option('create_listing_page', 0);
    $browse_id           = (int) stakmv_get_option('browse_listings_page', 0);

    if ($vendor_dashboard_id > 0 && (int) $post->ID === $vendor_dashboard_id) {
        $post_states['stakmv_vendor_dashboard_page'] = 'Stak Vendor Dashboard Page';
    }

    if ($create_listing_id > 0 && (int) $post->ID === $create_listing_id) {
        $post_states['stakmv_create_listing_page'] = 'Stak Create Listing Page';
    }

    if ($browse_id > 0 && (int) $post->ID === $browse_id) {
        $post_states['stakmv_browse_listings_page'] = 'Stak Browse Listings Page';
    }

    return $post_states;
}, 10, 2);

add_action('stakmv_auctions_render_tab_general', function () {
    if (false === stakmv_get_option('auction_product_template', false)) {
        stakmv_update_option('auction_product_template', 'template_1');
    }

    /* =========================
       SAVE SETTINGS
    ========================= */

    if (isset($_POST['save_general'])) {
        check_admin_referer('stakmv_save_general', 'stakmv_save_general_nonce');

        stakmv_update_option(
            'create_listing_page',
            absint(wp_unslash($_POST['stakmv_create_listing_page'] ?? 0))
        );

        stakmv_update_option(
            'vendor_dashboard_page',
            absint(wp_unslash($_POST['stakmv_vendor_dashboard_page'] ?? 0))
        );

        stakmv_update_option(
            'browse_listings_page',
            absint(wp_unslash($_POST['stakmv_browse_listings_page'] ?? 0))
        );
        stakmv_update_option(
            'browse_heading',
            sanitize_text_field((string) wp_unslash($_POST['stakmv_browse_heading'] ?? 'Browse Listing'))
        );
        stakmv_update_option(
            'browse_subheading',
            sanitize_text_field((string) wp_unslash($_POST['stakmv_browse_subheading'] ?? 'choose from several items'))
        );

        stakmv_update_option(
            'enable_auctions',
            isset($_POST['stakmv_enable_auctions']) ? 'yes' : 'no'
        );

        $template = sanitize_key((string) wp_unslash($_POST['stakmv_auction_product_template'] ?? 'template_1'));
        if (!in_array($template, array('template_1', 'default_woo'), true)) {
            $template = 'template_1';
        }
        stakmv_update_option('auction_product_template', $template);

        $commission_rate = floatval(wp_unslash($_POST['stakmv_commission_rate'] ?? 0));
        if ($commission_rate < 0) {
            $commission_rate = 0;
        }
        if ($commission_rate > 100) {
            $commission_rate = 100;
        }
        stakmv_update_option('commission_rate', $commission_rate);

        echo '<div class="updated"><p>Settings saved.</p></div>';
    }

    if (
        isset($_POST['stakmv_create_pages']) &&
        isset($_POST['stakmv_save_general_nonce']) &&
        wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['stakmv_save_general_nonce'])), 'stakmv_save_general')
    ) {
        $created = array();
        $reused  = array();

        $dashboard = stakmv_ensure_shortcode_page(
            'Vendor Dashboard',
            'stakmv-vendor-dashboard',
            'stakmv_vendor_dashboard_page'
        );
        if ($dashboard['page_id'] > 0) {
            $dashboard['created'] ? $created[] = 'Vendor Dashboard' : $reused[] = 'Vendor Dashboard';
        }

        $create_listing = stakmv_ensure_shortcode_page(
            'Create Listing',
            'stakmv-vendor-create',
            'stakmv_create_listing_page'
        );
        if ($create_listing['page_id'] > 0) {
            $create_listing['created'] ? $created[] = 'Create Listing' : $reused[] = 'Create Listing';
        }

        $browse = stakmv_ensure_shortcode_page(
            'Shop',
            'stakmv-browse-listings',
            'stakmv_browse_listings_page'
        );
        if ($browse['page_id'] > 0) {
            $browse['created'] ? $created[] = 'Shop' : $reused[] = 'Shop';
        }

        stakmv_delete_transient('vendor_dashboard_page_id');
        stakmv_delete_transient('apply_vendor_page_id');

        $parts = array();
        if (!empty($created)) {
            $parts[] = 'Created: ' . implode(', ', $created) . '.';
        }
        if (!empty($reused)) {
            $parts[] = 'Already existed: ' . implode(', ', $reused) . '.';
        }
        if (empty($parts)) {
            $parts[] = 'No pages were created.';
        }

        echo '<div class="updated"><p>' . esc_html(implode(' ', $parts)) . '</p></div>';
    }

    /* =========================
       LOAD SAVED VALUES
    ========================= */

    $create_page     = absint(stakmv_get_option('create_listing_page'));
    $dashboard_page  = absint(stakmv_get_option('vendor_dashboard_page'));
    $browse_page     = absint(stakmv_get_option('browse_listings_page'));
    $browse_heading  = (string) stakmv_get_option('browse_heading', 'Browse Listing');
    $browse_subheading = (string) stakmv_get_option('browse_subheading', 'choose from several items');
    $enable          = stakmv_get_option('enable_auctions', 'yes');
    $product_template = (string) stakmv_get_option('auction_product_template', 'template_1');
    if (!in_array($product_template, array('template_1', 'default_woo'), true)) {
        $product_template = 'template_1';
    }
    $commission      = stakmv_get_option('commission_rate', 20);
    ?>

    <form method="post">
        <?php wp_nonce_field('stakmv_save_general', 'stakmv_save_general_nonce'); ?>
        <table class="form-table">

            <tr>
                <th scope="row">Enable Auctions</th>
                <td>
                    <label>
                        <input type="checkbox" name="stakmv_enable_auctions" <?php checked($enable, 'yes'); ?>>
                        Enable auction functionality site-wide
                    </label>
                </td>
            </tr>

            <tr>
                <th scope="row">Auction Product Page Template</th>
                <td>
                    <select name="stakmv_auction_product_template">
                        <option value="template_1" <?php selected($product_template, 'template_1'); ?>>Template 1 (Modern)</option>
                        <option value="default_woo" <?php selected($product_template, 'default_woo'); ?>>Use default WooCommerce page</option>
                    </select>
                    <p class="description">Default WooCommerce page is not recommended for auction-focused UX.</p>
                </td>
            </tr>

            <tr>
                <th scope="row">Vendor Dashboard Page</th>
                <td>
                    <?php
                    echo wp_kses(wp_dropdown_pages(array(
                        'name'             => 'stakmv_vendor_dashboard_page',
                        'selected'         => $dashboard_page,
                        'show_option_none' => '-- Select Page --',
                        'echo'             => 0,
                    )), array(
                        'select' => array('name' => true, 'id' => true, 'class' => true),
                        'option' => array('value' => true, 'selected' => true, 'class' => true),
                    ));
                    ?>
                </td>
            </tr>

            <tr>
                <th scope="row">Create Listing Page</th>
                <td>
                    <?php
                    echo wp_kses(wp_dropdown_pages(array(
                        'name'             => 'stakmv_create_listing_page',
                        'selected'         => $create_page,
                        'show_option_none' => '-- Select Page --',
                        'echo'             => 0,
                    )), array(
                        'select' => array('name' => true, 'id' => true, 'class' => true),
                        'option' => array('value' => true, 'selected' => true, 'class' => true),
                    ));
                    ?>
                    <p class="description">Page vendors use to create auction listings.</p>
                </td>
            </tr>

            <tr>
                <th scope="row">Shop Page (Browse Listings)</th>
                <td>
                    <?php
                    echo wp_kses(wp_dropdown_pages(array(
                        'name'             => 'stakmv_browse_listings_page',
                        'selected'         => $browse_page,
                        'show_option_none' => '-- Select Page --',
                        'echo'             => 0,
                    )), array(
                        'select' => array('name' => true, 'id' => true, 'class' => true),
                        'option' => array('value' => true, 'selected' => true, 'class' => true),
                    ));
                    ?>
                </td>
            </tr>

            <tr>
                <th scope="row">Browse Listing Heading</th>
                <td>
                    <input
                        type="text"
                        name="stakmv_browse_heading"
                        value="<?php echo esc_attr($browse_heading); ?>"
                        class="regular-text"
                    >
                </td>
            </tr>

            <tr>
                <th scope="row">Browse Listing Subheading</th>
                <td>
                    <input
                        type="text"
                        name="stakmv_browse_subheading"
                        value="<?php echo esc_attr($browse_subheading); ?>"
                        class="regular-text"
                    >
                </td>
            </tr>

            <tr>
                <th scope="row">Commission Rate (%)</th>
                <td>
                    <input type="number" step="0.01" min="0" name="stakmv_commission_rate" value="<?php echo esc_attr($commission); ?>">
                    <p class="description">Percentage deducted from each vendor payout before crediting the wallet.</p>
                </td>
            </tr>

            <tr>
                <th scope="row">Page Setup</th>
                <td>
                    <button type="submit" name="stakmv_create_pages" value="1" class="button">
                        Create/Assign Core Pages
                    </button>
                    <p class="description">Creates or reuses: Vendor Dashboard, Create Listing, and Shop (Browse Listings).</p>
                </td>
            </tr>

        </table>

        <p>
            <button type="submit" name="save_general" class="button-primary">Save Changes</button>
        </p>
    </form>

    <?php
});
