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

function stakmv_get_color_presets() {
    return array(
        'carnival' => array(
            'label'  => 'Carnival Classic',
            'colors' => array(
                'page_bg_start'    => '#fff7ed',
                'page_bg_end'      => '#ffedd5',
                'card_bg'          => '#ffffff',
                'card_border'      => '#fbbf24',
                'heading_text'     => '#7c2d12',
                'body_text'        => '#1f2937',
                'muted_text'       => '#6b7280',
                'button_start'     => '#f97316',
                'button_end'       => '#dc2626',
                'success'          => '#16a34a',
                'info'             => '#2563eb',
                'danger'           => '#dc2626',
                'badge_bg'         => '#6366f1',
            ),
        ),
        'ocean' => array(
            'label'  => 'Ocean Breeze',
            'colors' => array(
                'page_bg_start'    => '#eff6ff',
                'page_bg_end'      => '#dbeafe',
                'card_bg'          => '#ffffff',
                'card_border'      => '#7dd3fc',
                'heading_text'     => '#0f172a',
                'body_text'        => '#0f172a',
                'muted_text'       => '#475569',
                'button_start'     => '#0ea5e9',
                'button_end'       => '#2563eb',
                'success'          => '#059669',
                'info'             => '#0284c7',
                'danger'           => '#e11d48',
                'badge_bg'         => '#0ea5e9',
            ),
        ),
        'forest' => array(
            'label'  => 'Forest Market',
            'colors' => array(
                'page_bg_start'    => '#f0fdf4',
                'page_bg_end'      => '#dcfce7',
                'card_bg'          => '#ffffff',
                'card_border'      => '#86efac',
                'heading_text'     => '#14532d',
                'body_text'        => '#1f2937',
                'muted_text'       => '#4b5563',
                'button_start'     => '#16a34a',
                'button_end'       => '#15803d',
                'success'          => '#16a34a',
                'info'             => '#0f766e',
                'danger'           => '#b91c1c',
                'badge_bg'         => '#15803d',
            ),
        ),
        'midnight' => array(
            'label'  => 'Midnight Pro',
            'colors' => array(
                'page_bg_start'    => '#111827',
                'page_bg_end'      => '#1f2937',
                'card_bg'          => '#0f172a',
                'card_border'      => '#334155',
                'heading_text'     => '#f8fafc',
                'body_text'        => '#e2e8f0',
                'muted_text'       => '#94a3b8',
                'button_start'     => '#3b82f6',
                'button_end'       => '#2563eb',
                'success'          => '#22c55e',
                'info'             => '#38bdf8',
                'danger'           => '#f43f5e',
                'badge_bg'         => '#6366f1',
            ),
        ),
        'custom' => array(
            'label'  => 'Custom',
            'colors' => array(),
        ),
    );
}

function stakmv_get_default_theme_colors() {
    $presets = stakmv_get_color_presets();
    return $presets['ocean']['colors'];
}

function stakmv_get_theme_colors() {
    $defaults = stakmv_get_default_theme_colors();
    $saved    = stakmv_get_option('theme_colors', array());

    if (!is_array($saved)) {
        $saved = array();
    }

    $colors = array();
    foreach ($defaults as $key => $value) {
        $candidate = isset($saved[$key]) ? sanitize_hex_color((string) $saved[$key]) : '';
        $colors[$key] = $candidate ? $candidate : $value;
    }

    return $colors;
}

function stakmv_get_corner_style() {
    $style = (string) stakmv_get_option('corner_style', 'flat');
    return in_array($style, array('rounded', 'flat'), true) ? $style : 'flat';
}

function stakmv_get_dashboard_tabs_layout() {
    $layout = (string) stakmv_get_option('dashboard_tabs_layout', 'vertical');
    return in_array($layout, array('horizontal', 'vertical'), true) ? $layout : 'horizontal';
}

function stakmv_get_frontend_layout_mode() {
    $mode = (string) stakmv_get_option('frontend_layout_mode', 'boxed');
    return in_array($mode, array('boxed', 'full_width'), true) ? $mode : 'boxed';
}

function stakmv_get_product_page_layout_mode() {
    $mode = (string) stakmv_get_option('product_page_layout_mode', 'full_width');
    return in_array($mode, array('contained', 'full_width'), true) ? $mode : 'full_width';
}

