<?php
$pageTitle = 'FleetLume AI';
$admin = in_array(current_role(), ['owner','admin'], true);
function ai_value($value): string {
    if ($value === null || $value === '') return '—';
    if (is_bool($value)) return $value ? 'Yes' : 'No';
    if (is_array($value)) return implode(' · ', array_map(fn($v) => is_scalar($v) ? (string)$v : json_encode($v), $value));
    return (string) $value;
}
?>
<div class="page-heading ai-heading">
    <div><p class="eyebrow">Assisted Operations</p><h1>FleetLume AI</h1><p>Analyze operations, extract transportation documents, and prepare fuel recommendations. Every result requires human review.</p></div>
    <div class="page-actions"><a class="btn btn-primary" href="<?= url('/ai/automation') ?>">Open Autopilot</a><span class="ai-status <?= $configured && $enabled ? 'is-ready' : 'is-off' ?>"><i></i><?= $configured ? ($enabled ? 'Connected' : 'Configured, disabled') : 'Not configured' ?></span></div>
</div>

<?php if($admin): ?>
<details class="panel ai-settings-panel" <?= !$configured ? 'open' : '' ?>>
    <summary><div><p class="eyebrow">Administrator Setup</p><h2>Gemini Connection</h2><span>Store the key server-side and control model, context, timeout, and per-user limits.</span></div><b>Configure</b></summary>
    <form method="post" action="<?= url('/ai/settings') ?>" class="form-stack ai-settings-form">
        <?= csrf_field() ?>
        <div class="form-grid three">
            <label><span>API Key</span><input type="password" name="gemini_api_key" autocomplete="new-password" placeholder="<?= $maskedKey ? e($maskedKey).' · leave blank to keep' : 'Enter Gemini API key' ?>"><small class="muted">The key is written to a protected server configuration file.</small></label>
            <label><span>Model</span><input name="gemini_model" value="<?= e(setting('gemini_model','gemini-3.5-flash')) ?>" required><small class="muted">Change this if your Google AI project uses another supported model.</small></label>
            <label><span>Requests per user / hour</span><input type="number" min="1" max="500" name="gemini_max_requests_per_hour" value="<?= e(setting('gemini_max_requests_per_hour','30')) ?>"></label>
            <label><span>Request timeout (seconds)</span><input type="number" min="15" max="180" name="gemini_timeout_seconds" value="<?= e(setting('gemini_timeout_seconds','75')) ?>"></label>
            <label class="toggle-option"><input type="checkbox" name="gemini_enabled" value="1" <?= setting('gemini_enabled','0')==='1'?'checked':'' ?>><span>Enable AI features</span></label>
            <label class="toggle-option"><input type="checkbox" name="gemini_context_enabled" value="1" <?= setting('gemini_context_enabled','1')==='1'?'checked':'' ?>><span>Allow read-only operational context</span></label>
        </div>
        <div class="form-actions"><button class="btn btn-primary">Save AI Settings</button></div>
    </form>
    <?php if($configured): ?><form method="post" action="<?= url('/ai/test') ?>" class="inline-form ai-test-form"><?= csrf_field() ?><button class="btn btn-light">Test Connection</button><span class="muted">Current model: <?= e($model) ?></span></form><?php endif; ?>
</details>
<?php endif; ?>

