<?php
/**
 * WhatsApp Messages Log
 */
$page   = max(1, (int)($_GET['page'] ?? 1));
$limit  = 25;

$filters = [
    'status' => $_GET['status'] ?? '',
    'event'  => $_GET['event']  ?? '',
    'phone'  => trim($_GET['phone'] ?? ''),
];

$_waModel  = new \Core\App\Models\WhatsAppMessageModel();
$_waResult = $_waModel->getPaginated($page, $limit, $filters);

$messages   = $_waResult['messages'];
$total      = $_waResult['total'];
$totalPages = $_waResult['total_pages'];

$filter_status = $filters['status'];
$filter_event  = $filters['event'];
$filter_phone  = $filters['phone'];

$statusBadge = [
    'sent'    => 'bg-success',
    'failed'  => 'bg-danger',
    'pending' => 'bg-warning text-dark',
];
?>

<div class="content-wrapper">
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2 align-items-center">
                <div class="col">
                    <h1 class="m-0">
                        <i class="bi bi-whatsapp me-2 text-success"></i>
                        <?= __('whatsapp.log_title', 'WhatsApp Messages Log') ?>
                    </h1>
                </div>
                <div class="col-auto d-flex gap-2">
                    <a href="/admin/settings/whatsapp" class="btn btn-outline-secondary btn-sm">
                        <i class="bi bi-gear me-1"></i><?= __('whatsapp.settings', 'Settings') ?>
                    </a>
                </div>
            </div>
        </div>
    </section>

    <section class="content">
        <div class="container-fluid">

            <!-- Stats row -->
            <div class="row g-3 mb-4">
                <?php
                $stats = $_waModel->getStats30d();
                ?>
                <div class="col-sm-4">
                    <div class="card border-0 shadow-sm text-center py-3">
                        <div class="fw-bold fs-4"><?= (int)$stats['total'] ?></div>
                        <div class="text-muted small"><?= __('whatsapp.log_total_30d', 'Total (30 days)') ?></div>
                    </div>
                </div>
                <div class="col-sm-4">
                    <div class="card border-0 shadow-sm text-center py-3">
                        <div class="fw-bold fs-4 text-success"><?= (int)$stats['sent'] ?></div>
                        <div class="text-muted small"><?= __('whatsapp.log_sent', 'Sent') ?></div>
                    </div>
                </div>
                <div class="col-sm-4">
                    <div class="card border-0 shadow-sm text-center py-3">
                        <div class="fw-bold fs-4 text-danger"><?= (int)$stats['failed'] ?></div>
                        <div class="text-muted small"><?= __('whatsapp.log_failed', 'Failed') ?></div>
                    </div>
                </div>
            </div>

            <!-- Filters -->
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-body py-2">
                    <form method="get" class="row g-2 align-items-end">
                        <div class="col-sm-3">
                            <select name="status" class="form-select form-select-sm">
                                <option value=""><?= __('whatsapp.log_all_status', 'All Statuses') ?></option>
                                <option value="sent"    <?= $filter_status === 'sent'    ? 'selected' : '' ?>>✅ Sent</option>
                                <option value="failed"  <?= $filter_status === 'failed'  ? 'selected' : '' ?>>❌ Failed</option>
                                <option value="pending" <?= $filter_status === 'pending' ? 'selected' : '' ?>>⏳ Pending</option>
                            </select>
                        </div>
                        <div class="col-sm-3">
                            <select name="event" class="form-select form-select-sm">
                                <option value=""><?= __('whatsapp.log_all_events', 'All Events') ?></option>
                                <option value="order_confirmed" <?= $filter_event === 'order_confirmed' ? 'selected' : '' ?>>Order Confirmed</option>
                                <option value="order_shipped"   <?= $filter_event === 'order_shipped'   ? 'selected' : '' ?>>Order Shipped</option>
                                <option value="status_updated"  <?= $filter_event === 'status_updated'  ? 'selected' : '' ?>>Status Updated</option>
                            </select>
                        </div>
                        <div class="col-sm-3">
                            <input type="text" name="phone" class="form-control form-control-sm"
                                   placeholder="<?= __('whatsapp.log_filter_phone', 'Filter by phone...') ?>"
                                   value="<?= htmlspecialchars($filter_phone) ?>">
                        </div>
                        <div class="col-sm-3 d-flex gap-2">
                            <button type="submit" class="btn btn-primary btn-sm">
                                <i class="bi bi-search me-1"></i><?= __('actions.filter', 'Filter') ?>
                            </button>
                            <a href="/admin/settings/whatsapp/logs" class="btn btn-outline-secondary btn-sm">
                                <?= __('actions.reset', 'Reset') ?>
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Table -->
            <div class="card border-0 shadow-sm">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0 small">
                        <thead class="table-light">
                            <tr>
                                <th>#</th>
                                <th><?= __('whatsapp.log_phone', 'Phone') ?></th>
                                <th><?= __('whatsapp.log_event', 'Event') ?></th>
                                <th><?= __('whatsapp.log_message', 'Message') ?></th>
                                <th><?= __('whatsapp.log_provider', 'Provider') ?></th>
                                <th><?= __('whatsapp.log_status', 'Status') ?></th>
                                <th><?= __('whatsapp.log_sent_at', 'Sent At') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($messages)): ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted py-5">
                                    <i class="bi bi-chat-square-dots d-block mb-2" style="font-size:2rem;opacity:.3"></i>
                                    <?= __('whatsapp.log_empty', 'No messages logged yet') ?>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($messages as $msg): ?>
                            <tr>
                                <td class="text-muted"><?= (int)$msg['id'] ?></td>
                                <td>
                                    <code><?= htmlspecialchars($msg['phone']) ?></code>
                                    <?php if ($msg['order_id']): ?>
                                    <br><a href="/admin/orders/view/<?= (int)$msg['order_id'] ?>" class="text-muted" style="font-size:11px">
                                        #<?= (int)$msg['order_id'] ?>
                                    </a>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($msg['event']): ?>
                                    <span class="badge bg-secondary"><?= htmlspecialchars($msg['event']) ?></span>
                                    <?php else: ?>
                                    <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                                <td style="max-width:220px;">
                                    <span class="d-inline-block text-truncate" style="max-width:200px;"
                                          title="<?= htmlspecialchars($msg['message']) ?>">
                                        <?= htmlspecialchars($msg['message']) ?>
                                    </span>
                                </td>
                                <td><?= htmlspecialchars(strtoupper($msg['provider'] ?? '—')) ?></td>
                                <td>
                                    <span class="badge <?= $statusBadge[$msg['status']] ?? 'bg-secondary' ?>">
                                        <?= htmlspecialchars($msg['status']) ?>
                                    </span>
                                    <?php if ($msg['error'] && $msg['status'] === 'failed'): ?>
                                    <br><small class="text-danger"><?= htmlspecialchars(mb_substr($msg['error'], 0, 60)) ?></small>
                                    <?php endif; ?>
                                </td>
                                <td class="text-muted" style="white-space:nowrap;">
                                    <?= $msg['sent_at'] ? date('d/m/Y H:i', strtotime($msg['sent_at'])) : '—' ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                <div class="card-footer bg-white">
                    <nav>
                        <ul class="pagination pagination-sm mb-0 justify-content-center">
                            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                            <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                <a class="page-link"
                                   href="?page=<?= $i ?>&status=<?= urlencode($filter_status) ?>&event=<?= urlencode($filter_event) ?>&phone=<?= urlencode($filter_phone) ?>">
                                    <?= $i ?>
                                </a>
                            </li>
                            <?php endfor; ?>
                        </ul>
                    </nav>
                </div>
                <?php endif; ?>
            </div>

        </div>
    </section>
</div>
