<?php
defined('ABSPATH') || exit;

use AI_BotKit\Integration\PEP_Detector;
use AI_BotKit\Integration\API_Handler;

$pep_settings = get_option('ai_botkit_pep_settings', []);
$pep_enabled = $pep_settings['enabled'] ?? false;
$pep_button_mode = $pep_settings['button_mode'] ?? 'new';
$pep_button_label = $pep_settings['button_label'] ?? __('Get Quote', 'ai-botkit-for-lead-generation');
$pep_button_position = $pep_settings['button_position'] ?? 'after_add_to_cart';
$pep_chatbot_id = $pep_settings['chatbot_id'] ?? '';

// Fetch chatbots for dropdown
$api_handler = new API_Handler();
$chatbots_data = $api_handler->send_get_request('chatbots');
$chatbots = isset($chatbots_data['data']) ? $chatbots_data['data'] : [];

// Fetch PEP enquiry form details for the prompt
$pep_form_option = get_option('wdm_form_data', []);
$enquiry_form_type = $pep_form_option['enquiry_form'] ?? 'default';
$form_fields = [];

if ($enquiry_form_type === 'default') {
    $form_fields = [
        ['label' => 'Name',     'required' => true],
        ['label' => 'Email',    'required' => true],
        ['label' => 'Phone',    'required' => true],
        ['label' => 'Quantity', 'required' => true],
        ['label' => 'Subject',  'required' => true],
        ['label' => 'Message',  'required' => true],
    ];
} elseif ($enquiry_form_type === 'custom' && !empty($pep_form_option['custom_formId'])) {
    $form_id = absint($pep_form_option['custom_formId']);
    $form_post = get_post($form_id);
    if ($form_post && $form_post->post_type === 'form') {
        $form_data = get_post_meta($form_id, 'form_data', true);
        if (!empty($form_data)) {
            $parsed = maybe_unserialize($form_data);
            if (is_array($parsed) && !empty($parsed['fields'])) {
                foreach ($parsed['fields'] as $key => $label) {
                    $is_required = false;
                    if (isset($parsed['fieldsinfo'][$key]['required']) && $parsed['fieldsinfo'][$key]['required'] == 1) {
                        $is_required = true;
                    }
                    $form_fields[] = [
                        'label'    => isset($parsed['fieldsinfo'][$key]['label']) ? $parsed['fieldsinfo'][$key]['label'] : $label,
                        'required' => $is_required,
                    ];
                }
            }
        }
    }
}

$form_lines = [];
foreach ($form_fields as $field) {
    $line = $field['label'];
    if ($field['required']) {
        $line .= ' *';
    }
    $form_lines[] = $line;
}

error_log(print_r($form_fields, true));

$form_fields_text = empty($form_lines)
    ? __('Name *, Email *, Phone *, Quantity *, Subject, Message', 'ai-botkit-for-lead-generation')
    : implode(",\n", $form_lines);