<?php if(!$configured || !$enabled): ?>
<div class="panel ai-empty-state"><div class="ai-orb">AI</div><div><h2><?= !$configured ? 'Connect Gemini to activate the tools' : 'AI features are currently disabled' ?></h2><p><?= $admin ? 'Open the connection panel above, save the API key, enable AI, and run the connection test.' : 'An administrator must configure and enable the AI connection.' ?></p></div></div>
<?php else: ?>
<div class="ai-grid">
    <section class="panel ai-card ai-assistant-card">
        <div class="panel-header"><div><p class="eyebrow">Read-only assistant</p><h2>Ask FleetLume</h2><p>Use current platform summaries to identify exceptions or draft updates.</p></div><span class="section-chip"><?= e($model) ?></span></div>
        <form method="post" action="<?= url('/ai/assistant') ?>" class="form-stack">
            <?= csrf_field() ?>
            <label><span>Task</span><select name="mode"><option value="operations">Operations question</option><option value="risk_review">Risk review</option><option value="customer_update">Customer / broker update</option><option value="accounting">Accounting explanation</option><option value="hos_review">HOS log review</option></select></label>
            <label><span>Question or instruction</span><textarea name="question" rows="6" maxlength="3500" required placeholder="Examples: Which active loads need attention? Draft a broker update for the late pickup. Summarize current receivable risk."></textarea></label>
            <div class="ai-prompt-chips"><button type="button" data-ai-prompt="List the most urgent operational exceptions and explain why each needs attention.">Urgent exceptions</button><button type="button" data-ai-prompt="Which upcoming pickups or deliveries may need dispatcher follow-up?">Upcoming stops</button><button type="button" data-ai-prompt="Summarize reefer, border, fuel, and HOS alerts for today.">Daily risk brief</button></div>
            <button class="btn btn-primary ai-submit">Generate Response</button>
        </form>
    </section>

    <div class="ai-side-stack">
    <section class="panel ai-card" id="document-reader">
        <div class="panel-header"><div><p class="eyebrow">Multimodal extraction</p><h2>Document Reader</h2><p>Extract visible data from transportation images and PDFs for review.</p></div></div>
        <form method="post" action="<?= url('/ai/document') ?>" enctype="multipart/form-data" class="form-stack">
            <?= csrf_field() ?>
            <label><span>Document Type</span><select name="document_type"><option value="rate_confirmation">Rate Confirmation</option><option value="bol_pod">BOL / POD</option><option value="fuel_receipt">Fuel Receipt</option><option value="challan_ticket">Challan / Citation</option><option value="border_document">Border / Customs</option><option value="invoice">Invoice</option><option value="general">Other Transportation Document</option></select></label>
            <label class="ai-file-drop"><span>Image or PDF</span><input type="file" name="ai_document" accept="application/pdf,image/jpeg,image/png,image/webp" required><small>Maximum 15 MB. Uploaded content is sent to the configured AI service for analysis.</small></label>
            <button class="btn btn-primary ai-submit">Analyze Document</button>
        </form>
    </section>

    <section class="panel ai-card" id="fuel-planner">
        <div class="panel-header"><div><p class="eyebrow">Planning assistance</p><h2>Fuel Allowance Review</h2><p>Compare the deterministic baseline with an AI-assisted recommendation.</p></div></div>
        <form method="post" action="<?= url('/ai/fuel-recommendation') ?>" class="form-stack">
            <?= csrf_field() ?>
            <div class="form-grid two"><label><span>Planned Miles</span><input type="number" step="0.1" min="0" name="planned_miles" required></label><label><span>Target MPG</span><input type="number" step="0.1" min="0.1" name="target_mpg" value="6.5" required></label><label><span>Expected Price / Gallon</span><input type="number" step="0.01" min="0" name="fuel_price" required></label><label><span>Reserve %</span><input type="number" step="0.1" min="0" max="50" name="reserve_percent" value="10"></label><label><span>Cargo Weight (lb)</span><input type="number" step="1" min="0" name="cargo_weight"></label><label class="toggle-option"><input type="checkbox" name="reefer" value="1"><span>Reefer load</span></label></div>
            <label><span>Route / Conditions Known to Your Team</span><textarea name="route" rows="3" placeholder="Origin, destination, expected deadhead, mountain routes, idle time, border wait, approved stations…"></textarea></label>
            <button class="btn btn-primary ai-submit">Review Fuel Plan</button>
        </form>
    </section>
    </div>
</div>

<?php if($assistantResult): ?><section class="panel ai-result" id="assistant-result"><div class="panel-header"><div><p class="eyebrow"><?= e(readable_status($assistantResult['mode'])) ?></p><h2>AI Response</h2><p><?= e($assistantResult['question']) ?></p></div><button type="button" class="btn btn-light btn-sm" data-copy-target="#assistant-copy">Copy</button></div><div class="ai-answer" id="assistant-copy"><?= nl2br(e($assistantResult['text'])) ?></div><small class="muted">Generated by <?= e($assistantResult['model']) ?> · Human verification required.</small></section><?php endif; ?>

