<?php

use MintyPHP\Router;
use MintyPHP\Support\Guard;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Mail\MailServicesFactory;

Guard::requireLogin();
Guard::requirePermissionOrForbidden(PermissionService::MAIL_LOG_VIEW);

$limit = (int) ($_GET['limit'] ?? 10);
$offset = (int) ($_GET['offset'] ?? 0);
$search = trim((string) ($_GET['search'] ?? ''));
$order = (string) ($_GET['order'] ?? 'created_at');
$dir = (string) ($_GET['dir'] ?? 'desc');
$status = trim((string) ($_GET['status'] ?? ''));
$createdFrom = trim((string) ($_GET['created_from'] ?? ''));
$createdTo = trim((string) ($_GET['created_to'] ?? ''));

$mailLogService = (new MailServicesFactory())->createMailLogService();
$result = $mailLogService->listPaged([
    'limit' => $limit,
    'offset' => $offset,
    'search' => $search,
    'order' => $order,
    'dir' => $dir,
    'status' => $status,
    'created_from' => $createdFrom,
    'created_to' => $createdTo,
]);

$rows = [];
foreach ($result['rows'] as $row) {
    $status = (string) ($row['status'] ?? '');
    $statusBadge = 'neutral';
    if ($status === 'sent') {
        $statusBadge = 'success';
    } elseif ($status === 'failed') {
        $statusBadge = 'danger';
    }

    $rows[] = [
        'id' => $row['id'] ?? null,
        'to_email' => $row['to_email'] ?? '',
        'subject' => $row['subject'] ?? '',
        'template' => $row['template'] ?? '',
        'status' => $status,
        'status_badge' => $statusBadge,
        'status_label' => t(ucfirst($status)),
        'created_at' => dt($row['created_at'] ?? ''),
        'sent_at' => dt($row['sent_at'] ?? ''),
    ];
}

Router::json([
    'data' => $rows,
    'total' => $result['total'] ?? 0,
]);
