<?php
$pageTitle='AI Automation';
$admin=in_array(current_role(),['owner','admin'],true);
$activeTab=in_array($tab,['overview','rules','actions','changes','runs'],true)?$tab:'overview';
function auto_config(array $rule): array { $v=json_decode((string)($rule['config_json']??''),true); return is_array($v)?$v:[]; }
?>
<div class="page-heading automation-hero">
    <div>
        <p class="eyebrow">FleetLume Autopilot</p>
        <h1>AI automation control center</h1>
        <p>Continuously find operational exceptions, prepare recommended actions, safely create alerts and tasks, and record every change in an auditable feed.</p>
    </div>
    <div class="page-actions">
        <?php if($admin): ?><form method="post" action="<?= url('/ai/automation/run') ?>"><?= csrf_field() ?><button class="btn btn-primary" type="submit"><span aria-hidden="true">✦</span> Run all automations</button></form><?php endif; ?>
        <a class="btn btn-light" href="<?= url('/ai') ?>">AI workspace</a>
    </div>
</div>

<div class="automation-stats">
    <article class="metric-card"><span>Enabled rules</span><strong><?= number_format((int)$stats['enabled_rules']) ?></strong><small>Scheduled and event-driven</small></article>
    <article class="metric-card"><span>Pending approvals</span><strong><?= number_format((int)$stats['pending_actions']) ?></strong><small>Human review required</small></article>
    <article class="metric-card is-success"><span>Safe actions today</span><strong><?= number_format((int)$stats['executed_24h']) ?></strong><small>Tasks and notifications</small></article>
    <article class="metric-card <?= (int)$stats['failed_24h']?'is-danger':'' ?>"><span>Failed actions</span><strong><?= number_format((int)$stats['failed_24h']) ?></strong><small>Last 24 hours</small></article>
    <article class="metric-card"><span>Change records</span><strong><?= number_format((int)$stats['changes_24h']) ?></strong><small>Last 24 hours</small></article>
</div>

<nav class="segmented-nav" aria-label="Automation sections">
    <?php foreach(['overview'=>'Overview','rules'=>'Rules','actions'=>'Approval queue','changes'=>'AI change feed','runs'=>'Run history'] as $key=>$label): ?>
        <a class="<?= $activeTab===$key?'active':'' ?>" href="<?= url('/ai/automation?tab='.$key) ?>"><?= e($label) ?><?php if($key==='actions' && (int)$stats['pending_actions']): ?><b><?= (int)$stats['pending_actions'] ?></b><?php endif; ?></a>
    <?php endforeach; ?>
</nav>

<?php if($activeTab==='overview'): ?>
<div class="content-grid automation-overview-grid">
    <section class="panel autopilot-status-card">
        <div class="panel-header"><div><p class="eyebrow">Automation policy</p><h2>Safe by design</h2></div><span class="status-dot is-online">Active</span></div>
        <div class="automation-policy-list">
            <div><span class="policy-icon">1</span><div><strong>Detect</strong><p>Deterministic checks scan loads, documents, reefer temperatures, fuel, HOS, borders, invoices, and carrier compliance.</p></div></div>
            <div><span class="policy-icon">2</span><div><strong>Analyze</strong><p>Gemini can prioritize findings and draft concise actions without changing identifiers or inventing facts.</p></div></div>
            <div><span class="policy-icon">3</span><div><strong>Act safely</strong><p>Low-risk notifications and team tasks may run automatically. Financial, compliance, dispatch, and safety decisions stay approval-only.</p></div></div>
            <div><span class="policy-icon">4</span><div><strong>Notify and audit</strong><p>Every completed AI action creates a change record and alerts owners and administrators.</p></div></div>
        </div>
    </section>
    <section class="panel">
        <div class="panel-header"><div><p class="eyebrow">Latest activity</p><h2>Recent AI changes</h2></div><a class="btn btn-light btn-sm" href="<?= url('/ai/automation?tab=changes') ?>">View all</a></div>
        <div class="activity-stream">
            <?php if(!$changes): ?><div class="empty-state compact"><strong>No AI changes yet</strong><span>Run the enabled rules to create the first audited actions.</span></div><?php endif; ?>
            <?php foreach(array_slice($changes,0,8) as $change): ?>
                <article class="activity-item"><span class="activity-marker"></span><div><strong><?= e($change['title']) ?></strong><p><?= e($change['message'] ?: readable_status($change['change_type'])) ?></p><small><?= e(date_display($change['created_at'])) ?> · <?= e($change['user_name'] ?: 'Autopilot') ?></small></div></article>
            <?php endforeach; ?>
        </div>
    </section>
