<?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 = 'Fetch inbox';
$errors = [];
$ok = '';
$results = ['fetched' => 0, 'saved' => 0, 'skipped' => 0, 'attachments' => 0];

if (!function_exists('imap_open')) {
    $errors[] = 'PHP IMAP extension is not enabled on this server.';
} else {
    $mailbox = inbox_mailbox_string($pdo);
    $username = inbox_setting($pdo, 'imap_username', '');
    $password = inbox_setting($pdo, 'imap_password', '');
    $limit = max(1, (int)inbox_setting($pdo, 'imap_fetch_limit', '20'));

    if ($mailbox === '' || $username === '' || $password === '') {
        $errors[] = 'Inbox settings are incomplete. Fill IMAP host, username and password first.';
    } else {
        $imap = @imap_open($mailbox, $username, $password);
        if (!$imap) {
            $errors[] = 'IMAP connection failed: ' . trim((string)imap_last_error());
        } else {
            $nums = imap_search($imap, 'ALL') ?: [];
            rsort($nums);
            $nums = array_slice($nums, 0, $limit);
            $results['fetched'] = count($nums);

            $emailCols = inbox_table_columns($pdo, 'inbox_emails');
            $attCols = inbox_table_columns($pdo, 'inbox_attachments');

            foreach ($nums as $msgno) {
                $overview = imap_fetch_overview($imap, (string)$msgno, 0);
                $ov = $overview[0] ?? null;
                if (!$ov) continue;

                $subject = inbox_decode_mime_header_text((string)($ov->subject ?? ''));
                $fromRaw = inbox_decode_mime_header_text((string)($ov->from ?? ''));
                $messageId = trim((string)($ov->message_id ?? ''));
                $received = date('Y-m-d H:i:s', strtotime((string)($ov->date ?? 'now')));

                $fromName = '';
                $fromEmail = '';
                if (preg_match('/^(.*?)\s*<([^>]+)>$/', $fromRaw, $m)) {
                    $fromName = trim($m[1], " \"'");
                    $fromEmail = trim($m[2]);
                } elseif (filter_var($fromRaw, FILTER_VALIDATE_EMAIL)) {
                    $fromEmail = $fromRaw;
                } else {
                    $fromName = $fromRaw;
                }

                $isDuplicate = false;
                if ($messageId !== '' && inbox_has_col($pdo, 'inbox_emails', 'message_id')) {
                    $stmt = $pdo->prepare("SELECT id FROM inbox_emails WHERE message_id = :mid LIMIT 1");
                    $stmt->execute([':mid' => $messageId]);
                    if ($stmt->fetchColumn()) $isDuplicate = true;
                } else {
                    $stmt = $pdo->prepare("SELECT id FROM inbox_emails WHERE subject = :sub AND from_email = :frm AND received_at = :rcv LIMIT 1");
                    $stmt->execute([':sub' => $subject, ':frm' => $fromEmail, ':rcv' => $received]);
                    if ($stmt->fetchColumn()) $isDuplicate = true;
                }

                if ($isDuplicate) {
                    $results['skipped']++;
                    continue;
                }

                $structure = imap_fetchstructure($imap, $msgno);
                $parts = $structure ? inbox_collect_bodies_and_attachments($imap, $msgno, $structure) : ['plain'=>'','html'=>'','attachments'=>[]];
                $body = $parts['plain'] !== '' ? $parts['plain'] : $parts['html'];
                if ($body === '') {
                    $raw = imap_body($imap, $msgno, FT_PEEK);
                    $body = inbox_extract_readable_text($raw);
                }

                $extract = inbox_extract_lines($subject, $body);
                $suggested = $extract['suggested_type'] ?: 'unknown';

                $fields = [];
                $placeholders = [];
                $params = [];

                $map = [
                    'from_name' => $fromName,
                    'from_email' => $fromEmail,
                    'subject' => $subject,
                    'body_text' => $body,
                    'suggested_type' => $suggested,
                    'status' => 'new',
                    'received_at' => $received,
                    'message_id' => $messageId !== '' ? $messageId : null,
                ];

                foreach ($map as $col => $val) {
                    if (in_array($col, $emailCols, true)) {
                        $fields[] = $col;
                        $placeholders[] = ':' . $col;
                        $params[':' . $col] = $val;
                    }
                }

                if (!$fields) continue;

                $sql = "INSERT INTO inbox_emails (" . implode(',', $fields) . ") VALUES (" . implode(',', $placeholders) . ")";
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                $emailId = (int)$pdo->lastInsertId();
                $results['saved']++;

                if ($emailId > 0 && $parts['attachments']) {
                    $baseDir = __DIR__ . '/../uploads/inbox/' . date('Y/m');
                    if (!is_dir($baseDir)) @mkdir($baseDir, 0777, true);

                    foreach ($parts['attachments'] as $a) {
                        $filename = preg_replace('/[^A-Za-z0-9._-]/', '_', (string)$a['filename']);
                        if ($filename === '') $filename = 'attachment.bin';
                        $savePath = $baseDir . '/' . time() . '_' . mt_rand(1000,9999) . '_' . $filename;
                        file_put_contents($savePath, (string)$a['content']);

                        $afields = [];
                        $aplaceholders = [];
                        $aparams = [];
                        $amap = [
                            'inbox_email_id' => $emailId,
                            'file_name' => $filename,
                            'file_path' => str_replace(__DIR__ . '/../', '/gopools/public/', $savePath),
                            'mime_type' => (string)$a['mime'],
                            'file_size' => filesize($savePath),
                        ];
                        foreach ($amap as $col => $val) {
                            if (in_array($col, $attCols, true)) {
                                $afields[] = $col;
                                $aplaceholders[] = ':' . $col;
                                $aparams[':' . $col] = $val;
                            }
                        }
                        if ($afields) {
                            $asql = "INSERT INTO inbox_attachments (" . implode(',', $afields) . ") VALUES (" . implode(',', $aplaceholders) . ")";
                            $astmt = $pdo->prepare($asql);
                            $astmt->execute($aparams);
                            $results['attachments']++;
                        }
                    }
                }
            }

            imap_close($imap);
            $ok = 'Fetch completed.';
        }
    }
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Fetch inbox</h1>
    <span>Real IMAP fetch</span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/gopools/public/inbox/index.php">Back to inbox</a>
  </div>
</div>

<?php if ($ok): ?>
<div class="card" style="margin-bottom:14px">
  <div class="small"><?php echo h($ok); ?></div>
  <div class="table-responsive" style="margin-top:10px">
    <table class="table">
      <tbody>
        <tr><td>Fetched</td><td><?php echo (int)$results['fetched']; ?></td></tr>
        <tr><td>Saved</td><td><?php echo (int)$results['saved']; ?></td></tr>
        <tr><td>Skipped</td><td><?php echo (int)$results['skipped']; ?></td></tr>
        <tr><td>Attachments</td><td><?php echo (int)$results['attachments']; ?></td></tr>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

<?php if ($errors): ?>
<div class="card">
  <div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div>
</div>
<?php endif; ?>

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