<?php
// Savit Research Module — UI
// Adapted from ai-prompt-research.php

$countries = [
    'IN' => ['name' => 'India', 'flag' => 'in', 'dataforseo_name' => 'India'],
    'US' => ['name' => 'United States', 'flag' => 'us', 'dataforseo_name' => 'United States'],
    'GB' => ['name' => 'United Kingdom', 'flag' => 'gb', 'dataforseo_name' => 'United Kingdom'],
    'CA' => ['name' => 'Canada', 'flag' => 'ca', 'dataforseo_name' => 'Canada'],
    'AU' => ['name' => 'Australia', 'flag' => 'au', 'dataforseo_name' => 'Australia'],
    'AE' => ['name' => 'UAE', 'flag' => 'ae', 'dataforseo_name' => 'United Arab Emirates'],
    'SG' => ['name' => 'Singapore', 'flag' => 'sg', 'dataforseo_name' => 'Singapore'],
    'DE' => ['name' => 'Germany', 'flag' => 'de', 'dataforseo_name' => 'Germany']
];

// Fetch projects for the URL option
$db = \CAE\Lib\Database::getInstance();
$projects = $db->fetchAll("SELECT id, business_name, website_url FROM projects ORDER BY business_name ASC");

require __DIR__ . '/../layout/header.php';
?>

