<?php
// Savit Project Research Prompts Management
// Adapted from ai-tool/prompts.php

use CAE\Lib\Database;

$projectId = (int)($id ?? 0);
if (!$projectId) {
    echo "Invalid Project ID";
    exit();
}

$db = Database::getInstance();
$project = $db->fetch("SELECT * FROM projects WHERE id = ?", [$projectId]);

if (!$project) {
    echo "Project not found";
    exit();
}

$pageTitle = $project['business_name'] . ' — AI Research Prompts';
require __DIR__ . '/../layout/header.php';
?>

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-4 gap-3">
    <div>
        <h2 class="h4 mb-1 font-semibold">AI Research Prompts</h2>
        <p class="text-muted small mb-0">See which AI prompts mention your brand, and which mention your competitors.</p>
    </div>
    <div class="d-flex flex-wrap gap-2 justify-content-start justify-content-md-end">
        <button class="btn btn-outline-secondary btn-sm d-flex align-items-center gap-2" data-bs-toggle="modal" data-bs-target="#addPromptModal">
            <i class="bi bi-plus-lg"></i>
            Add Prompt
        </button>
        <button id="export-csv-btn" class="btn btn-outline-secondary btn-sm d-flex align-items-center gap-2" title="Export summary of prompts">
            <i class="bi bi-file-earmark-spreadsheet"></i>
            Export Summary
        </button>
    </div>
</div>

<div class="d-flex flex-wrap align-items-center justify-content-between mb-4 gap-3">
    <!-- Left: Filters -->
    <div class="d-flex gap-2 flex-wrap align-items-center filters-group">
        <!-- Country Dropdown -->
        <div class="dropdown">
            <button class="btn btn-white btn-sm border dropdown-toggle d-flex align-items-center gap-2 py-1" type="button" id="countryDropdown" data-bs-toggle="dropdown">
                <img id="selected-flag" src="https://flagcdn.com/in.svg" width="16">
                <span id="selected-country-text">India</span>
            </button>
            <ul class="dropdown-menu shadow-sm border-0">
                <li><a class="dropdown-item country-select d-flex align-items-center gap-2" href="#" data-code="IN" data-name="India" data-flag="in"><img src="https://flagcdn.com/in.svg" width="16"> India</a></li>
                <li><a class="dropdown-item country-select d-flex align-items-center gap-2" href="#" data-code="US" data-name="United States" data-flag="us"><img src="https://flagcdn.com/us.svg" width="16"> United States</a></li>
                <li><a class="dropdown-item country-select d-flex align-items-center gap-2" href="#" data-code="GB" data-name="United Kingdom" data-flag="gb"><img src="https://flagcdn.com/gb.svg" width="16"> United Kingdom</a></li>
                <li><a class="dropdown-item country-select d-flex align-items-center gap-2" href="#" data-code="CA" data-name="Canada" data-flag="ca"><img src="https://flagcdn.com/ca.svg" width="16"> Canada</a></li>
                <li><a class="dropdown-item country-select d-flex align-items-center gap-2" href="#" data-code="AU" data-name="Australia" data-flag="au"><img src="https://flagcdn.com/au.svg" width="16"> Australia</a></li>
            </ul>
        </div>

        <!-- Platform Dropdown -->
        <div class="dropdown">
            <button class="btn btn-white btn-sm border dropdown-toggle d-flex align-items-center gap-2 py-1" type="button" id="modelDropdown" data-bs-toggle="dropdown">
                <span id="selected-model-text">ChatGPT</span>
            </button>
            <ul class="dropdown-menu shadow-sm border-0">
                <li><a class="dropdown-item platform-select" href="#" data-platform="ChatGPT">ChatGPT</a></li>
                <li><a class="dropdown-item platform-select" href="#" data-platform="Claude">Claude</a></li>
                <li><a class="dropdown-item platform-select" href="#" data-platform="Gemini">Gemini</a></li>
                <li><a class="dropdown-item platform-select" href="#" data-platform="Perplexity">Perplexity</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item platform-select" href="#" data-platform="Google AI Mode">Google AI Mode</a></li>
            </ul>
        </div>
    </div>

    <!-- Right: Actions & Search -->
    <div class="d-flex gap-2 flex-wrap align-items-center ms-md-auto search-actions-group">
        <div class="input-group input-group-sm search-input-group" style="width: 250px;">
            <input type="text" id="prompt-search" class="form-control" placeholder="Search prompts...">
            <span class="input-group-text bg-white text-muted"><i class="bi bi-search"></i></span>
        </div>

        <div class="d-flex gap-2 action-btns">
            <button class="btn btn-primary btn-sm d-flex align-items-center gap-2 px-3 shadow-none" id="run-selected-btn">
                <i class="bi bi-play-fill"></i> Run Selected
            </button>
            <button class="btn btn-outline-danger btn-sm d-flex align-items-center gap-2 px-3 shadow-none" id="delete-selected-btn">
                <i class="bi bi-trash"></i> Delete
            </button>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0 overflow-hidden rounded-4">
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0 custom-prompts-table">
            <thead class="bg-light">
                <tr class="small text-muted text-uppercase">
                    <th class="ps-4 py-3" style="width: 40px;">
                        <input class="form-check-input" type="checkbox" id="select-all-prompts">
                    </th>
                    <th class="py-3" style="width: 50px;">Status</th>
                    <th class="py-3" style="width: 35%;">Prompt</th>
                    <th class="py-3 text-center">Brand Mentions</th>
                    <th class="py-3 text-center">Domain Citations</th>
                    <th class="py-3 text-center">Total Citations</th>
                    <th class="py-3 text-center">Visibility</th>
                    <th class="pe-4 py-3 text-end">Competitors</th>
                </tr>
            </thead>
            <tbody id="prompts-table-body">
                <tr>
                    <td colspan="8" class="text-center py-5 text-muted">
                        <div class="spinner-border spinner-border-sm text-primary me-2"></div> Loading prompts...
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <div class="card-footer bg-white border-top py-3 d-flex justify-content-between align-items-center">
        <div class="small text-muted" id="results-count">Viewing 0 results</div>
        <nav aria-label="Page navigation">
            <ul class="pagination pagination-sm mb-0" id="pagination-list"></ul>
        </nav>
    </div>
