<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/helpers.php';
auth_require_login();

$pdo = crm_pdo();
if (!gp_is_full_project_access_role(gp_user_role($pdo))) {
    http_response_code(403);
    exit('Access denied.');
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die('Missing inbox id.');

$stmt = $pdo->prepare("SELECT * FROM inbox_emails WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $id]);
$email = $stmt->fetch();
if (!$email) die('Inbox email not found.');

$stmt = $pdo->prepare("SELECT * FROM inbox_attachments WHERE inbox_email_id = :id ORDER BY id ASC");
$stmt->execute([':id' => $id]);
$attachments = $stmt->fetchAll();

$decodedSubject = inbox_decode_mime_header_text((string)($email['subject'] ?? ''));
$cleanBody = inbox_extract_readable_text((string)($email['body_text'] ?? ''));
$bodyPreview = inbox_preview_text($cleanBody, 1200);
$extract = inbox_extract_lines($decodedSubject, $cleanBody);
$matchedCustomer = inbox_find_customer_from_signature($pdo, $extract);

$page_title = 'Inbox email';
include __DIR__ . '/../includes/header.php';
?>
<style>
.inbox-show-grid{display:grid;grid-template-columns:1.35fr .9fr;gap:16px}
.inbox-meta-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:14px 0}
.inbox-meta-card{border:1px solid rgba(15,23,42,.08);border-radius:14px;padding:12px;background:rgba(255,255,255,.35)}
.inbox-meta-label{font-size:.8rem;opacity:.68;margin-bottom:4px}
.inbox-meta-value{font-weight:700;word-break:break-word}
.inbox-body-box{border:1px solid rgba(15,23,42,.08);border-radius:16px;padding:14px;background:rgba(255,255,255,.28)}
.inbox-body-text{white-space:pre-wrap;line-height:1.55;word-break:break-word}
.inbox-actions-wrap{display:flex;gap:8px;flex-wrap:wrap}
.inbox-attachment-list{margin:0;padding-left:18px}
.inbox-attachment-list li{margin:6px 0}
.inbox-compact-note{font-size:.82rem;opacity:.68;margin-top:8px}
details.inbox-raw{margin-top:14px}
details.inbox-raw summary{cursor:pointer;font-weight:700}
@media (max-width:980px){.inbox-show-grid{grid-template-columns:1fr}.inbox-meta-grid{grid-template-columns:1fr}}
</style>

<div class="page-header">
  <div class="page-header-title">
    <h1>Inbox email #<?php echo (int)$email['id']; ?></h1>
    <span><?php echo h($decodedSubject !== '' ? $decodedSubject : (string)$email['subject']); ?></span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/public/inbox/index.php">Back to inbox</a>
  </div>
</div>

<div class="inbox-show-grid">
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1rem">Email details</h1></div>

    <div class="inbox-meta-grid">
      <div class="inbox-meta-card">
        <div class="inbox-meta-label">From</div>
        <div class="inbox-meta-value"><?php echo h(trim(($email['from_name'] ?? '') . ' ' . ($email['from_email'] ?? ''))); ?></div>
      </div>
      <div class="inbox-meta-card">
        <div class="inbox-meta-label">Received</div>
        <div class="inbox-meta-value"><?php echo h((string)$email['received_at']); ?></div>
      </div>
      <div class="inbox-meta-card">
        <div class="inbox-meta-label">Status</div>
        <div class="inbox-meta-value"><span class="badge"><?php echo h((string)$email['status']); ?></span></div>
      </div>
      <div class="inbox-meta-card">
        <div class="inbox-meta-label">Suggested type</div>
        <div class="inbox-meta-value"><span class="badge"><?php echo h((string)($email['suggested_type'] ?: $extract['suggested_type'])); ?></span></div>
      </div>
    </div>

    <div class="page-header-title"><h1 style="font-size:1rem">Body</h1></div>
    <div class="inbox-body-box">
      <div class="inbox-body-text"><?php echo h($bodyPreview !== '' ? $bodyPreview : 'No readable body found.'); ?></div>
      <div class="inbox-compact-note">The body is cleaned for easier reading. Raw source is hidden below.</div>
    </div>

    <details class="inbox-raw">
      <summary>Show raw email source</summary>
      <div class="inbox-body-box" style="margin-top:10px">
        <div class="inbox-body-text"><?php echo h((string)$email['body_text']); ?></div>
      </div>
    </details>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1rem">Extracted details</h1></div>

    <div class="inbox-meta-grid" style="margin-top:0">
      <div class="inbox-meta-card">
        <div class="inbox-meta-label">Phone</div>
        <div class="inbox-meta-value"><?php echo h((string)$extract['signature_phone']); ?></div>
      </div>
      <div class="inbox-meta-card">
        <div class="inbox-meta-label">Amount</div>
        <div class="inbox-meta-value"><?php echo h((string)$extract['amount']); ?></div>
      </div>
      <div class="inbox-meta-card">
        <div class="inbox-meta-label">Deposit</div>
        <div class="inbox-meta-value"><?php echo h((string)$extract['deposit']); ?></div>
      </div>
      <div class="inbox-meta-card">
        <div class="inbox-meta-label">Project type</div>
        <div class="inbox-meta-value"><?php echo h((string)$extract['project_type']); ?></div>
      </div>
    </div>

    <div class="page-header-title" style="margin-top:12px"><h1 style="font-size:1rem">Matched customer</h1></div>
    <?php if ($matchedCustomer): ?>
      <div class="inbox-body-box">
        <div class="inbox-body-text"><?php echo h((string)$matchedCustomer['name']); ?><?php if (!empty($matchedCustomer['phone'])): ?>

<?php echo h((string)$matchedCustomer['phone']); ?><?php endif; ?></div>
      </div>
    <?php else: ?>
      <p class="small">No existing customer matched.</p>
    <?php endif; ?>

    <div class="inbox-actions-wrap" style="margin-top:12px">
      <a class="btn btn-primary btn-sm" href="/public/inbox/process.php?id=<?php echo (int)$email['id']; ?>&action=create_customer">Create customer</a>
      <a class="btn btn-primary btn-sm" href="/public/inbox/process.php?id=<?php echo (int)$email['id']; ?>&action=create_project">Create project</a>
      <a class="btn btn-secondary btn-sm" href="/public/inbox/process.php?id=<?php echo (int)$email['id']; ?>&action=archive">Archive</a>
    </div>

    <div class="page-header-title" style="margin-top:14px"><h1 style="font-size:1rem">Attachments</h1></div>
    <?php if (!$attachments): ?>
      <p class="small">No attachments.</p>
    <?php else: ?>
      <ul class="inbox-attachment-list">
        <?php foreach ($attachments as $a): ?>
          <li><a href="<?php echo h((string)$a['file_path']); ?>" target="_blank" rel="noopener"><?php echo h((string)$a['file_name']); ?></a></li>
        <?php endforeach; ?>
      </ul>
    <?php endif; ?>
  </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
