<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/access_guards.php';
require_once __DIR__ . '/helpers.php';
auth_require_login();
$pdo = crm_pdo();
gp_require_staff_access($pdo);

$page_title = 'Inbox';

$rows = $pdo->query("
    SELECT ie.*,
           (SELECT COUNT(*) FROM inbox_attachments ia WHERE ia.inbox_email_id = ie.id) AS attachment_count
    FROM inbox_emails ie
    ORDER BY COALESCE(ie.received_at, ie.created_at) DESC, ie.id DESC
    LIMIT 200
")->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Inbox</h1>
    <span>Email intake from projects@gopools.gr</span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/gopools/public/inbox/settings.php">Inbox settings</a>
    <a class="btn btn-primary btn-sm" href="/gopools/public/inbox/fetch.php">Fetch emails</a>
  </div>
</div>

<div class="card">
  <div class="table-responsive">
    <table class="table">
      <thead>
        <tr>
          <th>ID</th>
          <th>From</th>
          <th>Subject</th>
          <th>Type</th>
          <th>Status</th>
          <th>Attachments</th>
          <th>Received</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($rows as $r): ?>
        <tr>
          <td><?php echo (int)$r['id']; ?></td>
          <td style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="<?php echo h(trim(($r['from_name'] ?? '') . ' ' . ($r['from_email'] ?? ''))); ?>">
            <?php echo h(trim(($r['from_name'] ?? '') . ' ' . ($r['from_email'] ?? ''))); ?>
          </td>
          <td style="max-width: 300px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="<?php echo h($r['subject']); ?>">
            <?php echo h($r['subject']); ?>
          </td>
          <td><span class="badge"><?php echo h($r['suggested_type']); ?></span></td>
          <td><span class="badge"><?php echo h($r['status']); ?></span></td>
          <td><?php echo (int)$r['attachment_count']; ?></td>
          <td><?php echo h($r['received_at'] ?: $r['created_at']); ?></td>
          <td>
            <a class="btn btn-sm btn-outline-light" href="/gopools/public/inbox/show.php?id=<?php echo (int)$r['id']; ?>">Open</a>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
