<?php
$automationStats = $automationStats ?? ['active_count' => 0, 'total_count' => 0, 'webhook_count' => 0, 'last_run_at' => null];
$automationRules = $automationRules ?? [];
$users = $users ?? [];
$mailFolders = $mailFolders ?? [];
$mailLabels = $mailLabels ?? [];
$sharedMailboxes = $sharedMailboxes ?? [];
?>
<section class="workspace-hero">
    <div>
        <h2>Automations</h2>
        <p>Build if/then workflows that react to mailbox events, campaign telemetry, suppressions, and CRM activity without leaving the campaign workspace.</p>
    </div>
    <div class="workspace-actions">
        <a class="btn secondary small" href="index.php?route=messages/commercialCampaign">Commercial Campaign</a>
        <a class="btn secondary small" href="index.php?route=messages/deliverabilityControlTower">Deliverability Control Tower</a>
    </div>
</section>

<section class="cards four compact-stats">
    <div class="card stat"><h3>Active rules</h3><p><?= (int)($automationStats['active_count'] ?? 0) ?></p><span><?= (int)($automationStats['total_count'] ?? 0) ?> total rules</span></div>
    <div class="card stat alt"><h3>Webhook-driven</h3><p><?= (int)($automationStats['webhook_count'] ?? 0) ?></p><span>Rules listening to provider or mailbox event intake</span></div>
    <div class="card stat alt"><h3>Last run</h3><p><?= e($automationStats['last_run_at'] ?? 'never') ?></p><span>Most recent rule execution</span></div>
    <div class="card stat alt"><h3>Connected mailboxes</h3><p><?= count($connectedMailboxes ?? []) ?></p><span>Mailbox actions available for routing and follow-up</span></div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Create automation rule</h2><span class="badge">If / Then</span></div>
        <form method="post" action="index.php?route=messages/saveAutomationRule" class="stacked-panel">
            <?= csrf_input() ?>
            <input type="hidden" name="return_route" value="messages/automations">
            <div class="form-grid two">
                <input name="name" placeholder="Rule name" required>
                <select name="trigger_event">
                    <option value="message_received">Message received</option>
                    <option value="event_webhook">Event webhook</option>
                </select>
                <select name="condition_channel">
                    <option value="">Any channel</option>
                    <option value="email">Email</option>
                    <option value="sms">SMS/MMS</option>
                </select>
                <input name="condition_contains" placeholder="Body or subject contains">
                <input name="condition_from_domain" placeholder="From domain contains">
                <input name="sort_order" type="number" value="100" min="1">
                <select name="action_move_folder">
                    <option value="">Do not move folder</option>
                    <?php foreach ($mailFolders as $folder): ?>
                        <option value="<?= e($folder['key'] ?? '') ?>"><?= e($folder['display_name'] ?? $folder['name'] ?? 'Folder') ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="action_apply_label">
                    <option value="">Do not apply label</option>
                    <?php foreach ($mailLabels as $label): ?>
                        <option value="<?= e($label['label_key'] ?? '') ?>"><?= e($label['name'] ?? 'Label') ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="action_assign_user_id">
                    <option value="0">Do not assign owner</option>
                    <?php foreach ($users as $user): ?>
                        <option value="<?= (int)$user['id'] ?>"><?= e($user['name'] ?? '') ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="action_shared_mailbox_id">
                    <option value="0">No shared inbox</option>
                    <?php foreach ($sharedMailboxes as $mailbox): ?>
                        <option value="<?= (int)$mailbox['id'] ?>"><?= e($mailbox['name'] ?? '') ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="action_focus_bucket">
                    <option value="">Keep focus state</option>
                    <option value="focused">Focused</option>
                    <option value="other">Other</option>
                </select>
                <input name="action_snooze_hours" type="number" min="0" step="1" placeholder="Snooze hours">
                <select name="action_set_mail_transport">
                    <option value="">Keep mail transport</option>
                    <option value="sendgrid_api">Switch to SendGrid API</option>
                    <option value="smtp">Switch to SMTP</option>
                    <option value="php_mail">Switch to PHP mail()</option>
                </select>
                <select name="action_sensitivity_level">
                    <option value="">Keep sensitivity</option>
                    <option value="standard">Standard</option>
                    <option value="confidential">Confidential</option>
                    <option value="regulated">Regulated</option>
                </select>
                <input name="action_followup_title" placeholder="Follow-up task title">
                <label class="mail-inline-check"><input type="checkbox" name="action_pause_campaign" value="1"> Pause campaign</label>
                <label class="mail-inline-check"><input type="checkbox" name="action_force_queue" value="1"> Force queue</label>
                <label class="mail-inline-check"><input type="checkbox" name="action_create_followup_task" value="1"> Create follow-up task</label>
                <label class="mail-inline-check"><input type="checkbox" name="is_active" value="1" checked> Active rule</label>
            </div>
            <button class="btn primary">Save automation rule</button>
        </form>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Playbook ideas</h2><span class="badge">Examples</span></div>
        <div class="alert-list">
            <article class="alert-tile ok"><strong>Open but no click</strong><div class="small muted">Queue a follow-up task after a campaign open without a click or reply.</div></article>
            <article class="alert-tile ok"><strong>Pricing intent</strong><div class="small muted">When the body contains quote or pricing language, assign sales and move to Focused.</div></article>
            <article class="alert-tile warn"><strong>Risk spike</strong><div class="small muted">Pause a campaign and change transport when event webhooks show elevated bounce or complaint risk.</div></article>
            <article class="alert-tile warn"><strong>Shared inbox routing</strong><div class="small muted">Move campaign replies into the right shared inbox with labels, ownership, and follow-up tasks.</div></article>
        </div>
    </div>
</section>

<section class="card">
    <div class="toolbar"><h2>Automation rule library</h2><span class="badge"><?= count($automationRules) ?></span></div>
    <table>
        <thead><tr><th>Name</th><th>Trigger</th><th>Active</th><th>Last run</th><th>Conditions</th><th>Actions</th><th>Toggle</th></tr></thead>
        <tbody>
        <?php foreach ($automationRules as $rule): ?>
            <?php $conditions = json_decode((string)($rule['condition_json'] ?? '{}'), true) ?: []; ?>
            <?php $actions = json_decode((string)($rule['action_json'] ?? '{}'), true) ?: []; ?>
            <tr>
                <td><strong><?= e($rule['name'] ?? '') ?></strong></td>
                <td><?= e($rule['trigger_event'] ?? '') ?></td>
                <td><?= !empty($rule['is_active']) ? 'Yes' : 'No' ?></td>
                <td><?= e($rule['last_run_at'] ?? 'never') ?></td>
                <td class="small"><code><?= e(json_encode($conditions, JSON_UNESCAPED_SLASHES)) ?></code></td>
                <td class="small"><code><?= e(json_encode($actions, JSON_UNESCAPED_SLASHES)) ?></code></td>
                <td><a class="btn secondary small" href="index.php?route=messages/toggleAutomationRule&id=<?= (int)$rule['id'] ?>&return=messages/automations"><?= !empty($rule['is_active']) ? 'Disable' : 'Enable' ?></a></td>
            </tr>
        <?php endforeach; ?>
        <?php if (!$automationRules): ?><tr><td colspan="7" class="muted">No automation rules created yet.</td></tr><?php endif; ?>
        </tbody>
    </table>
</section>