</div>

<!-- Add Prompt Modal -->
<div class="modal fade" id="addPromptModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header border-bottom-0">
                <h5 class="modal-title fw-bold">Add New AI Prompt</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="add-prompt-form">
                <input type="hidden" name="brand_id" value="<?= $projectId ?>">
                <div class="modal-body pb-0">
                    <div class="mb-3">
                        <label class="form-label small text-muted text-uppercase fw-bold">Prompt Text</label>
                        <textarea class="form-control border-2" name="prompt_text" rows="4" placeholder="e.g., What are the best website design services in India?" required></textarea>
                    </div>
                </div>
                <div class="modal-footer border-top-0 pt-0">
                    <button type="button" class="btn btn-light btn-sm" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary btn-sm px-4 shadow-none" id="save-prompt-btn">Save Prompt</button>
                </div>
            </form>
        </div>
    </div>
</div>



<script>
$(document).ready(function() {
    const brandId = '<?= $projectId ?>';
    const BASE_URL = $('meta[name="base-url"]').attr('content');
    let selectedPlatform = 'ChatGPT';
    let selectedModel = '';
    let selectedCountry = 'IN';
    let currentPage = 1;
    let limit = 10;

    loadModels(selectedPlatform);

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

    function loadModels(platform) {
        $.ajax({
            url: BASE_URL + '/api/research/get-models',
            data: { platform: platform },
            success: function(res) {
                if (res.success && res.models.length > 0) {
                    selectedModel = res.models[0].name;
                    $('#selected-model-text').html(`${platform} <span class="ms-1 text-muted opacity-50 small">(${selectedModel})</span>`);
                }
            }
        });
    }

    // Country selection
    $(document).on('click', '.country-select', function(e) {
        e.preventDefault();
        selectedCountry = $(this).data('code');
        $('#selected-flag').attr('src', `https://flagcdn.com/${$(this).data('flag')}.svg`);
        $('#selected-country-text').text($(this).data('name'));
    });

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

    // Run selected
    $('#run-selected-btn').on('click', function() {
        const ids = [];
        $('.prompt-checkbox:checked').each(function() { ids.push($(this).val()); });
        if (ids.length === 0) { alert('Select prompts first'); return; }
        runBatch(ids);
    });

    async function runBatch(ids) {
        $('#run-selected-btn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Running...');
        for (const id of ids) {
            await runSinglePrompt(id);
        }
        $('#run-selected-btn').prop('disabled', false).html('<i class="bi bi-play-fill"></i> Run Selected');
        fetchPrompts();
    }

    function runSinglePrompt(id) {
        const statusEl = $(`.status-icon[data-id="${id}"]`);
        statusEl.html('<div class="spinner-border spinner-border-sm text-primary"></div>');
        return new Promise(resolve => {
            $.ajax({
                url: BASE_URL + '/api/research/run-prompt',
                method: 'POST',
                data: { prompt_id: id, platform: selectedPlatform, model_version: selectedModel, country_code: selectedCountry, web_search_supported: true },
                success: function(res) {
                    statusEl.html(res.success ? '<i class="bi bi-check-circle-fill text-success"></i>' : '<i class="bi bi-x-circle-fill text-danger"></i>');
                    resolve();
                },
                error: function() { statusEl.html('<i class="bi bi-exclamation-circle-fill text-warning"></i>'); resolve(); }
            });
        });
    }

    // Fetch and Render
    function fetchPrompts() {
        $.ajax({
            url: BASE_URL + '/api/research/fetch-prompts',
            data: { brand_id: brandId, search: $('#prompt-search').val(), page: currentPage, limit: limit },
            success: function(res) {
                if (!res.success) return;
                let html = '';
                res.data.forEach(p => {
                    const visClass = p.visibility_score > 70 ? 'score-high' : (p.visibility_score > 30 ? 'score-mid' : 'score-low');
                    html += `
                        <tr>
                            <td class="ps-4"><input class="form-check-input prompt-checkbox" type="checkbox" value="${p.id}"></td>
                            <td><div class="status-icon" data-id="${p.id}"><i class="bi bi-circle text-light"></i></div></td>
                            <td><a href="${BASE_URL}/research/details?id=${p.id}" class="text-primary fw-medium text-decoration-none">${p.prompt_text}</a></td>
                            <td class="text-center">${p.brand_mentions || 0}</td>
                            <td class="text-center">${p.domain_citations || 0}</td>
                            <td class="text-center">${p.total_citations || 0}</td>
                            <td class="text-center"><span class="score-pill ${visClass}">${p.visibility_score || 0}%</span></td>
                            <td class="pe-4 text-end text-muted small italic">${p.competitors_mentions || 'None'}</td>
                        </tr>
                    `;
                });
                $('#prompts-table-body').html(html || '<tr><td colspan="8" class="text-center py-4 text-muted">No prompts found</td></tr>');
                $('#results-count').text(`Viewing ${res.data.length} of ${res.total} results`);
                renderPagination(res.total_pages);
            }
        });
    }

    function renderPagination(total) {
        let h = '';
        for (let i = 1; i <= total; i++) {
            h += `<li class="page-item ${i === currentPage ? 'active' : ''}"><a class="page-link" href="#" data-page="${i}">${i}</a></li>`;
        }
        $('#pagination-list').html(h);
    }

    $(document).on('click', '.page-link', function(e) {
        e.preventDefault();
        currentPage = $(this).data('page');
        fetchPrompts();
    });

    let searchTimer;
    $('#prompt-search').on('input', function() {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => { currentPage = 1; fetchPrompts(); }, 300);
    });

    // Add Prompt
    $('#add-prompt-form').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: BASE_URL + '/api/research/add-single-prompt',
            method: 'POST',
            data: $(this).serialize(),
            success: function(res) {
                if (res.success) {
                    $('#addPromptModal').modal('hide');
                    $('#add-prompt-form')[0].reset();
                    fetchPrompts();
                } else { alert(res.error); }
            }
        });
    });

    // Delete
    $('#delete-selected-btn').on('click', function() {
        const ids = [];
        $('.prompt-checkbox:checked').each(function() { ids.push($(this).val()); });
        if (ids.length === 0 || !confirm('Delete selected?')) return;
        $.ajax({
            url: BASE_URL + '/api/research/delete-prompt',
            method: 'POST',
            data: { prompt_ids: ids },
            success: function(res) { if (res.success) fetchPrompts(); }
        });
    });

    fetchPrompts();
});
</script>
<?php require __DIR__ . '/../layout/footer.php'; ?>