</div>
<section class="panel">
    <div class="panel-header"><div><p class="eyebrow">Attention required</p><h2>Pending AI actions</h2><p>Nothing is hidden: review the proposed change, its risk level, and the source rule.</p></div><a class="btn btn-light btn-sm" href="<?= url('/ai/automation?tab=actions') ?>">Open queue</a></div>
    <div class="automation-action-list">
        <?php $pending=array_values(array_filter($actions,fn($a)=>$a['status']==='proposed')); ?>
        <?php if(!$pending): ?><div class="empty-state compact"><strong>Approval queue is clear</strong><span>New proposals will appear here after automation runs.</span></div><?php endif; ?>
        <?php foreach(array_slice($pending,0,6) as $action): ?>
            <article class="automation-action-card"><div class="risk-rail risk-<?= e($action['risk_level']) ?>"></div><div class="automation-action-main"><div class="automation-action-head"><div><span class="badge badge-<?= status_class($action['risk_level']) ?>"><?= e(readable_status($action['risk_level'])) ?> risk</span><strong><?= e($action['title']) ?></strong></div><small><?= e($action['rule_name'] ?: 'Manual AI') ?></small></div><p><?= e($action['description']) ?></p><div class="action-meta"><span><?= e(readable_status($action['action_type'])) ?></span><span><?= e(date_display($action['created_at'])) ?></span></div></div></article>
        <?php endforeach; ?>
    </div>
</section>
<?php endif; ?>

