<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();

$user = getCurrentUser();
if (!$user) {
    redirect('login.php');
}

if (!hasRole('student')) {
    redirect('dashboard.php');
}

$db = Database::getInstance();
$hasAccess = false;

try {
    $row = $db->get(
        "SELECT id FROM payments WHERE user_id = ? AND payment_type = ? AND payment_status = ? LIMIT 1",
        [$user['id'], 'ai_premium', 'completed']
    );
    if ($row && isset($row['id'])) {
        $hasAccess = true;
    }
} catch (Exception $e) {
    $hasAccess = false;
}

$pageTitle = 'AI Cybersecurity Copilot';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h4 mb-0">GCOS Hybrid Cyber Copilot <span class="badge bg-primary">VPF L1,000,000</span></h1>
        <p class="text-muted mb-0">Powered by Visionary Prompt Framework (VPF) Planetary Version - 360° Cybersecurity Learning OS</p>
    </div>
</div>

<div class="row g-4">
    <div class="col-lg-8">
        <div class="card h-100">
            <div class="card-body">
                <?php if ($hasAccess): ?>
                    <div class="alert alert-info mb-4">
                        <strong>🚀 GCOS Hybrid Cyber Copilot</strong> - Powered by VPF Execution Level 1,000,000
                        <p class="mb-0 mt-2 small">This copilot uses the Visionary Prompt Framework (VPF) Planetary architecture with Chambers, Lenses, Bolts, and Cognitive Validation Matrix for defensive-only cybersecurity learning.</p>
                    </div>
                    <p class="mb-3">
                        <strong>Learning OS Mode:</strong> Progressive cybersecurity teaching across 10 domains with scenario-based assessment.
                    </p>
                    <div class="mb-3">
                        <h6 class="fw-semibold mb-2">10 Cybersecurity Domains:</h6>
                        <div class="row g-2 small">
                            <div class="col-md-6">
                                <span class="badge bg-secondary">1. Physical & Environmental</span>
                                <span class="badge bg-secondary">2. Identity & Access</span>
                                <span class="badge bg-secondary">3. Endpoint, IoT & OT</span>
                                <span class="badge bg-secondary">4. Network & Connectivity</span>
                                <span class="badge bg-secondary">5. Application & Platform</span>
                            </div>
                            <div class="col-md-6">
                                <span class="badge bg-secondary">6. Data Protection</span>
                                <span class="badge bg-secondary">7. Monitoring & SOC</span>
                                <span class="badge bg-secondary">8. Incident Response</span>
                                <span class="badge bg-secondary">9. Governance & Risk</span>
                                <span class="badge bg-secondary">10. Supply Chain Risk</span>
                            </div>
                        </div>
                    </div>
                    <ul class="list-unstyled mb-3">
                        <li class="mb-2">✓ <strong>Defensive Only:</strong> No exploitation or offensive techniques taught</li>
                        <li class="mb-2">✓ <strong>Evidence-Based:</strong> Aligned with NIST CSF, ISO 27001, NICE Framework</li>
                        <li class="mb-2">✓ <strong>Progressive Learning:</strong> Adapts to your skill level (Beginner → Advanced)</li>
                        <li class="mb-2">✓ <strong>Scenario Practice:</strong> Real-world cybersecurity scenarios and assessments</li>
                    </ul>
                    <div id="gcosWidget" class="border rounded shadow-sm" style="height: 580px; display: flex; flex-direction: column;">
                        <div class="bg-primary text-white p-3 rounded-top">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-0">GCOS Learning OS</h6>
                                    <small class="opacity-75">VPF Planetary L1,000,000</small>
                                </div>
                                <span id="gcosStatus" class="badge bg-success">Ready</span>
                            </div>
                        </div>
                        <div id="gcosChatMessages" class="p-3" style="flex: 1; overflow-y: auto; background-color: #f8fafc;"></div>
                        <div class="border-top p-3 bg-white">
                            <div id="gcosError" class="text-danger small mb-2" style="display:none;"></div>
                            <div id="gcosMetadata" class="text-muted small mb-2" style="display:none;">
                                <strong>VPF Runtime:</strong> <span id="gcosMode"></span> | <strong>CVM:</strong> <span id="gcosCVM"></span> | <strong>Confidence:</strong> <span id="gcosConfidence"></span>
                            </div>
                            <textarea id="gcosChatInput" class="form-control form-control-sm mb-2" rows="2" placeholder="Ask about cybersecurity concepts, scenarios, or practice questions..."></textarea>
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">Defensive learning only</small>
                                <button id="gcosChatSendBtn" type="button" class="btn btn-primary btn-sm">
                                    <i class="bi bi-send"></i> Ask GCOS
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="mt-3">
                        <p class="text-muted small mb-1">
                            <strong>VPF Architecture:</strong> Chambers (Intake, Learning, Audit) • Lenses (Learning, Evidence) • Bolts (Learning Integrity, Audit, Defensive Only)
                        </p>
                        <p class="text-muted small mb-0">
                            The copilot enforces defensive-only learning. Do not share confidential data. Always validate recommendations against official course material and industry standards.
                        </p>
                    </div>
                <?php else: ?>
                    <div class="alert alert-warning" role="alert">
                        <strong>Access locked.</strong> This AI premium service is available only to students who have completed payment for the AI cybersecurity copilot.
                    </div>
                    <p class="mb-3">
                        Once your payment is processed and linked to your SmartThink account, this space will unlock automatically and you will see a button to launch the copilot.
                    </p>
                    <p class="text-muted small mb-0">
                        If you believe you already have access, contact support and share your payment reference so we can enable this feature for your profile.
                    </p>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card mb-4">
            <div class="card-body">
                <?php if ($hasAccess): ?>
                    <h6 class="fw-semibold mb-3">VPF Runtime Status</h6>
                    <div class="mb-3">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="small">Access Status:</span>
                            <span class="badge bg-success">Active</span>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span class="small">Execution Level:</span>
                            <span class="badge bg-primary">1,000,000</span>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span class="small">Mode:</span>
                            <span class="badge bg-info">Learning OS</span>
                        </div>
                    </div>
                    <hr>
                    <h6 class="fw-semibold mb-2">Safety Guardrails</h6>
                    <p class="text-muted small mb-2">
                        ✓ Defensive-only teaching<br>
                        ✓ No exploitation techniques<br>
                        ✓ Evidence-based responses<br>
                        ✓ Standards-aligned (NIST, ISO)
                    </p>
                <?php else: ?>
                    <h6 class="fw-semibold mb-2">How to get access</h6>
                    <p class="text-muted small mb-2">
                        Contact your program coordinator or SmartThink support to purchase access to the AI cybersecurity copilot.
                    </p>
                    <p class="text-muted small mb-2">
                        After payment, access will be granted automatically based on your payment record.
                    </p>
                    <div class="mt-3">
                        <button id="aiPaystackBtn" type="button" class="btn btn-sm btn-primary me-2">
                            Pay with Paystack
                        </button>
                        <button id="aiSquareBtn" type="button" class="btn btn-sm btn-outline-secondary">
                            Pay with Square
                        </button>
                        <div id="aiPaymentError" class="text-danger small mt-2" style="display:none;"></div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php if ($hasAccess): ?>
