<?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 <?= ($requested_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_<?= (int)$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('<?= crmEid($em['id']) ?>')">
                    Set Default
                  </button>
                <?php endif; ?>
              </td>
              <td>
                <button class="btn btn-danger btn-sm" onclick="deleteEmail('<?= crmEid($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>

<!-- ADD EMAIL MODAL -->
<div class="modal-overlay" id="addEmailModal">
  <div class="modal">
    <div class="modal-header">
      <span class="modal-title">Add Email</span>
      <button class="modal-close">✕</button>
    </div>

    <div class="modal-body">
      <div class="form-group">
        <label class="form-label">Email *</label>
        <input type="email" id="accountEmailInput" class="form-control" placeholder="example@domain.com">
      </div>

      <div class="form-group">
        <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
          <input type="checkbox" id="accountEmailDefault">
          Set as default
        </label>
      </div>
    </div>

    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('addEmailModal')">Cancel</button>
      <button class="btn btn-primary" onclick="addAccountEmail()">Add Email</button>
    </div>
  </div>
</div>