function stakmv_get_product_page_corner_style() {
    $style = (string) stakmv_get_option('product_page_corner_style', 'flat');
    return in_array($style, array('rounded', 'flat'), true) ? $style : 'flat';
}

function stakmv_get_product_button_style_options() {
    $defaults = array(
        'border_color' => '#2563eb',
        'text_color'   => '#2563eb',
        'hover_bg'     => '#2563eb',
        'hover_text'   => '#ffffff',
        'radius'       => 10,
        'border_width' => 1,
    );

    $saved = stakmv_get_option('product_button_style', array());
    if (!is_array($saved)) {
        $saved = array();
    }

    $out = $defaults;
    $hex_keys = array('border_color', 'text_color', 'hover_bg', 'hover_text');
    foreach ($hex_keys as $key) {
        if (isset($saved[$key])) {
            $hex = sanitize_hex_color((string) $saved[$key]);
            if ($hex) {
                $out[$key] = $hex;
            }
        }
    }

    $radius = isset($saved['radius']) ? (int) $saved['radius'] : $defaults['radius'];
    $border_width = isset($saved['border_width']) ? (int) $saved['border_width'] : $defaults['border_width'];
    $out['radius'] = max(0, min(24, $radius));
    $out['border_width'] = max(1, min(4, $border_width));

    return $out;
}

add_action('plugins_loaded', function () {
    if (false === stakmv_get_option('theme_preset', false)) {
        stakmv_update_option('theme_preset', 'ocean');
    }

    if (false === stakmv_get_option('theme_colors', false)) {
        stakmv_update_option('theme_colors', stakmv_get_default_theme_colors());
    }

    if (false === stakmv_get_option('dashboard_tabs_layout', false)) {
        stakmv_update_option('dashboard_tabs_layout', 'vertical');
    }

    if (false === stakmv_get_option('corner_style', false)) {
        stakmv_update_option('corner_style', 'flat');
    }

    if (false === stakmv_get_option('frontend_layout_mode', false)) {
        stakmv_update_option('frontend_layout_mode', 'boxed');
    }

    if (false === stakmv_get_option('product_page_layout_mode', false)) {
        stakmv_update_option('product_page_layout_mode', 'full_width');
    }

    if (false === stakmv_get_option('product_page_corner_style', false)) {
        stakmv_update_option('product_page_corner_style', 'flat');
    }

    if (false === stakmv_get_option('product_button_style', false)) {
        stakmv_update_option('product_button_style', stakmv_get_product_button_style_options());
    }
}, 20);

add_action('stakmv_auctions_settings_tabs', function ($current_tab) {
    if (!current_user_can('manage_woocommerce')) {
        return;
    }

    $active = $current_tab === 'appearance' ? 'nav-tab-active' : '';
    printf(
        '<a href="?page=stakmv-auctions&tab=appearance" class="nav-tab %s">Appearance</a>',
        esc_attr($active)
    );
}, 14);

