<?php
// ============================================================
//  admin/email-accounts.php — list of email accounts
// ============================================================
//
//  Super admin only. Shows all configured email accounts with
//  status, last sync, and links to edit/delete. Used to set up
//  shared mailboxes (info@, branding@, etc.) and assign which
//  admin users can read them.
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/config.php';
auth_require_super_admin();

$me = auth_admin_user();

// ── POST: delete or toggle-active ───────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $action = $_POST['action'] ?? '';
    $id = (int)($_POST['id'] ?? 0);

    if ($action === 'delete' && $id) {
        db_exec('DELETE FROM email_accounts WHERE id=:id', ['id' => $id]);
        header('Location: email-accounts.php?msg=' . urlencode('Account deleted.'));
        exit;
    }

    if ($action === 'toggle' && $id) {
        db_exec('UPDATE email_accounts SET is_active = 1 - is_active WHERE id=:id', ['id' => $id]);
        header('Location: email-accounts.php?msg=' . urlencode('Account toggled.'));
        exit;
    }
}

$page_title = 'Email accounts';
require __DIR__ . '/_guard.php';

$accounts = db_all(
    'SELECT a.*,
            (SELECT COUNT(*) FROM email_account_users WHERE account_id = a.id) AS user_count,
            (SELECT COUNT(*) FROM email_messages WHERE account_id = a.id)      AS msg_count
       FROM email_accounts a
   ORDER BY a.display_name'
);

$settings_section = 'email_accts';
require __DIR__ . '/_settings_open.php';
?>

<style>
.acct-grid{display:grid;grid-template-columns:1fr;gap:.75rem;margin-top:1rem;}
.acct-card{
    background:#fff;border:1px solid var(--line);border-radius:8px;padding:1rem 1.25rem;
    display:flex;align-items:center;gap:1rem;flex-wrap:wrap;
}
.acct-card.inactive{opacity:.55;}
.acct-pill{
    display:inline-flex;align-items:center;justify-content:center;
    width:36px;height:36px;border-radius:50%;color:#fff;font-weight:700;font-size:.95rem;
    flex-shrink:0;
}
.acct-info{flex:1;min-width:0;}
.acct-info h3{margin:0 0 .15rem;font-size:1rem;}
.acct-info .acct-email{font-size:.85rem;color:var(--ink-muted);margin:0;}
.acct-meta{font-size:.78rem;color:var(--ink-muted);}
.acct-actions{display:flex;gap:.4rem;flex-wrap:wrap;}
.acct-actions .btn-mini{
    padding:.35rem .75rem;font-size:.78rem;border:1px solid var(--line);background:#fff;
    border-radius:5px;text-decoration:none;color:var(--ink);
}
.acct-actions .btn-mini:hover{background:#f5f3ee;}
.acct-actions .btn-mini.danger{color:#991b1b;border-color:#fca5a5;}
.acct-actions .btn-mini.danger:hover{background:#fee2e2;}
.acct-error{font-size:.78rem;color:#991b1b;margin-top:.35rem;}
.status-dot{
    display:inline-block;width:8px;height:8px;border-radius:50%;
    margin-right:.4rem;background:#94a3b8;
}
.status-dot.ok{background:#16a34a;}
.status-dot.bad{background:#dc2626;}
</style>

<?php if (!empty($_GET['msg'])): ?>
    <div class="alert alert-success" data-autohide style="margin-bottom:1rem;">
        <?= htmlspecialchars((string)$_GET['msg']) ?>
    </div>
<?php endif; ?>

<div style="display:flex;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:.5rem;flex-wrap:wrap;">
    <div>
        <h1 style="margin:0;">Email accounts</h1>
        <p style="margin:.25rem 0 0;color:var(--ink-muted);font-size:.88rem;">
            Configure shared mailboxes that admins can read and reply to from the email portal.
        </p>
    </div>
    <a href="email-account-edit.php" class="btn">+ Add account</a>
</div>

<?php if (empty($accounts)): ?>
    <div class="card" style="padding:2rem;text-align:center;color:var(--ink-muted);margin-top:1.5rem;">
        <p style="margin:0 0 .5rem;">No email accounts configured yet.</p>
        <p style="margin:0;font-size:.85rem;">Add one to get started — typically shared mailboxes like info@ or branding@.</p>
    </div>
<?php else: ?>
    <div class="acct-grid">
    <?php foreach ($accounts as $a):
        $initials = strtoupper(mb_substr($a['display_name'], 0, 1));
        $has_error = !empty($a['last_error']);
        $synced = $a['last_synced_at']
            ? date('j M H:i', strtotime($a['last_synced_at']))
            : 'never';
    ?>
        <div class="acct-card <?= $a['is_active'] ? '' : 'inactive' ?>">
            <div class="acct-pill" style="background:<?= htmlspecialchars($a['colour']) ?>;">
                <?= htmlspecialchars($initials) ?>
            </div>
            <div class="acct-info">
                <h3>
                    <span class="status-dot <?= !$a['is_active'] ? '' : ($has_error ? 'bad' : 'ok') ?>"></span>
                    <?= htmlspecialchars($a['display_name']) ?>
                </h3>
                <p class="acct-email"><?= htmlspecialchars($a['email_address']) ?></p>
                <p class="acct-meta">
                    <?= (int)$a['user_count'] ?> user<?= $a['user_count']==1?'':'s' ?> ·
                    <?= number_format((int)$a['msg_count']) ?> messages ·
                    last sync: <?= htmlspecialchars($synced) ?>
                    <?= $a['is_active'] ? '' : ' · <em>paused</em>' ?>
                </p>
                <?php if ($has_error): ?>
                    <div class="acct-error">⚠ <?= htmlspecialchars(mb_substr((string)$a['last_error'], 0, 200)) ?></div>
                <?php endif; ?>
            </div>
            <div class="acct-actions">
                <a href="email-account-edit.php?id=<?= (int)$a['id'] ?>" class="btn-mini">Edit</a>
                <form method="post" style="display:inline;">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="toggle">
                    <input type="hidden" name="id" value="<?= (int)$a['id'] ?>">
                    <button type="submit" class="btn-mini"><?= $a['is_active'] ? 'Pause' : 'Resume' ?></button>
                </form>
                <form method="post" style="display:inline;"
                      onsubmit="return confirm('Delete <?= htmlspecialchars(addslashes($a['display_name'])) ?> and all its synced messages?');">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= (int)$a['id'] ?>">
                    <button type="submit" class="btn-mini danger">Delete</button>
                </form>
            </div>
        </div>
    <?php endforeach; ?>
    </div>
<?php endif; ?>

<?php require __DIR__ . '/_settings_close.php'; ?>

<?php require __DIR__ . '/_footer.php'; ?>