<div id="research-container">
    <!-- Step 1: Initial Setup -->
    <div id="step-1" class="research-step active animate__animated animate__fadeIn">
        <div class="mb-4">
            <h2 class="h3 font-bold">How would you like to get started?</h2>
        </div>

        <div class="mb-5" style="max-width: 600px;">
            <label class="form-label small text-muted text-uppercase fw-bold mb-2 tracking-wider">Select AI Model</label>
            <div class="dropdown model-dropdown-wrapper">
                <button class="btn btn-white border dropdown-toggle d-flex align-items-center gap-2 py-2 w-100 justify-content-between rounded-3 shadow-none" type="button" id="modelDropdown" data-bs-toggle="dropdown">
                    <div class="d-flex align-items-center gap-2">
                        <span id="selected-model-icon"><i class="bi bi-robot"></i></span>
                        <span id="selected-model-text" class="fw-semibold">ChatGPT</span>
                    </div>
                    <i class="bi bi-chevron-down small opacity-50"></i>
                </button>
                <ul class="dropdown-menu shadow-sm border-0 w-100 mt-1">
                    <li><a class="dropdown-item platform-select py-2 d-flex align-items-center gap-2" href="#" data-platform="ChatGPT">
                        <i class="bi bi-chat-dots"></i> ChatGPT
                    </a></li>
                    <li><a class="dropdown-item platform-select py-2 d-flex align-items-center gap-2" href="#" data-platform="Claude">
                        <i class="bi bi-cpu"></i> Claude
                    </a></li>
                    <li><a class="dropdown-item platform-select py-2 d-flex align-items-center gap-2" href="#" data-platform="Gemini">
                        <i class="bi bi-stars"></i> Gemini
                    </a></li>
                    <li><a class="dropdown-item platform-select py-2 d-flex align-items-center gap-2" href="#" data-platform="Perplexity">
                        <i class="bi bi-search"></i> Perplexity
                    </a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item platform-select py-2 d-flex align-items-center gap-2" href="#" data-platform="Google AI Mode">
                        <i class="bi bi-google"></i> Google AI Mode
                    </a></li>
                </ul>
            </div>
            <input type="hidden" id="selected-platform" value="ChatGPT">
            <input type="hidden" id="selected-model-version" value="">
        </div>

        <!-- Option: SEO Keywords -->
        <div class="research-option-card mb-4 border rounded-4 bg-white p-4 transition-all-200 cursor-pointer active" data-type="keywords" style="max-width: 800px;">
            <div class="d-flex align-items-start gap-3">
                <div class="custom-radio-wrapper mt-1">
                    <input class="form-check-input custom-radio" type="radio" name="research_type" id="type-keywords" value="keywords" checked>
                </div>
                <div class="flex-grow-1">
                    <label class="fw-bold fs-5 mb-3 d-block clickable-label" for="type-keywords">I have SEO keywords and want help turning them into Search Prompts</label>
                    
                    <div id="keywords-input-container">
                        <div class="form-group mb-3">
                            <label class="small text-muted fw-semibold mb-2 d-flex align-items-center">
                                SEO keywords <i class="bi bi-question-circle ms-1 opacity-50 cursor-help" data-bs-toggle="tooltip" title="Enter keywords to generate search prompts. Paste your target SEO keywords one per line."></i>
                            </label>
                            <textarea id="seo-keywords" class="form-control border py-3 px-4 resize-none rounded-3" rows="5" placeholder="Paste in the top SEO keywords you're targeting"></textarea>
                            <div class="text-muted extra-small mt-2" id="keyword-count">Enter up to 20 keywords, one per line (0/20)</div>
                        </div>

                        <div class="row g-3 mt-1">
                            <div class="col-md-6">
                                <label class="small text-muted fw-semibold mb-2 d-flex align-items-center">Language <i class="bi bi-question-circle opacity-50 ms-1 cursor-help" data-bs-toggle="tooltip" title="Language for keyword discovery"></i></label>
                                <select id="language" class="form-select border rounded-3 py-2 px-3">
                                    <option value="English">English</option>
                                    <option value="Hindi">Hindi</option>
                                    <option value="Spanish">Spanish</option>
                                    <option value="French">French</option>
                                    <option value="German">German</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="small text-muted fw-semibold mb-2 d-flex align-items-center">Country <i class="bi bi-question-circle opacity-50 ms-1 cursor-help" data-bs-toggle="tooltip" title="Country for search data"></i></label>
                                <select id="country" class="form-select border rounded-3 py-2 px-3">
                                    <?php foreach ($countries as $code => $c): ?>
                                        <option value="<?php echo $code; ?>" <?php echo $code === 'IN' ? 'selected' : ''; ?>>
                                            <?php echo $c['name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Option: URL -->
        <div class="research-option-card mb-5 border rounded-4 bg-white p-4 transition-all-200 cursor-pointer" data-type="url" style="max-width: 800px;">
            <div class="d-flex align-items-start gap-3">
                <div class="custom-radio-wrapper mt-1">
                    <input class="form-check-input custom-radio" type="radio" name="research_type" id="type-url" value="url">
                </div>
                <div class="flex-grow-1">
                    <label class="fw-bold fs-5 mb-0 d-block clickable-label" for="type-url">I have a specific URL and want to discover which prompts are driving traffic</label>
                    
                    <div id="url-input-container" class="mt-4 d-none animate__animated animate__fadeIn">
                        <label class="small text-muted fw-semibold mb-2">Select Project</label>
                        <select id="research-project-select" class="form-select border rounded-3 py-2 px-3 mb-3">
                            <option value="">-- Choose a Project --</option>
                            <?php foreach ($projects as $proj): ?>
                                <option value="<?php echo htmlspecialchars($proj['website_url']); ?>" data-id="<?php echo $proj['id']; ?>">
                                    <?php echo htmlspecialchars($proj['business_name']); ?> (<?php echo htmlspecialchars($proj['website_url']); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <input type="hidden" id="target-url" value="">
                    </div>
                </div>
            </div>
        </div>

        <div class="mt-5 pt-3 d-flex gap-4 align-items-center">
            <a href="<?= BASE_URL ?>/" class="text-muted text-decoration-none fw-semibold">Cancel</a>
            <button type="button" class="btn btn-primary px-5 py-3 rounded-pill fw-bold" id="btn-next-step">Next step</button>
        </div>
    </div>

    <!-- Step 2: Generation Results -->
    <div id="step-2" class="research-step d-none animate__animated animate__fadeIn">
        <div class="mb-4 d-flex flex-column flex-sm-row justify-content-between align-items-sm-center gap-3">
            <div>
                <h2 class="h3 font-bold mb-1">AI Prompt Research</h2>
                <p class="text-muted small mb-0">We found the following high-potential search prompts</p>
            </div>
            <div class="d-flex gap-2">
                <button class="btn btn-outline-warning px-3 py-2 rounded-3 shadow-none d-flex align-items-center gap-2" id="btn-refresh-results">
                    <i class="bi bi-arrow-clockwise"></i> <span class="small fw-bold">Refresh</span>
                </button>
                <button class="btn btn-outline-secondary px-3 py-2 rounded-3 shadow-none d-flex align-items-center gap-2" id="btn-export-results">
                    <i class="bi bi-file-earmark-arrow-down"></i> <span class="small fw-bold">Export CSV</span>
                </button>
            </div>
        </div>

        <div class="card border-0 shadow-sm rounded-4 mb-4 overflow-hidden">
            <div class="card-body p-0">
                <div class="prompt-results-container">
                    <div class="table-responsive">
                        <table class="table no-datatable align-middle m-0" id="results-table">
                            <thead>
                                <tr class="text-muted small text-uppercase">
                                    <th style="width: 60px;" class="text-center">
                                        <div class="form-check d-flex justify-content-center">
                                            <input class="form-check-input custom-radio" type="checkbox" id="select-all-prompts" checked>
                                        </div>
                                    </th>
                                    <th class="ps-4">
                                        <div class="d-flex align-items-center gap-1 sortable-header" data-sort="text" data-bs-toggle="tooltip" title="AI-generated prompts based on your search intent keywords or URL.">
                                            <span>Your prompts</span>
                                            <span class="d-flex flex-column lh-1 opacity-50"><i class="bi bi-caret-up-fill sort-up"></i><i class="bi bi-caret-down-fill sort-down"></i></span>
                                        </div>
                                    </th>
                                    <th class="text-center p-0">
                                        <div class="d-flex flex-column align-items-center justify-content-center py-2 sortable-header" data-sort="intents.informational" data-bs-toggle="tooltip" title="Informational: Measures how much the user is seeking a guide, answer, or tutorial." style="min-width: 50px;">
                                            <span class="small">Info</span>
                                            <span class="d-flex gap-1 mt-1 opacity-40"><i class="bi bi-caret-up-fill sort-up"></i><i class="bi bi-caret-down-fill sort-down"></i></span>
                                        </div>
                                    </th>
                                    <th class="text-center p-0">
                                        <div class="d-flex flex-column align-items-center justify-content-center py-2 sortable-header" data-sort="intents.commercial" data-bs-toggle="tooltip" title="Commercial: Measures buying intent or vendor research (e.g., 'best', 'top')." style="min-width: 55px;">
                                            <span class="small">Comm</span>
                                            <span class="d-flex gap-1 mt-1 opacity-40"><i class="bi bi-caret-up-fill sort-up"></i><i class="bi bi-caret-down-fill sort-down"></i></span>
                                        </div>
                                    </th>
                                    <th class="text-center p-0">
                                        <div class="d-flex flex-column align-items-center justify-content-center py-2 sortable-header" data-sort="intents.navigational" data-bs-toggle="tooltip" title="Navigational: Measures how much the user is looking for a specific brand or official login page." style="min-width: 50px;">
                                            <span class="small">Nav</span>
                                            <span class="d-flex gap-1 mt-1 opacity-40"><i class="bi bi-caret-up-fill sort-up"></i><i class="bi bi-caret-down-fill sort-down"></i></span>
                                        </div>
                                    </th>
                                    <th class="text-center p-0">
                                        <div class="d-flex flex-column align-items-center justify-content-center py-2 sortable-header" data-sort="intents.comparison" data-bs-toggle="tooltip" title="Comparison: Measures product/service comparison intent (e.g., 'vs', 'alternatives')." style="min-width: 50px;">
                                            <span class="small">Comp</span>
                                            <span class="d-flex gap-1 mt-1 opacity-40"><i class="bi bi-caret-up-fill sort-up"></i><i class="bi bi-caret-down-fill sort-down"></i></span>
                                        </div>
                                    </th>
                                    <th class="text-center p-0">
                                        <div class="d-flex flex-column align-items-center justify-content-center py-2 sortable-header" data-sort="intents.competition" data-bs-toggle="tooltip" title="Difficulty: SEO proxy estimating ranking challenge based on keyword value and query length." style="min-width: 45px;">
                                            <span class="small">Diff</span>
                                            <span class="d-flex gap-1 mt-1 opacity-40"><i class="bi bi-caret-up-fill sort-up"></i><i class="bi bi-caret-down-fill sort-down"></i></span>
                                        </div>
                                    </th>
                                    <th class="text-center p-0">
                                        <div class="d-flex flex-column align-items-center justify-content-center py-2 sortable-header" data-sort="intents.branded" data-bs-toggle="tooltip" title="Branded: Measures if the query contains specific brand or company names." style="min-width: 50px;">
                                            <span class="small">Brand</span>
                                            <span class="d-flex gap-1 mt-1 opacity-40"><i class="bi bi-caret-up-fill sort-up"></i><i class="bi bi-caret-down-fill sort-down"></i></span>
                                        </div>
                                    </th>
                                    <th class="text-center pe-3">
                                        <div class="d-flex align-items-center justify-content-center gap-1 sortable-header" data-sort="volume" data-bs-toggle="tooltip" title="Monthly Volume: Estimated number of monthly searches for this specific prompt.">
                                            <span>Vol.</span>
                                            <span class="d-flex flex-column lh-1 opacity-50"><i class="bi bi-caret-up-fill sort-up"></i><i class="bi bi-caret-down-fill sort-down"></i></span>
                                        </div>
                                    </th>
                                </tr>
                            </thead>
                            <tbody id="prompts-list">
                                <!-- AJAX Content Here -->
                                <tr>
                                    <td colspan="9" class="text-center py-5">
                                        <div class="spinner-border text-primary" role="status"></div>
                                        <p class="mt-4 text-muted fw-semibold">Generating AI prompts based on your request...<br><small class="opacity-50">This may take up to 20 seconds</small></p>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="d-flex justify-content-between mt-5 pt-3">
            <button class="btn btn-link text-decoration-none text-muted fw-semibold" id="btn-back-to-1">Back to Setup</button>
            <button class="btn btn-primary px-5 py-3 rounded-pill fw-bold" id="btn-show-projects">Add prompts <i class="bi bi-arrow-right ms-2"></i></button>
        </div>
    </div>

    <!-- Step 3: Project Selection -->
    <div id="step-3" class="research-step d-none animate__animated animate__fadeIn">
        <div class="mb-5">
            <h2 class="h3 font-bold mb-1">Select Projects</h2>
            <p class="text-muted small">Choose which brands/reports should receive these prompts</p>
        </div>

        <div class="card border-0 shadow-sm rounded-4 mb-4 overflow-hidden">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table align-middle m-0" id="projects-table">
                        <thead class="bg-light">
                            <tr class="small text-muted text-uppercase">
                                <th style="width: 60px;" class="text-center"></th>
                                <th>Project Name</th>
                                <th>URL</th>
                                <th>Date Added</th>
                            </tr>
                        </thead>
                        <tbody id="projects-list">
                            <!-- AJAX Content Here -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="d-flex justify-content-between mt-5 pt-3">
            <button class="btn btn-link text-decoration-none text-muted fw-semibold" id="btn-back-to-2">Back to Prompts</button>
            <button class="btn btn-primary px-5 py-3 rounded-pill fw-bold" id="btn-finish">Add prompts & Finish</button>
        </div>
    </div>
</div>



<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    let selectedPlatform = 'ChatGPT';
    let selectedModel = '';
    let researchData = [];
    let selectedPrompts = [];
    let currentRequestParams = {};
    let currentSort = { field: null, order: 'asc' };
    const BASE_URL = $('meta[name="base-url"]').attr('content');

    // --- Core Navigation ---
    $(document).on('click', '#btn-next-step', function() {
        const type = $('input[name="research_type"]:checked').val();
        const platform = $('#selected-platform').val();
        const model = $('#selected-model-version').val();
        const country = $('#country').val();
        const language = $('#language').val();

        let inputVal = '';
        if (type === 'keywords') {
            inputVal = $('#seo-keywords').val();
            if (!inputVal || !inputVal.trim()) { alert('Please enter some keywords.'); return; }
        } else {
            inputVal = $('#target-url').val();
            if (!inputVal || !inputVal.trim()) { alert('Please select a project to analyze.'); return; }
        }

        switchStep(2);
        currentRequestParams = { type, inputVal, platform, model, country, language };
        generatePrompts(type, inputVal, platform, model, country, language);
    });

    $(document).on('click', '#btn-refresh-results', function() {
        const btn = $(this);
        btn.find('i').addClass('fa-spin');
        
        generatePrompts(
            currentRequestParams.type, 
            currentRequestParams.inputVal, 
            currentRequestParams.platform, 
            currentRequestParams.model, 
            currentRequestParams.country, 
            currentRequestParams.language,
            () => btn.find('i').removeClass('fa-spin')
        );
    });

    $(document).on('click', '#btn-back-to-1', () => switchStep(1));
    $(document).on('click', '#btn-back-to-2', () => switchStep(2));

    function switchStep(step) {
        $('.research-step').addClass('d-none').removeClass('active');
        $(`#step-${step}`).removeClass('d-none').addClass('active');
        window.scrollTo(0, 0);
    }

    // --- Step 1 Navigation & UI ---
    $(document).on('click', '.research-option-card', function() {
        const type = $(this).data('type');
        $('.research-option-card').removeClass('active');
        $(this).addClass('active');
        $(this).find('input[type="radio"]').prop('checked', true);
        
        if (type === 'keywords') {
            $('#keywords-input-container').removeClass('d-none');
            $('#url-input-container').addClass('d-none');
        } else {
            $('#keywords-input-container').addClass('d-none');
            $('#url-input-container').removeClass('d-none');
            
            // Try to auto-select from localStorage if available
            const activeProj = localStorage.getItem('savit_project');
            if (activeProj) {
                try {
                    const projData = JSON.parse(activeProj);
                    if (projData && projData.domain) {
                        $('#research-project-select').val(projData.domain).trigger('change');
                    }
                } catch(e) {}
            }
        }
    });

    $(document).on('change', '#research-project-select', function() {
        $('#target-url').val($(this).val());
    });

    $('#seo-keywords').on('input', function() {
        const text = $(this).val();
        const lines = text.split('\n').filter(l => l.trim() !== '');
        $('#keyword-count').text(`Enter up to 20 keywords, one per line (${lines.length}/20)`);
    });

    // Model selection
    $(document).on('click', '.platform-select', function(e) {
        e.preventDefault();
        const platform = $(this).data('platform');
        
        selectedPlatform = platform;
        $('#selected-model-text').text(platform);
        $('#selected-platform').val(platform);
        
        selectedModel = '';
        $('#selected-model-version').val('');
        
        loadModels(platform);
    });

    const defaultModels = {
        'ChatGPT': 'gpt-4o',
        'Claude': 'claude-3-5-sonnet-20240620',
        'Gemini': 'gemini-1.5-pro',
        'Perplexity': 'sonar-large-online',
        'Google AI Mode': 'Search Generative Experience (SGE)'
    };
    
    loadModels(selectedPlatform);

    function loadModels(platform) {
        selectedModel = defaultModels[platform] || '';
        $('#selected-model-version').val(selectedModel);

        $.ajax({
            url: BASE_URL + '/api/research/get-models',
            method: 'GET',
            data: { platform: platform },
            success: function(response) {
                if (response.success && response.models.length > 0) {
                    // Use the first model (which is sorted by is_latest DESC)
                    selectedModel = response.models[0].name;
                    const label = response.models[0].label;
                    $('#selected-model-version').val(selectedModel);
                    $('#selected-model-text').html(`${platform} <span class="ms-1 text-muted opacity-50 extra-small">(${label})</span>`);
                } else {
                    $('#selected-model-text').html(`${platform} <span class="ms-1 text-muted opacity-50 extra-small">(${selectedModel})</span>`);
                }
            },
            error: function() {
                $('#selected-model-text').html(`${platform} <span class="ms-1 text-muted opacity-50 extra-small">(${selectedModel})</span>`);
            }
        });
    }

    function generatePrompts(type, value, platform, model, country, language, callback = null) {
        $('#prompts-list').html(`
            <tr>
                <td colspan="9" class="text-center py-5">
                    <div class="spinner-border text-primary" role="status"></div>
                    <p class="mt-3 text-muted">Analyzing ${type} with DataforSEO & AI...<br><small>Calculating detailed intent scores for all results...</small></p>
                </td>
            </tr>
        `);

        $.ajax({
            url: BASE_URL + '/api/research/generate-prompts',
            method: 'POST',
            data: {
                type: type,
                value: value,
                platform: platform,
                model: model,
                country: country,
                language: language
            },
            success: function(response) {
                if (response.success) {
                    researchData = response.prompts;
                    renderPrompts(response.prompts);
                } else {
                    $('#prompts-list').html(`<tr><td colspan="9" class="text-center text-danger py-5">${response.error || 'Failed to generate prompts'}</td></tr>`);
                }
                if (callback) callback();
            },
            error: function() {
                $('#prompts-list').html(`<tr><td colspan="9" class="text-center text-danger py-5">Connection error. Please try again.</td></tr>`);
                if (callback) callback();
            }
        });
    }

    function renderPrompts(prompts) {
        let html = '';
        prompts.forEach((p, index) => {
            const i = p.intents;
            
            html += `
                <tr>
                    <td>
                        <div class="form-check">
                            <input class="form-check-input prompt-checkbox" type="checkbox" value="${index}" checked>
                        </div>
                    </td>
                    <td class="fw-medium">${p.text}</td>
                    <td class="text-center intent-col"><span class="badge score-pill score-${i.informational}">${i.informational}</span></td>
                    <td class="text-center intent-col"><span class="badge score-pill score-${i.commercial}">${i.commercial}</span></td>
                    <td class="text-center intent-col"><span class="badge score-pill score-${i.navigational}">${i.navigational}</span></td>
                    <td class="text-center intent-col"><span class="badge score-pill score-${i.comparison}">${i.comparison}</span></td>
                    <td class="text-center intent-col"><span class="badge score-pill score-${i.competition}">${i.competition}</span></td>
                    <td class="text-center intent-col"><span class="badge score-pill score-${i.branded}">${i.branded}</span></td>
                    <td class="text-center fw-bold text-dark">${p.volume.toLocaleString()}</td>
                </tr>
            `;
        });
        $('#prompts-list').html(html);
    }

    // --- Sorting Logic ---
    $(document).on('click', '.sortable-header', function() {
        const field = $(this).data('sort');
        const order = (currentSort.field === field && currentSort.order === 'asc') ? 'desc' : 'asc';
        currentSort = { field, order };
        
        $('.sortable-header').removeClass('sorting-asc sorting-desc');
        $(this).addClass(order === 'asc' ? 'sorting-asc' : 'sorting-desc');
        
        sortData(field, order);
        renderPrompts(researchData);
    });

    function sortData(field, order) {
        researchData.sort((a, b) => {
            let valA, valB;
            
            if (field.includes('.')) {
                const parts = field.split('.');
                valA = a[parts[0]][parts[1]];
                valB = b[parts[0]][parts[1]];
            } else {
                valA = a[field];
                valB = b[field];
            }

            if (typeof valA === 'string') {
                return order === 'asc' ? valA.localeCompare(valB) : valB.localeCompare(valA);
            } else {
                return order === 'asc' ? valA - valB : valB - valA;
            }
        });
    }

    // --- Step 2 Interactions ---
    $(document).on('click', '#btn-export-results', function() {
        if (researchData.length === 0) return;
        
        let csvContent = "data:text/csv;charset=utf-8,";
        csvContent += "Prompt,Volume,Informational,Commercial,Navigational,Comparison,Competition,Branded\n";
        
        researchData.forEach(p => {
            const i = p.intents;
            csvContent += `"${p.text}",${p.volume},${i.informational},${i.commercial},${i.navigational},${i.comparison},${i.competition},${i.branded}\n`;
        });
        
        const encodedUri = encodeURI(csvContent);
        const link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "ai_prompt_research.csv");
        document.body.appendChild(link);
        link.click();
    });

    $(document).on('change', '#select-all-prompts', function() {
        $('.prompt-checkbox').prop('checked', $(this).is(':checked'));
    });

    // --- Move to Step 3 ---
    $(document).on('click', '#btn-show-projects', function() {
        selectedPrompts = [];
        $('.prompt-checkbox:checked').each(function() {
            selectedPrompts.push(researchData[$(this).val()]);
        });

        if (selectedPrompts.length === 0) {
            alert('Please select at least one prompt.');
            return;
        }

        switchStep(3);
        loadProjects();
    });

    function loadProjects() {
        $('#projects-list').html('<tr><td colspan="4" class="text-center py-5"><div class="spinner-border text-primary"></div></td></tr>');
        
        $.ajax({
            url: BASE_URL + '/api/research/fetch-projects', 
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    let html = '';
                    response.projects.forEach(p => {
                        html += `
                            <tr>
                                <td class="text-center"><div class="form-check d-flex justify-content-center"><input class="form-check-input custom-radio project-checkbox" type="checkbox" value="${p.id}"></div></td>
                                <td class="fw-bold">${p.business_name}</td>
                                <td><span class="text-muted small">${p.website_url}</span></td>
                                <td class="text-muted small">${p.created_at}</td>
                            </tr>
                        `;
                    });
                    $('#projects-list').html(html);
                }
            }
        });
    }

    // --- Finish ---
    $(document).on('click', '#btn-finish', function() {
        const selectedProjectIds = [];
        $('.project-checkbox:checked').each(function() {
            selectedProjectIds.push($(this).val());
        });

        if (selectedProjectIds.length === 0) {
            alert('Please select at least one project.');
            return;
        }

        const btn = $(this);
        btn.prop('disabled', true).html('<i class="bi bi-hourglass-split me-1"></i> Saving...');

        $.ajax({
            url: BASE_URL + '/api/research/add-prompts',
            method: 'POST',
            data: {
                prompts: JSON.stringify(selectedPrompts),
                project_ids: JSON.stringify(selectedProjectIds)
            },
            success: function(response) {
                if (response.success) {
                    alert('Prompts added successfully!');
                    window.location.href = BASE_URL + '/projects';
                } else {
                    alert('Error: ' + response.error);
                    btn.prop('disabled', false).text('Add prompts & Finish');
                }
            },
            error: function() {
                alert('Connection error.');
                btn.prop('disabled', false).text('Add prompts & Finish');
            }
        });
    });
});
</script>
<?php require __DIR__ . '/../layout/footer.php'; ?>
