<?php
// ============================================================
//  admin/email-whitelist.php — manage sender whitelist
// ============================================================
//
//  Lists every (account, sender) pair where remote images are
//  always allowed. Super admin can manage across all accounts;
//  regular admins see only their accessible accounts.
//
//  Add a sender manually here, or via the "Always trust X" button
//  in the message view.
// ============================================================

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

$me = auth_admin_user();
$is_super = ($me['role'] === 'super_admin');

// ── POST handlers ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $account_id = (int)($_POST['account_id'] ?? 0);
        $sender     = strtolower(trim((string)($_POST['sender'] ?? '')));
        $note       = trim((string)($_POST['note'] ?? ''));

        // Verify user has access to this account
        $can = (bool)db_row(
            'SELECT 1 FROM email_account_users WHERE account_id=:a AND user_id=:u',
            ['a' => $account_id, 'u' => $me['id']]
        );
        if (!$can) {
            header('Location: email-whitelist.php?msg=' . urlencode('You don\'t have access to that account.'));
            exit;
        }
        if (!filter_var($sender, FILTER_VALIDATE_EMAIL)) {
            header('Location: email-whitelist.php?msg=' . urlencode('Invalid email address.'));
            exit;
        }

        $existing = db_row(
            'SELECT id FROM email_sender_whitelist WHERE account_id=:a AND sender=:s',
            ['a' => $account_id, 's' => $sender]
        );
        if (!$existing) {
            db_insert('email_sender_whitelist', [
                'account_id' => $account_id,
                'sender'     => $sender,
                'note'       => $note !== '' ? mb_substr($note, 0, 255) : null,
                'added_by'   => $me['id'],
            ]);
            header('Location: email-whitelist.php?msg=' . urlencode("Added {$sender}."));
        } else {
            header('Location: email-whitelist.php?msg=' . urlencode("{$sender} was already on the whitelist."));
        }
        exit;
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        // Permission: user must have access to the account that owns this row
        $row = db_row(
            "SELECT w.* FROM email_sender_whitelist w
               JOIN email_account_users u ON u.account_id = w.account_id
              WHERE w.id=:id AND u.user_id=:uid",
            ['id' => $id, 'uid' => $me['id']]
        );
        if ($row) {
            db_exec('DELETE FROM email_sender_whitelist WHERE id=:id', ['id' => $id]);
            header('Location: email-whitelist.php?msg=' . urlencode('Removed.'));
        } else {
            header('Location: email-whitelist.php?msg=' . urlencode('Not found or no permission.'));
        }
        exit;
    }
}

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

// User's accessible accounts
$accounts = db_all(
    "SELECT a.id, a.display_name, a.email_address, a.colour
       FROM email_accounts a
       JOIN email_account_users u ON u.account_id = a.id
      WHERE u.user_id = :uid
      ORDER BY a.display_name",
    ['uid' => $me['id']]
);

// All whitelist entries the user can see
$account_ids = array_column($accounts, 'id');
$entries = [];
if (!empty($account_ids)) {
    $in = implode(',', array_map('intval', $account_ids));
    $entries = db_all(
        "SELECT w.*, a.display_name AS account_name, a.colour AS account_colour, a.email_address AS account_email,
                au.first_name, au.last_name
           FROM email_sender_whitelist w
           JOIN email_accounts a       ON a.id = w.account_id
      LEFT JOIN admin_users au         ON au.id = w.added_by
          WHERE w.account_id IN ($in)
       ORDER BY a.display_name, w.sender"
    );
}
?>