<?php if($activeTab==='rules'): ?>
<div class="content-grid automation-rules-layout">
    <?php if($admin): ?>
    <section class="panel automation-rule-editor">
        <div class="panel-header"><div><p class="eyebrow">Create automation</p><h2>New rule</h2><p>Choose what FleetLume should watch and which safe actions it may perform.</p></div></div>
        <form method="post" action="<?= url('/ai/automation/rules/save') ?>" class="form-stack">
            <?= csrf_field() ?>
            <label><span>Rule name</span><input name="name" maxlength="190" required placeholder="Example: Reefer exception response"></label>
            <label><span>Description</span><textarea name="description" rows="3" placeholder="Explain the expected workflow and who should respond."></textarea></label>
            <div class="form-grid two">
                <label><span>Watch for</span><select name="event_type"><option value="scheduled">All operational exceptions</option><option value="load_exception">Late or stalled loads</option><option value="document_missing">Missing delivery documents</option><option value="reefer_alert">Reefer temperature exceptions</option><option value="fuel_exception">Fuel allowance exceptions</option><option value="hos_risk">HOS / logbook risks</option><option value="border_delay">Border crossing delays</option><option value="invoice_overdue">Overdue invoices</option><option value="carrier_compliance">Carrier compliance expiries</option></select></label>
                <label><span>Frequency</span><select name="frequency"><option value="hourly">Hourly</option><option value="every_4_hours">Every 4 hours</option><option value="daily" selected>Daily</option><option value="manual">Manual only</option></select></label>
                <label><span>Execution mode</span><select name="execution_mode"><option value="recommend_only">Recommend only</option><option value="auto_safe">Automatically run safe actions</option></select></label>
                <label><span>Priority</span><input type="number" name="priority" min="1" max="100" value="50"></label>
                <label><span>Look-ahead hours</span><input type="number" name="lookahead_hours" min="1" max="168" value="24"></label>
                <label><span>Grace period (minutes)</span><input type="number" name="grace_minutes" min="0" max="1440" value="30"></label>
            </div>
            <fieldset class="choice-grid"><legend>Notify these portals</legend><?php foreach(['owner'=>'Owner','admin'=>'Admin','dispatcher'=>'Dispatcher','accountant'=>'Accountant','maintenance'=>'Maintenance','team'=>'Team'] as $value=>$label): ?><label class="check-card"><input type="checkbox" name="target_roles[]" value="<?= e($value) ?>" <?= in_array($value,['owner','admin','dispatcher'],true)?'checked':'' ?>><span><?= e($label) ?></span></label><?php endforeach; ?></fieldset>
            <div class="switch-list"><label><input type="checkbox" name="send_notification" value="1" checked><span><strong>Create notifications</strong><small>Low-risk and safe for automatic execution</small></span></label><label><input type="checkbox" name="create_task" value="1" checked><span><strong>Create team tasks</strong><small>Assigns the first suitable active team member</small></span></label><label><input type="checkbox" name="use_ai_summary" value="1" checked><span><strong>Use Gemini analysis</strong><small>Prioritizes findings and drafts action text</small></span></label><label><input type="checkbox" name="enabled" value="1" checked><span><strong>Enable immediately</strong><small>The cron runner will include this rule</small></span></label></div>
            <button class="btn btn-primary" type="submit">Save automation rule</button>
        </form>
    </section>
    <?php endif; ?>
    <section class="panel automation-rule-list-panel">
        <div class="panel-header"><div><p class="eyebrow">Configured workflows</p><h2><?= count($rules) ?> automation rules</h2></div></div>
        <div class="automation-rule-list">
            <?php foreach($rules as $rule): $cfg=auto_config($rule); ?>
            <article class="automation-rule-card <?= $rule['enabled']?'is-enabled':'' ?>">
                <div class="rule-card-top"><div class="rule-icon">✦</div><div><strong><?= e($rule['name']) ?></strong><p><?= e($rule['description'] ?: 'No description provided.') ?></p></div><span class="badge badge-<?= $rule['enabled']?'success':'neutral' ?>"><?= $rule['enabled']?'Enabled':'Paused' ?></span></div>
                <div class="rule-facts"><span><?= e(readable_status($rule['event_type'])) ?></span><span><?= e(readable_status($rule['frequency'])) ?></span><span><?= e(readable_status($rule['execution_mode'])) ?></span><span>Priority <?= (int)$rule['priority'] ?></span></div>
                <div class="rule-card-footer"><small>Last run: <?= e($rule['last_run_at']?date_display($rule['last_run_at']):'Never') ?> · <?= (int)$rule['pending_actions'] ?> pending</small><?php if($admin): ?><div class="action-row"><form method="post" action="<?= url('/ai/automation/run') ?>"><?= csrf_field() ?><input type="hidden" name="rule_id" value="<?= (int)$rule['id'] ?>"><button class="btn btn-light btn-sm">Run now</button></form><form method="post" action="<?= url('/ai/automation/rules/toggle') ?>"><?= csrf_field() ?><input type="hidden" name="id" value="<?= (int)$rule['id'] ?>"><input type="hidden" name="enabled" value="<?= $rule['enabled']?0:1 ?>"><button class="btn btn-light btn-sm"><?= $rule['enabled']?'Pause':'Enable' ?></button></form></div><?php endif; ?></div>
            </article>
            <?php endforeach; ?>
        </div>
    </section>
</div>
<?php endif; ?>

