<?= $this->extend('layout/app') ?>

<?= $this->section('title') ?>Mock Call Logs<?= $this->endSection() ?>
<?= $this->section('pageTitle') ?>Mock Call Logs<?= $this->endSection() ?>

<?= $this->section('content') ?>
<div class="space-y-6">
    <div class="flex flex-wrap items-center justify-between gap-3">
        <div class="flex items-center gap-3 flex-wrap">
            <?php if ($bindingId > 0): ?>
                <?php
                $curBinding = null;
                foreach ($agentBindings as $ab) {
                    if ((int)$ab['id'] === $bindingId) { $curBinding = $ab; break; }
                }
                ?>
                <p class="text-sm text-slate-500">Calls for <span class="font-semibold text-slate-800"><?= esc($curBinding['name'] ?? 'Assistant') ?></span></p>
                <a href="<?= site_url('/agent/mock-call-logs') ?>" class="text-xs font-semibold text-violet-600 hover:text-violet-700">← Show all</a>
            <?php else: ?>
                <p class="text-sm text-slate-500"><?= count($callRows ?? []) ?> total call(s)</p>
            <?php endif; ?>
        </div>
        <a href="<?= site_url('/agent/mock-calls') ?>" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 transition">
            ← Back to Mock Calls
        </a>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="bg-slate-50/70 border-b border-slate-200/60">
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Date</th>
                        <?php if (!empty($user['role']) && $user['role'] === 'admin'): ?>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Agent</th>
                        <?php endif; ?>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Assistant</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Direction</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Phone</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Duration</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Score</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3.5 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php if (empty($callRows)): ?>
                        <tr><td colspan="<?= (!empty($user['role']) && $user['role'] === 'admin') ? 9 : 8 ?>" class="px-6 py-16 text-center">
                            <div class="flex flex-col items-center gap-3">
                                <div class="w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2" /></svg>
                                </div>
                                <p class="text-sm font-medium text-slate-600">No calls yet — go to <a href="<?= site_url('/agent/mock-calls') ?>" class="text-violet-600 font-semibold underline">Mock Calls</a> and click "Sync Calls" after making some test calls.</p>
                            </div>
                        </td></tr>
                    <?php else: ?>
                        <?php foreach ($callRows as $c):
                            $cid = (int)($c['id'] ?? 0);
                            $score = $c['score_pct'] !== null ? (float)$c['score_pct'] : null;
                            $threshold = $c['pass_threshold_pct'] !== null ? (float)$c['pass_threshold_pct'] : 70;
                            $scored = $score !== null;
                            $passed = $scored && $score >= $threshold;
                            $durationSec = (int)($c['duration_seconds'] ?? 0);
                            $durStr = '';
                            if ($durationSec > 0) {
                                $m = (int)($durationSec / 60);
                                $s = $durationSec % 60;
                                $durStr = $m . 'm ' . $s . 's';
                            }
                            $direction = strtolower(trim((string)($c['direction'] ?? 'outbound')));
                            $dirClass = $direction === 'inbound' ? 'bg-sky-100 text-sky-700' : 'bg-indigo-100 text-indigo-700';
                            $dirText = ucfirst($direction);
                            $bindingName = (string)($c['binding_name'] ?? '');
                            $phone = (string)($c['phone_number'] ?? '');
                        ?>
                            <tr class="hover:bg-slate-50/50 transition" id="row-<?= $cid ?>">
                                <td class="px-6 py-4 text-sm text-slate-600"><?= !empty($c['started_at']) ? date('M j, Y H:i', strtotime($c['started_at'])) : '—' ?></td>
                                <?php if (!empty($user['role']) && $user['role'] === 'admin'): ?>
                                <?php $agentName = (string)($c['agent_name'] ?? ''); ?>
                                <td class="px-6 py-4 text-sm font-medium text-slate-700"><?= $agentName !== '' ? esc($agentName) : '<span class="text-slate-400">—</span>' ?></td>
                                <?php endif; ?>
                                <td class="px-6 py-4 text-sm font-medium text-slate-700"><?= $bindingName !== '' ? esc($bindingName) : '—' ?></td>
                                <td class="px-6 py-4"><span class="inline-flex px-2 py-0.5 rounded-lg text-[11px] font-semibold <?= $dirClass ?>"><?= $dirText ?></span></td>
                                <td class="px-6 py-4 text-sm text-slate-600 font-mono"><?= $phone !== '' ? esc($phone) : '—' ?></td>
                                <td class="px-6 py-4 text-sm text-slate-600"><?= $durStr !== '' ? $durStr : '—' ?></td>
                                <td class="px-6 py-4">
                                    <?php if ($scored): ?>
                                        <div class="flex items-center gap-2">
                                            <span class="text-sm font-bold <?= $score >= 70 ? 'text-emerald-600' : ($score >= 50 ? 'text-amber-600' : 'text-rose-600') ?>"><?= number_format($score, 0) ?>%</span>
                                            <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-semibold <?= $passed ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700' ?>">
                                                <?= $passed ? 'PASS' : 'FAIL' ?>
                                            </span>
                                        </div>
                                    <?php else: ?>
                                        <span class="text-sm text-slate-400">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4" id="status-<?= $cid ?>">
                                    <?php if ($scored): ?>
                                        <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-emerald-100 text-emerald-700">Scored</span>
                                    <?php else: ?>
                                        <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-slate-100 text-slate-600">Not Scored</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <button type="button" id="btn-<?= $cid ?>" onclick="scoreOrReview(<?= $cid ?>, <?= $scored ? 'true' : 'false' ?>)" class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[12px] font-semibold bg-violet-50 text-violet-700 hover:bg-violet-100 transition">
                                        <span id="btn-spinner-<?= $cid ?>" class="hidden inline-block w-3.5 h-3.5 border-2 border-violet-300 border-t-violet-600 rounded-full animate-spin"></span>
                                        <span id="btn-icon-<?= $cid ?>">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /></svg>
                                        </span>
                                        <span id="btn-text-<?= $cid ?>"><?= $scored ? 'Review' : 'Score / Review' ?></span>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
async function scoreOrReview(callId, alreadyScored) {
    if (alreadyScored) {
        window.location.href = '<?= site_url('/agent/mock-call-review/') ?>' + callId;
        return;
    }

    const btn = document.getElementById('btn-' + callId);
    const spinner = document.getElementById('btn-spinner-' + callId);
    const iconEl = document.getElementById('btn-icon-' + callId);
    const textEl = document.getElementById('btn-text-' + callId);
    const statusEl = document.getElementById('status-' + callId);

    btn.disabled = true;
    spinner.classList.remove('hidden');
    iconEl.classList.add('hidden');
    textEl.textContent = 'Scoring...';

    const fd = new FormData();
    fd.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');

    try {
        const resp = await fetch('<?= site_url('/agent/mock-call-score/') ?>' + callId, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: fd
        });
        const data = await resp.json();
        if (data.ok || data.already_scored) {
            statusEl.innerHTML = '<span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-emerald-100 text-emerald-700">Scored</span>';
            textEl.textContent = 'Review';
            setTimeout(() => {
                window.location.href = '<?= site_url('/agent/mock-call-review/') ?>' + callId;
            }, 400);
        } else {
            textEl.textContent = 'Error — retry';
            btn.disabled = false;
        }
    } catch (e) {
        textEl.textContent = 'Network error';
        btn.disabled = false;
    } finally {
        spinner.classList.add('hidden');
        iconEl.classList.remove('hidden');
    }
}
</script>
<?= $this->endSection() ?>