<script>
    (function () {
        var APP_URL = <?php echo json_encode(APP_URL); ?>;
        var gcosEndpoint = APP_URL + '/website/api/ai_premium/gcos_chat.php';

        function parseJsonSafe(raw) {
            if (!raw) return null;
            var cleaned = raw.replace(/^\uFEFF+/g, '').trim();
            return cleaned ? JSON.parse(cleaned) : null;
        }

        function setGcosError(message) {
            var el = document.getElementById('gcosError');
            if (!el) return;
            if (!message) {
                el.style.display = 'none';
                el.innerHTML = '';
            } else {
                el.style.display = 'block';
                el.innerHTML = message;
            }
        }

        function setGcosStatus(status, variant) {
            var el = document.getElementById('gcosStatus');
            if (!el) return;
            el.textContent = status;
            el.className = 'badge bg-' + (variant || 'success');
        }

        function updateGcosMetadata(data) {
            if (!data.reasoning_architecture) return;
            
            var metadataEl = document.getElementById('gcosMetadata');
            var modeEl = document.getElementById('gcosMode');
            var cvmEl = document.getElementById('gcosCVM');
            var confEl = document.getElementById('gcosConfidence');
            
            if (metadataEl && modeEl && cvmEl && confEl) {
                modeEl.textContent = data.reasoning_architecture.mode || 'learning';
                cvmEl.textContent = data.reasoning_architecture.cvm_status || 'passed';
                confEl.textContent = data.confidence || 'Medium';
                metadataEl.style.display = 'block';
            }
        }

        function appendGcosMessage(role, content, metadata) {
            var container = document.getElementById('gcosChatMessages');
            if (!container) return;
            
            var wrapper = document.createElement('div');
            wrapper.className = 'mb-3';

            var bubble = document.createElement('div');
            bubble.className = 'p-3 rounded-3';

            if (role === 'user') {
                bubble.className += ' bg-primary text-white ms-auto';
                bubble.style.maxWidth = '85%';
                bubble.innerHTML = '<div class="small mb-1"><strong>You</strong></div>' + 
                    '<div>' + escapeHtml(content) + '</div>';
            } else {
                bubble.className += ' bg-white border me-auto';
                bubble.style.maxWidth = '90%';
                
                var html = '<div class="d-flex justify-content-between align-items-center mb-2">' +
                    '<strong class="text-primary">GCOS Learning OS</strong>';
                
                if (metadata && metadata.reasoning_architecture) {
                    var cvmStatus = metadata.reasoning_architecture.cvm_status || 'passed';
                    var cvmClass = cvmStatus === 'passed' ? 'success' : (cvmStatus === 'blocked' ? 'danger' : 'warning');
                    html += '<span class="badge bg-' + cvmClass + ' small">CVM: ' + cvmStatus + '</span>';
                }
                
                html += '</div><div>' + formatMessage(content) + '</div>';
                
                if (metadata && metadata.reasoning_architecture) {
                    html += '<div class="mt-2 pt-2 border-top small text-muted">' +
                        '<strong>VPF:</strong> ' + (metadata.reasoning_architecture.chambers_used || []).join(', ') +
                        '</div>';
                }
                
                bubble.innerHTML = html;
            }

            wrapper.appendChild(bubble);
            container.appendChild(wrapper);
            container.scrollTop = container.scrollHeight;
        }

        function escapeHtml(text) {
            var div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function formatMessage(text) {
            text = escapeHtml(text);
            text = text.replace(/\n/g, '<br>');
            text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
            return text;
        }

        document.addEventListener('DOMContentLoaded', function () {
            var input = document.getElementById('gcosChatInput');
            var sendBtn = document.getElementById('gcosChatSendBtn');
            var messagesEl = document.getElementById('gcosChatMessages');
            if (!input || !sendBtn || !messagesEl) return;

            var history = [];

            appendGcosMessage('assistant', 
                'Welcome to GCOS Hybrid Cyber Copilot powered by VPF Execution Level 1,000,000.\n\n' +
                'I\'m your Learning OS for 360° cybersecurity education across 10 domains. ' +
                'Ask me about concepts, scenarios, or practice questions. I teach defensive cybersecurity only.\n\n' +
                'What would you like to learn today?'
            );

            async function sendMessage() {
                var text = input.value.trim();
                if (!text) return;

                setGcosError('');
                appendGcosMessage('user', text);
                history.push({ role: 'user', content: text });
                input.value = '';

                input.disabled = true;
                sendBtn.disabled = true;
                setGcosStatus('Thinking...', 'warning');

                try {
                    var res = await fetch(gcosEndpoint, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ 
                            messages: history,
                            mode: 'learn'
                        })
                    });

                    var raw = await res.text();
                    var data = null;
                    try {
                        data = parseJsonSafe(raw);
                    } catch (e) {
                        setGcosError('GCOS responded in an unexpected format. Raw: ' + raw.substring(0, 200));
                        setGcosStatus('Error', 'danger');
                        return;
                    }

                    if (!data || !data.success || !data.reply) {
                        var msg = data && data.message ? data.message : 'GCOS could not answer right now.';
                        
                        // Handle quota errors specifically
                        if (data.error_type === 'quota_exceeded') {
                            msg = '<strong>OpenAI API Quota Exceeded</strong><br><br>' +
                                  'Your OpenAI account has reached its usage limit. To continue using the GCOS copilot:<br><br>' +
                                  '1. Log in to <a href="https://platform.openai.com/account/billing" target="_blank">OpenAI Billing</a><br>' +
                                  '2. Check your usage and billing details<br>' +
                                  '3. Add payment method or upgrade your plan<br>' +
                                  '4. Wait a few minutes for quota to refresh after payment<br><br>' +
                                  'Contact your administrator if you believe this is an error.';
                        }
                        
                        if (data && data.raw) {
                            try {
                                var rawStr = typeof data.raw === 'string' ? data.raw : JSON.stringify(data.raw);
                                if (data.error_type !== 'quota_exceeded') {
                                    msg += ' Raw: ' + rawStr.substring(0, 200);
                                }
                            } catch (e2) {
                                // ignore
                            }
                        }
                        setGcosError(msg);
                        setGcosStatus('Error', 'danger');
                        return;
                    }

                    history.push({ role: 'assistant', content: data.reply });
                    appendGcosMessage('assistant', data.reply, data);
                    updateGcosMetadata(data);
                    setGcosStatus('Ready', 'success');
                } catch (err) {
                    setGcosError('Network error while connecting to GCOS.');
                    setGcosStatus('Error', 'danger');
                } finally {
                    input.disabled = false;
                    sendBtn.disabled = false;
                    input.focus();
                }
            }

            sendBtn.addEventListener('click', sendMessage);
            input.addEventListener('keydown', function (e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
        });
    })();
