<?php

$emails = $conn->query("
    SELECT *
    FROM accounts_email
    WHERE account_id = $account_id
    ORDER BY is_default DESC, id DESC
");
?>

<!-- ===================== EMAIL TAB ===================== -->
<div class="tab-pane <?= (isset($_GET['tab']) && $_GET['tab'] == 'email') ? 'active' : '' ?>" id="tab-email">

  <div class="toolbar">
    <span class="card-title">Account Emails</span>

    <button class="btn btn-primary btn-sm"
            onclick="openModal('addEmailModal')"
            style="margin-left:auto">
      + Add Email
    </button>
  </div>

  <div class="card">
    <div class="table-wrapper">
      <table class="crm-table">
        <thead>
          <tr>
            <th>Email</th>
            <th>Default</th>
            <th>Actions</th>
          </tr>
        </thead>

        <tbody>
        <?php if ($emails && $emails->num_rows > 0): ?>
          <?php while($em = $emails->fetch_assoc()): ?>
            <tr id="email_<?= $em['id'] ?>">

              <td>
                <?= htmlspecialchars($em['email']) ?>
              </td>

              <td>
                <?php if ((int)$em['is_default'] === 1): ?>
                  <span class="badge badge-green">Default</span>
                <?php else: ?>
                  <button class="btn btn-secondary btn-sm"
                          onclick="setDefaultEmail(<?= $em['id'] ?>)">
                    Set Default
                  </button>
                <?php endif; ?>
              </td>

              <td>
                <button class="btn btn-danger btn-sm"
                        onclick="deleteEmail(<?= $em['id'] ?>)">
                  Delete
                </button>
              </td>

            </tr>
          <?php endwhile; ?>
        <?php else: ?>
          <tr>
            <td colspan="3" class="text-muted text-center">
              No emails added yet.
            </td>
          </tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>