<?php if($documentResult): ?><section class="panel ai-result" id="document-result"><div class="panel-header"><div><p class="eyebrow">Document extraction</p><h2><?= e($documentResult['filename']) ?></h2><p>Review every extracted field against the original before saving it anywhere.</p></div><button type="button" class="btn btn-light btn-sm" data-copy-target="#document-json">Copy JSON</button></div><div class="ai-extraction-grid"><?php foreach(($documentResult['data']??[]) as $key=>$value): ?><div class="ai-field"><span><?= e(readable_status((string)$key)) ?></span><strong><?= e(ai_value($value)) ?></strong></div><?php endforeach; ?></div><pre id="document-json" class="ai-json"><?= e(json_encode($documentResult['data'], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES) ?: '{}') ?></pre><small class="muted">Generated by <?= e($documentResult['model']) ?> · Extraction can be incorrect.</small></section><?php endif; ?>

<?php if($fuelResult): $d=$fuelResult['data']??[]; ?><section class="panel ai-result" id="fuel-result"><div class="panel-header"><div><p class="eyebrow">Fuel recommendation</p><h2>Allowance Review</h2><p>AI guidance does not issue funds or replace dispatcher/accounting approval.</p></div></div><div class="ai-comparison"><div><span>Baseline Gallons</span><strong><?= number_format((float)$fuelResult['baseline_gallons'],2) ?></strong></div><div><span>Recommended Gallons</span><strong><?= number_format((float)($d['recommended_gallons']??0),2) ?></strong></div><div><span>Baseline Amount</span><strong><?= money($fuelResult['baseline_amount']) ?></strong></div><div><span>Recommended Amount</span><strong><?= money($d['recommended_amount']??0) ?></strong></div><div><span>Suggested Reserve</span><strong><?= number_format((float)($d['recommended_reserve_percent']??0),1) ?>%</strong></div><div><span>Confidence</span><strong><?= e(readable_status((string)($d['confidence']??'unknown'))) ?></strong></div></div><div class="content-grid two"><div><h3>Assumptions</h3><ul class="ai-list"><?php foreach(($d['assumptions']??[]) as $item): ?><li><?= e((string)$item) ?></li><?php endforeach; ?></ul></div><div><h3>Risk Flags</h3><ul class="ai-list"><?php foreach(($d['risk_flags']??[]) as $item): ?><li><?= e((string)$item) ?></li><?php endforeach; ?></ul></div></div><div class="ai-answer"><?= nl2br(e((string)($d['explanation']??''))) ?></div></section><?php endif; ?>

<?php if($usage): ?><section class="panel ai-usage-panel"><div class="panel-header"><div><h2>My Recent AI Usage</h2><p>Prompts are not stored in this log; only hashes and usage metadata are recorded.</p></div></div><div class="table-wrap"><table><thead><tr><th>Feature</th><th>Model</th><th>Status</th><th>Latency</th><th>Tokens</th><th>Time</th></tr></thead><tbody><?php foreach($usage as $row): ?><tr><td><?= e(readable_status($row['feature'])) ?></td><td><?= e($row['model_name']) ?></td><td><span class="badge badge-<?= status_class($row['status']) ?>"><?= e(readable_status($row['status'])) ?></span></td><td><?= number_format((int)$row['latency_ms']) ?> ms</td><td><?= number_format((int)$row['total_tokens']) ?></td><td><?= e(date_display($row['created_at'])) ?></td></tr><?php endforeach; ?></tbody></table></div></section><?php endif; ?>
<?php endif; ?>

<div class="panel ai-safety-note"><strong>Human review is mandatory.</strong><span>AI output may be incomplete or incorrect. It must not automatically approve payments, dispatch loads, certify HOS records, clear borders, determine legal compliance, or make safety-critical decisions.</span></div>