</script>
<?php endif; ?>

<?php if (!$hasAccess): ?>
<script>
    const AI_USER_ID = <?php echo (int)$user['id']; ?>;
    const APP_URL = <?php echo json_encode(APP_URL); ?>;
    const PAYSTACK_PUBLIC_KEY = <?php echo json_encode(PAYSTACK_PUBLIC_KEY); ?>;
    const SQUARE_APPLICATION_ID = <?php echo json_encode(defined('SQUARE_APPLICATION_ID') ? SQUARE_APPLICATION_ID : ''); ?>;

    function setAiPaymentError(message) {
        var el = document.getElementById('aiPaymentError');
        if (!el) return;
        if (!message) {
            el.style.display = 'none';
            el.textContent = '';
        } else {
            el.style.display = 'block';
            el.textContent = message;
        }
    }

    function parseJsonSafe(raw) {
        if (!raw) return null;
        var cleaned = raw.replace(/^\uFEFF+/g, '').trim();
        return cleaned ? JSON.parse(cleaned) : null;
    }

    async function aiInitPaystack() {
        if (!PAYSTACK_PUBLIC_KEY || PAYSTACK_PUBLIC_KEY.indexOf('your-paystack') !== -1) {
            setAiPaymentError('Paystack is not configured on this site.');
            return;
        }
        setAiPaymentError(null);

        try {
            const res = await fetch(APP_URL + '/website/api/paystack/init.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: 'ai_premium', user_id: AI_USER_ID })
            });

            const text = await res.text();
            let data = null;
            try {
                data = parseJsonSafe(text);
            } catch (e) {
                setAiPaymentError('Paystack init failed. Raw response: ' + text.substring(0, 200));
                return;
            }

            if (!data || !data.success) {
                var msg = data && data.message ? data.message : ('Raw response: ' + text.substring(0, 200));
                setAiPaymentError('Paystack init failed: ' + msg);
                return;
            }

            function openPaystack(data) {
                if (typeof PaystackPop === 'undefined' || !window.PaystackPop) {
                    setAiPaymentError('Paystack SDK failed to load.');
                    return;
                }
                var txCurrency = (data.currency || 'NGN').toUpperCase();
                var handler = PaystackPop.setup({
                    key: data.public_key,
                    email: data.customer_email,
                    amount: data.amount * 100,
                    currency: txCurrency,
                    ref: data.reference,
                    callback: function (response) {
                        (async function () {
                            try {
                                const vr = await fetch(APP_URL + '/website/api/paystack/verify.php', {
                                    method: 'POST',
                                    headers: { 'Content-Type': 'application/json' },
                                    body: JSON.stringify({
                                        type: 'ai_premium',
                                        reference: response.reference,
                                        user_id: AI_USER_ID
                                    })
                                });
                                const vText = await vr.text();
                                let vData = null;
                                try {
                                    vData = parseJsonSafe(vText);
                                } catch (e2) {
                                    setAiPaymentError('Payment verification failed. Raw response: ' + vText.substring(0, 200));
                                    return;
                                }

                                if (vData && vData.success) {
                                    window.location.href = APP_URL + '/lms/ai_premium.php';
                                } else {
                                    var m = vData && vData.message ? vData.message : ('Raw response: ' + vText.substring(0, 200));
                                    setAiPaymentError('Payment verification failed. ' + m);
                                }
                            } catch (err) {
                                setAiPaymentError('Error verifying payment.');
                            }
                        })();
                    }
                });
                handler.openIframe();
            }

            if (typeof PaystackPop !== 'undefined') {
                openPaystack(data);
            } else {
                var s = document.createElement('script');
                s.src = 'https://js.paystack.co/v1/inline.js';
                s.onload = function () { openPaystack(data); };
                s.onerror = function () { setAiPaymentError('Failed to load Paystack payment widget.'); };
                document.head.appendChild(s);
            }
        } catch (e) {
            setAiPaymentError('Unexpected error while starting Paystack payment.');
        }
    }

    async function aiHandleSquare() {
        if (!SQUARE_APPLICATION_ID) {
            setAiPaymentError('Square is not configured on this site.');
            return;
        }
        setAiPaymentError(null);

        try {
            const res = await fetch(APP_URL + '/website/api/square/initialize.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: 'ai_premium', user_id: AI_USER_ID })
            });

            const text = await res.text();
            let data = null;
            try {
                data = parseJsonSafe(text);
            } catch (e) {
                setAiPaymentError('Square init failed. Raw response: ' + text.substring(0, 200));
                return;
            }

            if (!data || !data.success || !data.checkout_url) {
                var msg = data && data.message ? data.message : 'Failed to start Square payment.';
                setAiPaymentError(msg);
                return;
            }

            window.location.href = data.checkout_url;
        } catch (e) {
            setAiPaymentError('Unexpected error while starting Square payment.');
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        var pBtn = document.getElementById('aiPaystackBtn');
        if (pBtn) {
            pBtn.addEventListener('click', aiInitPaystack);
        }
        var sBtn = document.getElementById('aiSquareBtn');
        if (sBtn) {
            sBtn.addEventListener('click', aiHandleSquare);
        }
    });
</script>
<?php endif; ?>

<?php include __DIR__ . '/includes/footer.php'; ?>