add_action('stakmv_auctions_render_tab_appearance', function () {
    if (!current_user_can('manage_woocommerce')) {
        echo '<p>Insufficient permissions.</p>';
        return;
    }

    $presets = stakmv_get_color_presets();

    if (isset($_POST['save_appearance'])) {
        check_admin_referer('stakmv_save_appearance', 'stakmv_save_appearance_nonce');
        $selected_preset = sanitize_key((string) wp_unslash($_POST['stakmv_theme_preset_choice'] ?? 'ocean'));
        if (!isset($presets[$selected_preset])) {
            $selected_preset = 'ocean';
        }

        if ($selected_preset === 'custom') {
            $defaults = stakmv_get_default_theme_colors();
            $colors   = array();
            foreach ($defaults as $key => $default_value) {
                $raw = isset($_POST[$key]) ? sanitize_hex_color((string) wp_unslash($_POST[$key])) : '';
                $colors[$key] = $raw ? $raw : $default_value;
            }
            stakmv_update_option('theme_colors', $colors);
            stakmv_update_option('theme_preset', 'custom');
        } else {
            stakmv_update_option('theme_preset', $selected_preset);
            stakmv_update_option('theme_colors', $presets[$selected_preset]['colors']);
        }

        $corner_style = sanitize_key(wp_unslash($_POST['stakmv_corner_style'] ?? 'flat'));
        if (!in_array($corner_style, array('rounded', 'flat'), true)) {
            $corner_style = 'flat';
        }

        $tabs_layout = sanitize_key(wp_unslash($_POST['stakmv_dashboard_tabs_layout'] ?? 'vertical'));
        if (!in_array($tabs_layout, array('horizontal', 'vertical'), true)) {
            $tabs_layout = 'horizontal';
        }

        $layout_mode = sanitize_key(wp_unslash($_POST['stakmv_frontend_layout_mode'] ?? 'boxed'));
        if (!in_array($layout_mode, array('boxed', 'full_width'), true)) {
            $layout_mode = 'boxed';
        }

        $product_layout_mode = sanitize_key(wp_unslash($_POST['stakmv_product_page_layout_mode'] ?? 'full_width'));
        if (!in_array($product_layout_mode, array('contained', 'full_width'), true)) {
            $product_layout_mode = 'full_width';
        }

        $product_corner_style = sanitize_key(wp_unslash($_POST['stakmv_product_page_corner_style'] ?? 'flat'));
        if (!in_array($product_corner_style, array('rounded', 'flat'), true)) {
            $product_corner_style = 'flat';
        }

        stakmv_update_option('corner_style', $corner_style);
        stakmv_update_option('dashboard_tabs_layout', $tabs_layout);
        stakmv_update_option('frontend_layout_mode', $layout_mode);
        stakmv_update_option('product_page_layout_mode', $product_layout_mode);
        stakmv_update_option('product_page_corner_style', $product_corner_style);

        $button_style = stakmv_get_product_button_style_options();
        $button_style['border_color'] = sanitize_hex_color((string) wp_unslash($_POST['stakmv_product_btn_border_color'] ?? $button_style['border_color'])) ?: $button_style['border_color'];
        $button_style['text_color'] = sanitize_hex_color((string) wp_unslash($_POST['stakmv_product_btn_text_color'] ?? $button_style['text_color'])) ?: $button_style['text_color'];
        $button_style['hover_bg'] = sanitize_hex_color((string) wp_unslash($_POST['stakmv_product_btn_hover_bg'] ?? $button_style['hover_bg'])) ?: $button_style['hover_bg'];
        $button_style['hover_text'] = sanitize_hex_color((string) wp_unslash($_POST['stakmv_product_btn_hover_text'] ?? $button_style['hover_text'])) ?: $button_style['hover_text'];
        $button_style['radius'] = max(
            0,
            min(
                24,
                (int) sanitize_text_field((string) wp_unslash($_POST['stakmv_product_btn_radius'] ?? (string) $button_style['radius']))
            )
        );
        $button_style['border_width'] = max(
            1,
            min(
                4,
                (int) sanitize_text_field((string) wp_unslash($_POST['stakmv_product_btn_border_width'] ?? (string) $button_style['border_width']))
            )
        );
        stakmv_update_option('product_button_style', $button_style);
        echo '<div class="updated"><p>Appearance settings saved.</p></div>';
    }

    $active_preset = (string) stakmv_get_option('theme_preset', 'ocean');
    $colors = stakmv_get_theme_colors();
    $corner_style = stakmv_get_corner_style();
    $tabs_layout = stakmv_get_dashboard_tabs_layout();
    $layout_mode = stakmv_get_frontend_layout_mode();
    $product_layout_mode = stakmv_get_product_page_layout_mode();
    $product_corner_style = stakmv_get_product_page_corner_style();
    $product_button_style = stakmv_get_product_button_style_options();
    ?>

    <h2>Appearance</h2>
    <p>Choose a preset theme style. Color palette controls only appear when Custom is selected.</p>

    <form method="post">
        <?php wp_nonce_field('stakmv_save_appearance', 'stakmv_save_appearance_nonce'); ?>

        <h3>Color Presets</h3>
        <p class="description">Pick a style thumbnail below.</p>
        <div class="wcmv-presets-grid">
            <?php
            $preset_images = array(
                'carnival' => 'carnival.jpg',
                'ocean'    => 'ocean.jpg',
                'forest'   => 'forest.jpg',
                'midnight' => 'midnight.jpg',
                'custom'   => 'custom.png',
            );
            foreach ($presets as $preset_key => $preset_data) :
                $img_file = isset($preset_images[$preset_key]) ? $preset_images[$preset_key] : '';
                $img_url = $img_file ? (STAKMV_PLUGIN_URL . 'assets/images/' . $img_file) : '';
            ?>
                <label class="wcmv-preset-card<?php echo $active_preset === $preset_key ? ' is-active' : ''; ?>">
                    <input
                        type="radio"
                        name="stakmv_theme_preset_choice"
                        value="<?php echo esc_attr($preset_key); ?>"
                        <?php checked($active_preset, $preset_key); ?>
                    >
                    <span class="wcmv-preset-thumb-wrap">
                        <?php if ($img_url) : ?>
                            <img class="wcmv-preset-thumb" src="<?php echo esc_url($img_url); ?>" alt="<?php echo esc_attr($preset_data['label']); ?>">
                        <?php endif; ?>
                    </span>
                    <span class="wcmv-preset-label"><?php echo esc_html($preset_data['label']); ?></span>
                </label>
            <?php endforeach; ?>
        </div>

        <div id="wcmv-custom-palette-section" class="<?php echo $active_preset === 'custom' ? '' : 'wcmv-hidden'; ?>">
        <h3>Custom Palette</h3>
        <table class="form-table" role="presentation">
            <tr>
                <th scope="row"><label for="page_bg_start">Page Background Start</label></th>
                <td><input type="color" id="page_bg_start" name="page_bg_start" value="<?php echo esc_attr($colors['page_bg_start']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="page_bg_end">Page Background End</label></th>
                <td><input type="color" id="page_bg_end" name="page_bg_end" value="<?php echo esc_attr($colors['page_bg_end']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="card_bg">Card Background</label></th>
                <td><input type="color" id="card_bg" name="card_bg" value="<?php echo esc_attr($colors['card_bg']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="card_border">Card Border</label></th>
                <td><input type="color" id="card_border" name="card_border" value="<?php echo esc_attr($colors['card_border']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="heading_text">Heading Text</label></th>
                <td><input type="color" id="heading_text" name="heading_text" value="<?php echo esc_attr($colors['heading_text']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="body_text">Body Text</label></th>
                <td><input type="color" id="body_text" name="body_text" value="<?php echo esc_attr($colors['body_text']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="muted_text">Muted Text</label></th>
                <td><input type="color" id="muted_text" name="muted_text" value="<?php echo esc_attr($colors['muted_text']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="button_start">Primary Button Start</label></th>
                <td><input type="color" id="button_start" name="button_start" value="<?php echo esc_attr($colors['button_start']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="button_end">Primary Button End</label></th>
                <td><input type="color" id="button_end" name="button_end" value="<?php echo esc_attr($colors['button_end']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="success">Success (Prices)</label></th>
                <td><input type="color" id="success" name="success" value="<?php echo esc_attr($colors['success']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="info">Info Accent</label></th>
                <td><input type="color" id="info" name="info" value="<?php echo esc_attr($colors['info']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="danger">Danger Accent</label></th>
                <td><input type="color" id="danger" name="danger" value="<?php echo esc_attr($colors['danger']); ?>"></td>
            </tr>
            <tr>
                <th scope="row"><label for="badge_bg">Badge Background</label></th>
                <td><input type="color" id="badge_bg" name="badge_bg" value="<?php echo esc_attr($colors['badge_bg']); ?>"></td>
            </tr>
        </table>
        </div>

        <h3>Layout & Shape</h3>
        <table class="form-table" role="presentation">
            <tr>
                <th scope="row">Corner Style</th>
                <td>
                    <label style="margin-right:14px;">
                        <input type="radio" name="stakmv_corner_style" value="rounded" <?php checked($corner_style, 'rounded'); ?>>
                        Rounded
                    </label>
                    <label>
                        <input type="radio" name="stakmv_corner_style" value="flat" <?php checked($corner_style, 'flat'); ?>>
                        Flat
                    </label>
                    <p class="description">Choose rounded edges (default) or flat edges across major UI components.</p>
                </td>
            </tr>
            <tr>
                <th scope="row">Dashboard Tabs Layout</th>
                <td>
                    <label style="margin-right:14px;">
                        <input type="radio" name="stakmv_dashboard_tabs_layout" value="horizontal" <?php checked($tabs_layout, 'horizontal'); ?>>
                        Horizontal
                    </label>
                    <label>
                        <input type="radio" name="stakmv_dashboard_tabs_layout" value="vertical" <?php checked($tabs_layout, 'vertical'); ?>>
                        Vertical
                    </label>
                    <p class="description">Choose how vendor dashboard tabs are displayed.</p>
                </td>
            </tr>
            <tr>
                <th scope="row">Frontend Layout Width</th>
                <td>
                    <label style="margin-right:14px;">
                        <input type="radio" name="stakmv_frontend_layout_mode" value="boxed" <?php checked($layout_mode, 'boxed'); ?>>
                        Boxed
                    </label>
                    <label>
                        <input type="radio" name="stakmv_frontend_layout_mode" value="full_width" <?php checked($layout_mode, 'full_width'); ?>>
                        Full Width
                    </label>
                    <p class="description">Boxed keeps centered container width. Full width stretches major frontend dashboard/listing wrappers.</p>
                </td>
            </tr>
            <tr>
                <th scope="row">Product Page Width</th>
                <td>
                    <label style="margin-right:14px;">
                        <input type="radio" name="stakmv_product_page_layout_mode" value="full_width" <?php checked($product_layout_mode, 'full_width'); ?>>
                        Full Width
                    </label>
                    <label>
                        <input type="radio" name="stakmv_product_page_layout_mode" value="contained" <?php checked($product_layout_mode, 'contained'); ?>>
                        Contained
                    </label>
                    <p class="description">Controls width for the custom auction product page only.</p>
                </td>
            </tr>
            <tr>
                <th scope="row">Product Page Corners</th>
                <td>
                    <label style="margin-right:14px;">
                        <input type="radio" name="stakmv_product_page_corner_style" value="rounded" <?php checked($product_corner_style, 'rounded'); ?>>
                        Rounded
                    </label>
                    <label>
                        <input type="radio" name="stakmv_product_page_corner_style" value="flat" <?php checked($product_corner_style, 'flat'); ?>>
                        Flat
                    </label>
                    <p class="description">Controls corner style for the custom auction product page only.</p>
                </td>
            </tr>
            <tr>
                <th scope="row">Product Button Style</th>
                <td>
                    <p>
                        <label style="display:inline-block; margin-right:12px;">Border color
                            <input type="color" name="stakmv_product_btn_border_color" value="<?php echo esc_attr($product_button_style['border_color']); ?>">
                        </label>
                        <label style="display:inline-block; margin-right:12px;">Text color
                            <input type="color" name="stakmv_product_btn_text_color" value="<?php echo esc_attr($product_button_style['text_color']); ?>">
                        </label>
                        <label style="display:inline-block; margin-right:12px;">Hover background
                            <input type="color" name="stakmv_product_btn_hover_bg" value="<?php echo esc_attr($product_button_style['hover_bg']); ?>">
                        </label>
                        <label style="display:inline-block;">Hover text
                            <input type="color" name="stakmv_product_btn_hover_text" value="<?php echo esc_attr($product_button_style['hover_text']); ?>">
                        </label>
                    </p>
                    <p>
                        <label style="display:inline-block; margin-right:12px;">Radius (px)
                            <input type="number" min="0" max="24" step="1" name="stakmv_product_btn_radius" value="<?php echo esc_attr((string) $product_button_style['radius']); ?>">
                        </label>
                        <label style="display:inline-block;">Border width (px)
                            <input type="number" min="1" max="4" step="1" name="stakmv_product_btn_border_width" value="<?php echo esc_attr((string) $product_button_style['border_width']); ?>">
                        </label>
                    </p>
                    <p class="description">Applies to custom auction product page action buttons.</p>
                </td>
            </tr>
        </table>

        <p>
            <button type="submit" name="save_appearance" class="button-primary">Save Appearance</button>
        </p>
    </form>

    <?php
});
