<?php
/**
 * Rig N Dig - AI Maintenance Oracle (Pioneer Suite)
 * Predictive Sales & Maintenance Analyzer
 */
require_once __DIR__ . '/includes/header.php';

// Fetch Recent Sales Data for Analysis
$sales = Database::fetchAll("
    SELECT i.*, c.company_name, c.contact_name, GROUP_CONCAT(it.description) as items
    FROM invoices i
    JOIN customers c ON i.customer_id = c.id
    JOIN invoice_items it ON i.id = it.invoice_id
    GROUP BY i.id
    ORDER BY i.created_at DESC
    LIMIT 20
");

// Build a context for AI analysis
$ctx = "Analyze these recent industrial sales for maintenance opportunities. Identify which customers might need spare parts or seal kits soon based on industry standards (valves need gaskets every 6-12 months, etc.):\n";
foreach ($sales as $s) {
    $ctx .= "Customer: {$s['company_name']} | Items: {$s['items']} | Date: {$s['created_at']}\n";
}
?>

<div class="p-6 max-w-7xl mx-auto">
    <div class="flex items-center justify-between mb-8">
        <div>
            <h1 class="text-3xl font-black font-display text-white italic tracking-tighter">AI <span class="text-orange-500">ORACLE</span></h1>
            <p class="text-gray-500 text-xs font-bold uppercase tracking-widest mt-1">Predictive Industrial Maintenance & Sales Intelligence</p>
        </div>
        <div class="flex gap-4">
            <div class="card-dark px-6 py-3 border-orange-600/20 text-center">
                <div class="text-[10px] text-gray-500 font-black uppercase tracking-widest mb-1">Prediction Engine</div>
                <div class="text-white font-black uppercase text-xs">V1.0 Neural Sourcing</div>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        <!-- AI Prediction Analysis -->
        <div class="lg:col-span-3">
            <div class="card-dark p-8 border-orange-600/30 bg-gradient-to-br from-navy-900 to-navy-800 relative overflow-hidden">
                <div class="absolute top-0 right-0 p-4 text-7xl opacity-5">🤖</div>
                <h3 class="text-sm font-black text-white uppercase tracking-[0.2em] mb-8 flex items-center gap-3">
                    <span class="relative flex h-3 w-3">
                        <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-orange-400 opacity-75"></span>
                        <span class="relative inline-flex rounded-full h-3 w-3 bg-orange-500"></span>
                    </span>
                    Neural Market Opportunity Report
                </h3>
                
                <div id="ai-oracle-content" class="text-gray-400 text-sm leading-relaxed space-y-6">
                    <div class="animate-pulse flex space-y-4 flex-col">
                        <div class="h-4 bg-navy-700 rounded w-3/4"></div>
                        <div class="h-4 bg-navy-700 rounded w-1/2"></div>
                        <div class="h-4 bg-navy-700 rounded w-5/6"></div>
                    </div>
                </div>

                <div class="mt-12 flex gap-4">
                    <button id="run-analysis" class="btn-primary px-8 py-3 text-xs font-black uppercase tracking-widest">Execute Full Scan</button>
                    <button class="btn-outline px-8 py-3 text-xs font-black uppercase tracking-widest">Export Targets</button>
                </div>
            </div>

            <!-- Historical Sales Matrix -->
            <div class="mt-8">
                <h3 class="text-xs font-black text-white uppercase tracking-widest mb-4">Input Data Stream</h3>
                <div class="card-dark overflow-hidden border-navy-800">
                    <table class="w-full text-left">
                        <thead class="bg-navy-800 text-[10px] text-gray-400 font-black uppercase tracking-widest">
                            <tr><th class="px-6 py-4">Client</th><th class="px-6 py-4">Asset Profile</th><th class="px-6 py-4">Sourcing Date</th></tr>
                        </thead>
                        <tbody class="divide-y divide-navy-700">
                            <?php foreach ($sales as $s): ?>
                            <tr>
                                <td class="px-6 py-4 text-xs font-black text-white"><?= e($s['company_name']) ?></td>
                                <td class="px-6 py-4 text-[10px] font-bold text-gray-500 uppercase"><?= e($s['items']) ?></td>
                                <td class="px-6 py-4 text-[10px] font-bold text-gray-400 uppercase"><?= date('M Y', strtotime($s['created_at'])) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Sidebar: Pioneer Controls -->
        <div class="lg:col-span-1 space-y-6">
            <div class="card-dark p-6">
                <h4 class="text-[10px] font-black text-white uppercase tracking-widest mb-4">Oracle Health</h4>
                <div class="space-y-4">
                    <div class="flex justify-between items-center text-[9px] font-bold uppercase tracking-widest">
                        <span class="text-gray-500">Node Status</span>
                        <span class="text-green-500">Connected</span>
                    </div>
                    <div class="flex justify-between items-center text-[9px] font-bold uppercase tracking-widest">
                        <span class="text-gray-500">AI Latency</span>
                        <span class="text-orange-400">Stable</span>
                    </div>
                    <div class="w-full bg-navy-700 h-1 rounded-full overflow-hidden">
                        <div class="bg-orange-600 h-full w-[88%]"></div>
                    </div>
                </div>
            </div>

            <div class="card-dark p-6 border-navy-700">
                <h4 class="text-[10px] font-black text-white uppercase tracking-widest mb-4">Quick Protocols</h4>
                <div class="grid grid-cols-1 gap-3">
                    <a href="/admin/certificates.php" class="bg-navy-800 hover:bg-orange-600/10 p-3 rounded-lg border border-white/5 text-[9px] font-black text-white uppercase tracking-widest transition-all">Vault Manager</a>
                    <a href="/admin/invoices.php" class="bg-navy-800 hover:bg-orange-600/10 p-3 rounded-lg border border-white/5 text-[9px] font-black text-white uppercase tracking-widest transition-all">Invoice Matrix</a>
                    <a href="/" target="_blank" class="bg-navy-800 hover:bg-orange-600/10 p-3 rounded-lg border border-white/5 text-[9px] font-black text-white uppercase tracking-widest transition-all">Public Portal</a>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('run-analysis').addEventListener('click', async function() {
    const content = document.getElementById('ai-oracle-content');
    content.innerHTML = '<div class="text-orange-500 font-bold uppercase tracking-[0.3em] text-xs flex items-center gap-2"><div class="w-4 h-4 border-2 border-t-transparent border-orange-500 rounded-full animate-spin"></div> SYNCING NEURAL DATA...</div>';
    
    try {
        const response = await fetch('/api/ai_handler.php', {
            method: 'POST',
            body: JSON.stringify({
                prompt: `<?= addslashes($ctx) ?>`,
                mode: 'generate'
            })
        });
        
        const data = await response.json();
        if (data.success) {
            content.innerHTML = '<div class="whitespace-pre-line border-l-2 border-orange-600/30 pl-6">' + data.response + '</div>';
        } else {
            content.innerHTML = '<div class="text-red-500 uppercase text-xs">Calibration Error: ' + data.error + '</div>';
        }
    } catch (err) {
        content.innerHTML = '<div class="text-red-500 uppercase text-xs">Transmission Failed.</div>';
    }
});
</script>

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