<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<?php $featureLabel = static fn (string $slug) => str_replace('Kpi ', 'KPI ', ucwords(str_replace('_', ' ', $slug))); ?>

<div class="mb-3">
    <h1 class="h3 mb-1">AI Call Log</h1>
    <p class="text-muted mb-0">Every Claude API call this hotel's account has made — request, response, tool calls, and token usage — for debugging and cost tracking. See <a href="<?= site_url('settings') ?>#tab-ai">Settings &gt; AI Features</a> to configure the API key or turn features on/off.</p>
</div>

<div class="row g-3 mb-3">
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Total Calls</div>
            <div class="fs-4 fw-bold"><?= number_format($stats['total']) ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Succeeded</div>
            <div class="fs-4 fw-bold text-success"><?= number_format($stats['success']) ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Failed</div>
            <div class="fs-4 fw-bold text-danger"><?= number_format($stats['failed']) ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Total Tokens</div>
            <div class="fs-4 fw-bold"><?= number_format($stats['tokens']) ?></div>
        </div></div>
    </div>
</div>

<div class="card shadow-sm mb-3">
    <div class="card-body">
        <form action="<?= site_url('ai-call-log') ?>" method="get" class="row g-2 align-items-center">
            <div class="col-md-4">
                <div class="input-group input-group-sm">
                    <span class="input-group-text bg-white"><i class="bi bi-calendar3"></i></span>
                    <input type="date" class="form-control" name="date_from" value="<?= esc($filters['date_from']) ?>" title="From">
                    <input type="date" class="form-control" name="date_to" value="<?= esc($filters['date_to']) ?>" title="To">
                </div>
            </div>
            <div class="col-md-3 col-6">
                <select class="form-select form-select-sm" name="feature">
                    <option value="">All Features</option>
                    <?php foreach ($features as $feature): ?>
                        <option value="<?= esc($feature) ?>" <?= $filters['feature'] === $feature ? 'selected' : '' ?>><?= esc($featureLabel($feature)) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3 col-6">
                <select class="form-select form-select-sm" name="status">
                    <option value="">All Status</option>
                    <option value="success" <?= $filters['status'] === 'success' ? 'selected' : '' ?>>Succeeded</option>
                    <option value="failed" <?= $filters['status'] === 'failed' ? 'selected' : '' ?>>Failed</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-sm btn-outline-primary w-100"><i class="bi bi-funnel me-1"></i>Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="table-scroll">
        <table class="table table-hover mb-0 align-middle small">
            <thead class="table-light">
                <tr><th>Date &amp; Time</th><th>Feature</th><th>Related</th><th>Model</th><th>Tokens</th><th>Status</th><th>Triggered By</th><th class="text-end">Actions</th></tr>
            </thead>
            <tbody>
            <?php if (empty($entries)): ?>
                <tr><td colspan="8" class="text-center text-muted py-4">No AI calls match this search/filter.</td></tr>
            <?php endif; ?>
            <?php foreach ($entries as $e): ?>
                <tr>
                    <td class="text-nowrap text-muted"><?= esc(date('d M Y, g:i a', strtotime($e->created_at))) ?></td>
                    <td><span class="badge bg-light text-dark border"><?= esc($featureLabel($e->feature)) ?></span></td>
                    <td class="text-muted"><?= $e->related_type ? esc(ucwords(str_replace('_', ' ', $e->related_type)) . ' #' . $e->related_id) : '—' ?></td>
                    <td class="text-muted"><?= esc($e->model ?? '—') ?></td>
                    <td class="text-muted"><?= $e->input_tokens !== null ? number_format((int) $e->input_tokens + (int) $e->output_tokens) : '—' ?></td>
                    <td><span class="badge bg-<?= $e->success ? 'success' : 'danger' ?>"><?= $e->success ? 'Succeeded' : 'Failed' ?></span></td>
                    <td class="text-muted"><?= esc($e->triggered_by_name ?? 'System') ?></td>
                    <td class="text-end">
                        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#viewCallModal"
                                data-when="<?= esc(date('d M Y, g:i a', strtotime($e->created_at))) ?>"
                                data-feature="<?= esc($featureLabel($e->feature)) ?>"
                                data-system="<?= esc($e->system_prompt ?? '') ?>"
                                data-request="<?= esc($e->request_messages ?? '') ?>"
                                data-tools="<?= esc($e->tool_calls ?? '') ?>"
                                data-response="<?= esc($e->response_text ?? '') ?>"
                                data-error="<?= esc($e->error_message ?? '') ?>">
                            <i class="bi bi-eye"></i>
                        </button>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if (! empty($entries)): ?>
    <?php
        $current = $pager->getCurrentPage();
        $total   = $pager->getTotal();
        $totalPages = max(1, (int) ceil($total / $perPage));
        $first   = ($current - 1) * $perPage + 1;
        $last    = min($current * $perPage, $total);
        $qs      = array_merge($filters, ['per_page' => $perPage]);
    ?>
    <div class="card-footer bg-white d-flex justify-content-between align-items-center flex-wrap gap-2">
        <span class="text-muted small">Showing <?= $first ?> to <?= $last ?> of <?= number_format($total) ?> calls</span>
        <div class="d-flex align-items-center gap-2">
            <nav>
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item <?= $current <= 1 ? 'disabled' : '' ?>">
                        <a class="page-link" href="<?= site_url('ai-call-log?' . http_build_query(array_merge($qs, ['page' => $current - 1]))) ?>"><i class="bi bi-chevron-left"></i></a>
                    </li>
                    <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                        <li class="page-item <?= $p === $current ? 'active' : '' ?>">
                            <a class="page-link" href="<?= site_url('ai-call-log?' . http_build_query(array_merge($qs, ['page' => $p]))) ?>"><?= $p ?></a>
                        </li>
                    <?php endfor; ?>
                    <li class="page-item <?= $current >= $totalPages ? 'disabled' : '' ?>">
                        <a class="page-link" href="<?= site_url('ai-call-log?' . http_build_query(array_merge($qs, ['page' => $current + 1]))) ?>"><i class="bi bi-chevron-right"></i></a>
                    </li>
                </ul>
            </nav>
            <form action="<?= site_url('ai-call-log') ?>" method="get" id="perPageForm">
                <?php foreach (['date_from', 'date_to', 'feature', 'status'] as $key): ?>
                    <input type="hidden" name="<?= $key ?>" value="<?= esc($filters[$key]) ?>">
                <?php endforeach; ?>
                <select class="form-select form-select-sm" name="per_page" onchange="document.getElementById('perPageForm').submit();" style="width: auto;">
                    <option value="10" <?= $perPage === 10 ? 'selected' : '' ?>>10 per page</option>
                    <option value="25" <?= $perPage === 25 ? 'selected' : '' ?>>25 per page</option>
                    <option value="50" <?= $perPage === 50 ? 'selected' : '' ?>>50 per page</option>
                </select>
            </form>
        </div>
    </div>
    <?php endif; ?>