<style>
.wl-wrap{max-width:900px;margin:0 auto;}
.wl-add{background:#fff;border:1px solid var(--line);border-radius:8px;padding:1.25rem;margin-bottom:1.5rem;}
.wl-add h3{margin:0 0 .85rem;font-size:1rem;}
.wl-add .row-grid{display:grid;grid-template-columns:200px 1fr 1fr auto;gap:.6rem;align-items:end;}
@media(max-width:720px){.wl-add .row-grid{grid-template-columns:1fr;}}
.wl-add label{font-weight:600;font-size:.82rem;display:block;margin-bottom:.25rem;}
.wl-add input, .wl-add select{
    width:100%;padding:.5rem .65rem;border:1px solid var(--line);border-radius:5px;font-size:.88rem;font-family:inherit;
}

.wl-list{background:#fff;border:1px solid var(--line);border-radius:8px;overflow:hidden;}
.wl-row{
    display:grid;grid-template-columns:200px 1fr 200px auto;
    padding:.7rem 1rem;border-bottom:1px solid var(--line);align-items:center;gap:.75rem;
    font-size:.88rem;
}
.wl-row:last-child{border-bottom:none;}
.wl-acct{
    display:inline-flex;align-items:center;gap:.4rem;font-size:.78rem;color:var(--ink-muted);
}
.wl-acct .dot{width:8px;height:8px;border-radius:50%;display:inline-block;}
.wl-sender strong{color:var(--ink);}
.wl-note{font-size:.78rem;color:var(--ink-muted);}
.wl-when{font-size:.75rem;color:var(--ink-muted);}
.wl-empty{padding:2.5rem 1rem;text-align:center;color:var(--ink-muted);}

.flash{padding:.7rem 1rem;border-radius:6px;margin-bottom:1rem;font-size:.88rem;background:#dbeafe;color:#1e40af;border:1px solid #93c5fd;}
</style>

<section class="section"><div class="container wl-wrap">

<p style="margin:0 0 .5rem;">
    <a href="email.php" style="color:var(--ink-muted);text-decoration:none;font-size:.86rem;">← Back to email</a>
</p>

<h1 style="margin:0 0 .25rem;">Sender whitelist</h1>
<p class="muted" style="margin:0 0 1.5rem;font-size:.88rem;">
    Senders on this list have their remote images automatically loaded.
    All other senders' images are blocked for privacy (and to defeat tracking pixels).
</p>

<?php if (!empty($_GET['msg'])): ?>
    <div class="flash"><?= htmlspecialchars((string)$_GET['msg']) ?></div>
<?php endif; ?>

<?php if (empty($accounts)): ?>
    <p class="muted">You don't have access to any mailboxes.</p>
<?php else: ?>

    <!-- Add form -->
    <div class="wl-add">
        <h3>+ Add a trusted sender</h3>
        <form method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="add">
            <div class="row-grid">
                <div>
                    <label for="account_id">Mailbox</label>
                    <select name="account_id" id="account_id" required>
                        <?php foreach ($accounts as $a): ?>
                            <option value="<?= (int)$a['id'] ?>"><?= htmlspecialchars($a['display_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="sender">Sender email</label>
                    <input type="email" name="sender" id="sender" required placeholder="newsletter@example.com">
                </div>
                <div>
                    <label for="note">Note (optional)</label>
                    <input type="text" name="note" id="note" maxlength="255" placeholder="Mailchimp, etc.">
                </div>
                <div>
                    <button type="submit" class="btn">Add</button>
                </div>
            </div>
        </form>
    </div>

    <!-- List -->
    <?php if (empty($entries)): ?>
        <div class="wl-list">
            <div class="wl-empty">
                <p style="margin:0 0 .25rem;">No trusted senders yet.</p>
                <p style="margin:0;font-size:.82rem;">Add one above, or click "Always trust [sender]" on any message.</p>
            </div>
        </div>
    <?php else: ?>
        <div class="wl-list">
            <?php foreach ($entries as $e):
                $author_name = trim(($e['first_name'] ?? '') . ' ' . ($e['last_name'] ?? ''));
            ?>
                <div class="wl-row">
                    <div class="wl-acct">
                        <span class="dot" style="background:<?= htmlspecialchars($e['account_colour']) ?>;"></span>
                        <?= htmlspecialchars($e['account_name']) ?>
                    </div>
                    <div class="wl-sender">
                        <strong><?= htmlspecialchars($e['sender']) ?></strong>
                        <?php if (!empty($e['note'])): ?>
                            <div class="wl-note"><?= htmlspecialchars($e['note']) ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="wl-when">
                        Added <?= htmlspecialchars(date('j M Y', strtotime($e['created_at']))) ?>
                        <?php if ($author_name): ?>
                            <br>by <?= htmlspecialchars($author_name) ?>
                        <?php endif; ?>
                    </div>
                    <div>
                        <form method="post" style="margin:0;" onsubmit="return confirm('Remove this trusted sender?');">
                            <?= csrf_field() ?>
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= (int)$e['id'] ?>">
                            <button type="submit" class="btn btn-outline"
                                    style="padding:.3rem .65rem;font-size:.78rem;color:#991b1b;border-color:#fca5a5;">
                                Remove
                            </button>
                        </form>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

<?php endif; ?>

</div></section>

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