<?php if($activeTab==='actions'): ?>
<section class="panel">
    <div class="panel-header"><div><p class="eyebrow">Human-in-the-loop</p><h2>AI approval queue</h2><p>Safe actions can be automatic. Drafts and higher-impact actions remain here until an owner or administrator approves them.</p></div></div>
    <div class="automation-action-list full-list">
        <?php if(!$actions): ?><div class="empty-state"><strong>No AI actions yet</strong><span>Run an automation to scan current operational data.</span></div><?php endif; ?>
        <?php foreach($actions as $action): $payload=json_decode((string)$action['payload_json'],true)?:[]; ?>
        <article class="automation-action-card"><div class="risk-rail risk-<?= e($action['risk_level']) ?>"></div><div class="automation-action-main"><div class="automation-action-head"><div><span class="badge badge-<?= status_class($action['status']) ?>"><?= e(readable_status($action['status'])) ?></span><span class="badge badge-<?= status_class($action['risk_level']) ?>"><?= e(readable_status($action['risk_level'])) ?> risk</span><strong><?= e($action['title']) ?></strong></div><small><?= e($action['rule_name'] ?: 'AI workflow') ?></small></div><p><?= e($action['description']) ?></p><?php if(!empty($payload['draft'])): ?><div class="ai-draft-preview"><span>Draft</span><p><?= nl2br(e($payload['draft'])) ?></p></div><?php endif; ?><div class="rule-card-footer"><div class="action-meta"><span><?= e(readable_status($action['action_type'])) ?></span><span><?= e(readable_status($action['entity_type'] ?: 'general')) ?> #<?= (int)$action['entity_id'] ?></span><span><?= e(date_display($action['created_at'])) ?></span></div><?php if($admin && $action['status']==='proposed'): ?><div class="action-row"><form method="post" action="<?= url('/ai/automation/actions/approve') ?>"><?= csrf_field() ?><input type="hidden" name="id" value="<?= (int)$action['id'] ?>"><button class="btn btn-primary btn-sm">Approve & run</button></form><form method="post" action="<?= url('/ai/automation/actions/reject') ?>"><?= csrf_field() ?><input type="hidden" name="id" value="<?= (int)$action['id'] ?>"><button class="btn btn-light btn-sm">Reject</button></form></div><?php endif; ?></div></div></article>
        <?php endforeach; ?>
    </div>
</section>
<?php endif; ?>

<?php if($activeTab==='changes'): ?>
<section class="panel"><div class="panel-header"><div><p class="eyebrow">Transparent automation</p><h2>AI change feed</h2><p>Every change made by automation is recorded and announced to owners and administrators.</p></div></div><div class="activity-stream detailed"><?php if(!$changes): ?><div class="empty-state"><strong>No changes recorded</strong><span>Completed AI actions will appear here.</span></div><?php endif; ?><?php foreach($changes as $change): ?><article class="activity-item"><span class="activity-marker"></span><div><div class="activity-title-row"><strong><?= e($change['title']) ?></strong><span class="badge badge-success">Completed</span></div><p><?= e($change['message'] ?: readable_status($change['change_type'])) ?></p><div class="action-meta"><span><?= e(readable_status($change['change_type'])) ?></span><span><?= e(readable_status($change['entity_type'] ?: 'system')) ?> <?= $change['entity_id']?'#'.(int)$change['entity_id']:'' ?></span><span><?= e($change['user_name'] ?: 'FleetLume Autopilot') ?></span><span><?= e(date_display($change['created_at'])) ?></span></div></div></article><?php endforeach; ?></div></section>
<?php endif; ?>

<?php if($activeTab==='runs'): ?>
<section class="panel"><div class="panel-header"><div><p class="eyebrow">System health</p><h2>Automation run history</h2></div></div><div class="table-wrap"><table><thead><tr><th>Rule</th><th>Source</th><th>Status</th><th>Scanned</th><th>Proposed</th><th>Executed</th><th>Summary</th><th>Started</th></tr></thead><tbody><?php foreach($runs as $run): ?><tr><td><strong><?= e($run['rule_name'] ?: 'All rules') ?></strong></td><td><?= e(readable_status($run['trigger_source'])) ?></td><td><span class="badge badge-<?= status_class($run['status']) ?>"><?= e(readable_status($run['status'])) ?></span></td><td><?= (int)$run['items_scanned'] ?></td><td><?= (int)$run['actions_proposed'] ?></td><td><?= (int)$run['actions_executed'] ?></td><td><?= e($run['summary'] ?: $run['error_message'] ?: '—') ?></td><td><?= e(date_display($run['started_at'])) ?></td></tr><?php endforeach; ?></tbody></table></div></section>
<?php endif; ?>

<div class="panel automation-safety-banner"><div class="safety-icon">✓</div><div><strong>Automation guardrails</strong><p>FleetLume allows AI to create notifications, tasks, summaries, and drafts. It does not automatically approve payments, change load assignments, certify HOS logs, clear borders, alter accounting entries, or make safety-critical decisions.</p></div></div>