</div>

<div class="modal fade" id="viewCallModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-robot me-2"></i>AI Call Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body small">
                <p class="mb-2"><strong id="vc-feature"></strong> — <span id="vc-when" class="text-muted"></span></p>
                <div class="mb-2" id="vc-error-wrap" style="display:none;"><div class="alert alert-danger py-2 mb-0" id="vc-error"></div></div>
                <div class="mb-2"><div class="text-muted mb-1">System Prompt</div><pre class="border rounded p-2 bg-light" style="white-space: pre-wrap; max-height: 150px; overflow-y: auto;" id="vc-system"></pre></div>
                <div class="mb-2"><div class="text-muted mb-1">Request Messages</div><pre class="border rounded p-2 bg-light" style="white-space: pre-wrap; max-height: 150px; overflow-y: auto;" id="vc-request"></pre></div>
                <div class="mb-2" id="vc-tools-wrap" style="display:none;"><div class="text-muted mb-1">Tool Calls</div><pre class="border rounded p-2 bg-light" style="white-space: pre-wrap; max-height: 150px; overflow-y: auto;" id="vc-tools"></pre></div>
                <div><div class="text-muted mb-1">Response</div><pre class="border rounded p-2" style="white-space: pre-wrap; max-height: 200px; overflow-y: auto;" id="vc-response"></pre></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('viewCallModal').addEventListener('show.bs.modal', function (event) {
    const btn = event.relatedTarget;
    document.getElementById('vc-feature').textContent = btn.dataset.feature;
    document.getElementById('vc-when').textContent = btn.dataset.when;
    document.getElementById('vc-system').textContent = btn.dataset.system || '(none)';
    document.getElementById('vc-request').textContent = btn.dataset.request || '(none)';
    document.getElementById('vc-response').textContent = btn.dataset.response || '(none)';

    const toolsWrap = document.getElementById('vc-tools-wrap');
    if (btn.dataset.tools) {
        toolsWrap.style.display = '';
        document.getElementById('vc-tools').textContent = btn.dataset.tools;
    } else {
        toolsWrap.style.display = 'none';
    }

    const errorWrap = document.getElementById('vc-error-wrap');
    if (btn.dataset.error) {
        errorWrap.style.display = '';
        document.getElementById('vc-error').textContent = btn.dataset.error;
    } else {
        errorWrap.style.display = 'none';
    }
});
</script>

<?= $this->endSection() ?>