$default_prompt = sprintf(
    __("You are an AI sales and quotation assistant.

Your role is to:
help visitors explore products from the uploaded catalog
answer product and pricing questions
recommend suitable products
collect enquiry details naturally
generate a professional quotation in table format

You must behave like a smart sales executive, not a support chatbot.

--------------------------------------------------
CONVERSATION FLOW
--------------------------------------------------

Whenever a visitor asks about a product:

1. Identify the matching product from the uploaded catalog.
2. Explain the product briefly:
   - model name
   - frame type
   - material
   - available colors
   - specifications
   - unit price
   - MOQ if available

3. Then collect customer details conversationally one-by-one.

--------------------------------------------------
LEAD COLLECTION QUESTIONS
--------------------------------------------------

Ask naturally:

%s

Rules:
- Only fields marked with * are required.
- If the user does not provide non-required fields, do not force them.
- Ask questions one at a time so the conversation feels natural.
- Never ask all fields together.
- First collect all required fields.
- After required fields are collected, create a draft quotation.
- Then optionally ask for non-required fields.
- If any information can already be inferred from the conversation, auto-fill it.
- Do not ask the same question repeatedly.
Example:
“Great choice. May I know how many pieces you’re looking for?”

--------------------------------------------------
RECOMMENDATION RULES
--------------------------------------------------

If the customer is unsure:
ask guiding questions
recommend products from the catalog only

Example:
budget range
men/women/kids
sunglasses or optical
premium or budget category

Never invent products outside the uploaded catalog.

--------------------------------------------------
PRICING RULES
--------------------------------------------------

Use ONLY prices available in the uploaded catalog.
Never guess pricing.
Never invent discounts.
If pricing is unavailable:
  “The exact pricing is not available in the catalog. Our team will confirm it shortly.”

--------------------------------------------------
FINAL QUOTATION FORMAT
--------------------------------------------------

Once all details are collected, generate the quotation in a CLEAN HTML TABLE FORMAT.
Trigger lead collection based on the gathered data.

Use this exact structure:

# QUOTATION SUMMARY

| Product | Model No | Variant/Color | Qty | Unit Price | Total |
|---|---|---|---|---|---|
| Product Name | M102 | Black | 100 | ₹250 | ₹25,000 |

After the table, include:

Customer Details:
Name:
Company:
Location:
Email:
WhatsApp:

Additional Notes:
MOQ if applicable
Shipping note
Tax note
Delivery note

Then end with:

“Thank you! Your quotation request has been prepared successfully. Our team will contact you shortly.”

--------------------------------------------------
IMPORTANT RULES
--------------------------------------------------

Always generate quotations in tabular HTML format.
If multiple products are selected, include all products in the same table.
Keep responses short, professional, and sales-oriented.
Never hallucinate prices or stock.
Never answer outside the uploaded catalog knowledge.
Never show empty values, blank fields, placeholders, 'N/A', '-', or null data anywhere in the conversation, product details, customer details, or quotation table.

--------------------------------------------------
MAIN GOAL
--------------------------------------------------

Convert visitors into qualified leads and generate clean quotation-ready summaries automatically.", 'ai-botkit-for-lead-generation'),
    $form_fields_text
);
?>

<div class="ai-botkit-dashboard-wrapper">
    <div class="ai-botkit-dashboard-container">
        <div class="ai-botkit-dashboard-header">
            <div class="ai-botkit-knowledge-header-left">
                <h1 class="ai-botkit-dashboard-title"><?php esc_html_e('WooCommerce Enquiry', 'ai-botkit-for-lead-generation'); ?></h1>
                <p class="ai-botkit-dashboard-subtitle"><?php esc_html_e('Configure Product Enquiry for WooCommerce integration settings.', 'ai-botkit-for-lead-generation'); ?></p>
            </div>
        </div>

        <div class="ai-botkit-card">
            <div class="ai-botkit-card-header">
                <h3><?php esc_html_e('Product Enquiry Integration Settings', 'ai-botkit-for-lead-generation'); ?></h3>
                <p><?php esc_html_e('Manage how the Ask AI button appears on WooCommerce product pages.', 'ai-botkit-for-lead-generation'); ?></p>
            </div>
            <div class="ai-botkit-card-body">
                <?php if ( ! PEP_Detector::is_woocommerce_active() ) : ?>
                    <div class="notice notice-warning inline">
                        <p>
                            <?php esc_html_e( 'WooCommerce is not active. Please install and activate WooCommerce to use this integration.', 'ai-botkit-for-lead-generation' ); ?>
                        </p>
                    </div>
                <?php endif; ?>

                <form method="post" action="">
                    <?php wp_nonce_field('ai_botkit_pep_settings', 'ai_botkit_pep_nonce'); ?>

                    <div class="ai-botkit-form-group">
                        <label class="ai-botkit-label">
                            <input type="checkbox" name="pep_enabled" value="1" <?php checked($pep_enabled, true); ?> />
                            <?php esc_html_e('Enable Product Enquiry Integration', 'ai-botkit-for-lead-generation'); ?>
                        </label>
                        <p class="ai-botkit-help-text"><?php esc_html_e('When enabled, the Ask AI button will appear on WooCommerce product pages.', 'ai-botkit-for-lead-generation'); ?></p>
                    </div>

                    <div class="ai-botkit-form-group">
                        <label class="ai-botkit-select-label" for="pep_button_mode"><?php esc_html_e('Button Mode:', 'ai-botkit-for-lead-generation'); ?></label>
                        <select name="pep_button_mode" id="pep_button_mode" class="ai-botkit-select-input">
                            <option value="new" <?php selected($pep_button_mode, 'new'); ?>><?php esc_html_e('Add New Button', 'ai-botkit-for-lead-generation'); ?></option>
                            <option value="override" <?php selected($pep_button_mode, 'override'); ?>><?php esc_html_e('Override Request a Quote', 'ai-botkit-for-lead-generation'); ?></option>
                        </select>
                        <p class="ai-botkit-help-text"><?php esc_html_e('Choose whether to add a new button or replace the existing PEP button.', 'ai-botkit-for-lead-generation'); ?></p>
                    </div>

                    <div class="ai-botkit-form-group">
                        <label class="ai-botkit-select-label" for="pep_button_label"><?php esc_html_e('Button Label:', 'ai-botkit-for-lead-generation'); ?></label>
                        <input type="text" name="pep_button_label" id="pep_button_label" value="<?php echo esc_attr($pep_button_label); ?>" class="ai-botkit-input" />
                        <p class="ai-botkit-help-text"><?php esc_html_e('Custom label for the Ask AI button.', 'ai-botkit-for-lead-generation'); ?></p>
                    </div>

                    <div class="ai-botkit-form-group">
                        <label class="ai-botkit-select-label" for="pep_button_position"><?php esc_html_e('Button Position:', 'ai-botkit-for-lead-generation'); ?></label>
                        <select name="pep_button_position" id="pep_button_position" class="ai-botkit-select-input">
                            <option value="after_add_to_cart" <?php selected($pep_button_position, 'after_add_to_cart'); ?>><?php esc_html_e('After Add to Cart', 'ai-botkit-for-lead-generation'); ?></option>
                            <option value="after_summary" <?php selected($pep_button_position, 'after_summary'); ?>><?php esc_html_e('After Product Summary', 'ai-botkit-for-lead-generation'); ?></option>
                        </select>
                    </div>

                    <div class="ai-botkit-form-group">
                        <label class="ai-botkit-select-label" for="pep_chatbot_id"><?php esc_html_e('Trigger Chatbot:', 'ai-botkit-for-lead-generation'); ?></label>
                        <select name="pep_chatbot_id" id="pep_chatbot_id" class="ai-botkit-select-input">
                            <option value=""><?php esc_html_e('-- Select a Chatbot --', 'ai-botkit-for-lead-generation'); ?></option>
                            <?php foreach ($chatbots as $chatbot) :
                                $bot_id = isset($chatbot['messagesTemplate']['namespace']) ? $chatbot['messagesTemplate']['namespace'] : '';
                                $bot_name = isset($chatbot['name']) ? $chatbot['name'] : __('Unnamed Bot', 'ai-botkit-for-lead-generation');
                            ?>
                                <option value="<?php echo esc_attr($bot_id); ?>" <?php selected($pep_chatbot_id, $bot_id); ?>>
                                    <?php echo esc_html($bot_name); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <p class="ai-botkit-help-text"><?php esc_html_e('The button will only appear on pages where this chatbot is active.', 'ai-botkit-for-lead-generation'); ?></p>
                    </div>

                    <div class="ai-botkit-card-footer">
                        <button type="submit" name="ai_botkit_pep_settings" class="ai-botkit-btn-primary">
                            <?php esc_html_e('Save PEP Settings', 'ai-botkit-for-lead-generation'); ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="ai-botkit-card">
            <div class="ai-botkit-card-header">
                <h3><?php esc_html_e('Need Help Setting Up?', 'ai-botkit-for-lead-generation'); ?></h3>
                <p><?php esc_html_e('Watch the tutorial video or read the documentation to get started.', 'ai-botkit-for-lead-generation'); ?></p>
            </div>
            <div class="ai-botkit-card-body">
                <div style="display:flex;gap:0.625rem;flex-wrap:wrap;">
                    <a href="https://youtu.be/OhTKgqKxo9A?si=7Xpb67vjn5kbH1Z8" target="_blank" rel="noopener noreferrer" class="ai-botkit-btn-primary" style="text-decoration:none;">
                        <?php esc_html_e('Watch Video Tutorial', 'ai-botkit-for-lead-generation'); ?>
                    </a>
                    <a href="https://aibotkit.gitbook.io/documentation/woocommerce/pep-woocommerce-integration" target="_blank" rel="noopener noreferrer" class="ai-botkit-btn-outline" style="text-decoration:none;">
                        <?php esc_html_e('Read Documentation', 'ai-botkit-for-lead-generation'); ?>
                    </a>
                </div>
            </div>
        </div>

        <div class="ai-botkit-card">
            <div class="ai-botkit-card-header">
                <h3><?php esc_html_e('Enquiry Agent Prompt', 'ai-botkit-for-lead-generation'); ?></h3>
                <p><?php esc_html_e('Copy this prompt into your chatbot settings to make it work as an enquiry agent.', 'ai-botkit-for-lead-generation'); ?></p>
            </div>
            <div class="ai-botkit-card-body">
                <div class="ai-botkit-prompt-wrapper">
                    <label class="ai-botkit-select-label" for="ai_botkit_pep_prompt">
                        <?php esc_html_e('Suggested Prompt', 'ai-botkit-for-lead-generation'); ?>
                    </label>
                    <textarea
                        id="ai_botkit_pep_prompt"
                        class="ai-botkit-textarea ai-botkit-prompt-textarea"
                        rows="12"
                        readonly
                    ><?php echo esc_textarea($default_prompt); ?></textarea>
                    <p class="ai-botkit-help-text">
                        <?php esc_html_e('This prompt is automatically generated based on your current enquiry form configuration.', 'ai-botkit-for-lead-generation'); ?>
                    </p>
                    <button type="button" class="ai-botkit-btn-primary ai-botkit-copy-prompt-btn" data-target="ai_botkit_pep_prompt">
                        <?php esc_html_e('Copy Prompt', 'ai-botkit-for-lead-generation'); ?>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
