<?php
require_once __DIR__ . '/inc/layout.php';
require_once __DIR__ . '/inc/utils.php';
require_once __DIR__ . '/inc/parsers.php';

require_login();

$config = require __DIR__ . '/config/config.php';
date_default_timezone_set($config['timezone'] ?? 'UTC');

$logs = $config['logs'] ?? [];
$log = $_GET['log'] ?? 'merged';
if (!isset($logs[$log])) $log = 'merged';

$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = max(10, min(200, (int)($_GET['per_page'] ?? ($config['per_page'] ?? 50))));

$range = $_GET['range'] ?? '24h';
$today = date('Y-m-d');

$date_from = trim($_GET['date_from'] ?? '');
$date_to   = trim($_GET['date_to'] ?? '');

if ($range === 'today') {
    $date_from = $today;
    $date_to = $today;
} elseif ($range === '7d') {
    $date_from = date('Y-m-d', strtotime('-6 days'));
    $date_to = $today;
} elseif ($range === 'custom') {
} else {
    $range = '24h';
    $date_from = date('Y-m-d', strtotime('-1 day'));
    $date_to = $today;
}

$filters = [
    'date_from' => $date_from,
    'date_to'   => $date_to,
    'caller'    => trim($_GET['caller'] ?? ''),
    'zip'       => trim($_GET['zip'] ?? ''),
    'vertical'  => trim($_GET['vertical'] ?? ''),
    'callsid'   => trim($_GET['callsid'] ?? ''),
];

$total = 0;
$rows = [];

if ($log === 'merged') {
    $rows = read_merged_rows(
        [
            'sd' => $logs['sd']['path'] ?? null,
            'twilio' => $logs['twilio']['path'] ?? null,
        ],
        $filters,
        $page,
        $per_page,
        $total
    );
} else {
    $rows = read_log_rows(
        $logs[$log]['type'] ?? $log,
        $logs[$log]['path'] ?? null,
        $filters,
        $page,
        $per_page,
        $total
    );
}

$total_pages = max(1, (int)ceil($total / $per_page));

foreach ($rows as &$r) {
    if ($log === 'merged') {
        $verticalKey = normalize_vertical_from_service_category(
            $r['sd_vertical'] ?? '',
            $r['tw_vertical'] ?? ''
        );
    } elseif ($log === 'sd') {
        $verticalKey = normalize_vertical_from_service_category(
            $r['service_category'] ?? '',
            $r['service_category'] ?? ''
        );
    } else {
        $verticalKey = normalize_vertical_from_service_category(
            '',
            $r['vertical'] ?? ''
        );
    }

    $rule = bid_rule_for_vertical($verticalKey);
    $r['_rule_enabled'] = $rule['enabled'];
    $r['_rule_bid'] = $rule['min_bid'];
    $r['_decision'] = routing_decision_label($r);
}
unset($r);

function qs(array $extra = []): string {
    $q = array_merge($_GET, $extra);
    return http_build_query($q);
}

function zval(array $row, array $keys): string {
    foreach ($keys as $key) {
        if (isset($row[$key]) && trim((string)$row[$key]) !== '') {
            return trim((string)$row[$key]);
        }
    }
    return '';
}

function zip_source_label(string $source): string {
    $source = trim($source);

    $labels = [
        'IVR' => 'IVR',
        'CACHED' => 'Cached',
        'TWILIO' => 'Twilio',
        'TWILIO_FALLBACK' => 'Twilio Fallback',
        'TWILIO_RETRY' => 'Twilio Retry',
        'TWILIO_RETRY_SUCCESS' => 'Twilio Retry Success',
        'TWILIO_RETRY_FAILED' => 'Twilio Retry Failed',
        'TWILIO_RETRY_HTTP_FAILED' => 'Twilio Retry HTTP Failed',
        'FAILED' => 'Failed',
        'UNKNOWN' => 'Unknown',
    ];

    return $labels[$source] ?? $source;
}

function zip_source_badge_html(string $source): string {
    $source = trim($source);

    if ($source === '') {
        return '<span class="pill-badge pill-off">—</span>';
    }

    $label = h(zip_source_label($source));

    if (strpos($source, 'SUCCESS') !== false || $source === 'IVR') {
        return '<span class="pill-badge pill-on">' . $label . '</span>';
    }

    if (strpos($source, 'FAILED') !== false || $source === 'FAILED') {
        return '<span class="pill-badge pill-off">' . $label . '</span>';
    }

    if (strpos($source, 'TWILIO') !== false) {
        return '<span class="pill-badge pill-on">' . $label . '</span>';
    }

    return '<span class="pill-badge pill-off">' . $label . '</span>';
}

page_header('View Logs');
?>

<div class="d-flex flex-wrap gap-2 mb-3">
    <?php foreach ($logs as $k => $v): ?>
        <a class="btn <?= $k === $log ? 'btn-primary' : 'btn-outline-secondary' ?>" href="?<?= qs(['log' => $k, 'page' => 1]) ?>">
            <?= h($v['label']) ?>
        </a>
    <?php endforeach; ?>

    <a class="btn btn-outline-dark ms-md-auto" href="dashboard.php">Back to Dashboard</a>
    <a class="btn btn-outline-success" href="bid-control/index.php">Minimum Bid Control</a>
    <a class="btn btn-outline-primary" href="/common_zip/admin/zip_switch_admin.php">ZIP Switch</a>
</div>

<div class="card soft-card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3">
            <input type="hidden" name="log" value="<?= h($log) ?>">

            <div class="col-12 col-md-3">
                <label class="form-label">Quick Range</label>
                <select class="form-select" name="range" id="rangeSelect">
                    <option value="24h" <?= $range==='24h'?'selected':'' ?>>Last 24 hours</option>
                    <option value="today" <?= $range==='today'?'selected':'' ?>>Today</option>
                    <option value="7d" <?= $range==='7d'?'selected':'' ?>>Last 7 days</option>
                    <option value="custom" <?= $range==='custom'?'selected':'' ?>>Custom</option>
                </select>
            </div>

            <div class="col-6 col-md-2 custom-range" <?= $range !== 'custom' ? 'style="display:none;"' : '' ?>>
                <label class="form-label">Date From</label>
                <input type="date" class="form-control" name="date_from" value="<?= h($filters['date_from']) ?>">
            </div>

            <div class="col-6 col-md-2 custom-range" <?= $range !== 'custom' ? 'style="display:none;"' : '' ?>>
                <label class="form-label">Date To</label>
                <input type="date" class="form-control" name="date_to" value="<?= h($filters['date_to']) ?>">
            </div>

            <div class="col-6 col-md-2">
                <label class="form-label">Vertical</label>
                <input type="text" class="form-control" name="vertical" value="<?= h($filters['vertical']) ?>" placeholder="plumbing">
            </div>

            <div class="col-6 col-md-2">
                <label class="form-label">Caller</label>
                <input type="text" class="form-control" name="caller" value="<?= h($filters['caller']) ?>" placeholder="+1...">
            </div>

            <div class="col-4 col-md-1">
                <label class="form-label">ZIP</label>
                <input type="text" class="form-control" name="zip" value="<?= h($filters['zip']) ?>" placeholder="30303">
            </div>

            <div class="col-8 col-md-3">
                <label class="form-label">CallSid</label>
                <input type="text" class="form-control mono" name="callsid" value="<?= h($filters['callsid']) ?>" placeholder="CA...">
            </div>

            <div class="col-4 col-md-2">
                <label class="form-label">Per Page</label>
                <input type="number" class="form-control" name="per_page" value="<?= (int)$per_page ?>" min="10" max="200">
            </div>

            <div class="col-8 col-md-7 d-flex align-items-end gap-2 flex-wrap">
                <button class="btn btn-primary" type="submit">Show Logs</button>
                <a class="btn btn-outline-secondary" href="view.php?log=<?= h($log) ?>&range=24h">Reset</a>
                <span class="text-muted small ms-md-auto">Total: <?= (int)$total ?> | Page <?= (int)$page ?> / <?= (int)$total_pages ?></span>
            </div>
        </form>
    </div>
</div>

<div class="card soft-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                <?php if ($log === 'merged'): ?>
                    <tr>
                        <th>CallSid</th>
                        <th>TW Time</th>
                        <th>From</th>
                        <th>TW Vertical</th>
                        <th>SD Time</th>
                        <th>ZIP</th>
                        <th>ZIP Source</th>
                        <th>Twilio ZIP</th>
                        <th>SD Category</th>
                        <th>Bid</th>
                        <th>Threshold</th>
                        <th>Decision</th>
                        <th>Buyer</th>
                        <th>Request</th>
                        <th>Dial To</th>
                        <th>Events</th>
                    </tr>
                <?php elseif ($log === 'sd'): ?>
                    <tr>
                        <th>Time</th>
                        <th>Event</th>
                        <th>CallSid</th>
                        <th>Caller</th>
                        <th>ZIP</th>
                        <th>ZIP Source</th>
                        <th>Twilio ZIP</th>
                        <th>Category</th>
                        <th>Bid</th>
                        <th>Threshold</th>
                        <th>Decision</th>
                        <th>Buyer</th>
                        <th>Request</th>
                    </tr>
                <?php else: ?>
                    <tr>
                        <th>Time</th>
                        <th>Event</th>
                        <th>CallSid</th>
                        <th>From</th>
                        <th>To</th>
                        <th>Vertical</th>
                        <th>Step</th>
                        <th>Digits</th>
                        <th>ZIP Source</th>
                        <th>Twilio ZIP</th>
                        <th class="threshold-col">Current Threshold</th>
                    </tr>
                <?php endif; ?>
                </thead>

                <tbody>
                <?php if (!$rows): ?>
                    <tr><td colspan="20" class="text-muted">No rows found.</td></tr>
                <?php endif; ?>

                <?php foreach ($rows as $r): ?>
                    <?php if ($log === 'merged'): ?>
                        <?php
                            $zipSource = zval($r, ['zip_source', 'sd_zip_source', 'tw_zip_source']);
                            $twilioZip = zval($r, ['twilio_zip', 'sd_twilio_zip', 'tw_twilio_zip']);
                        ?>
                        <tr>
                            <td class="mono"><?= h($r['callSid'] ?? '') ?></td>
                            <td class="mono"><?= h($r['tw_ts'] ?? '') ?></td>
                            <td class="mono"><?= h($r['from'] ?? '') ?></td>
                            <td><?= h($r['tw_vertical'] ?? '') ?></td>
                            <td class="mono"><?= h($r['sd_ts'] ?? '') ?></td>
                            <td class="mono"><?= h($r['zip'] ?? '') ?></td>
                            <td><?= zip_source_badge_html($zipSource) ?></td>
                            <td class="mono"><?= h($twilioZip !== '' ? $twilioZip : '—') ?></td>
                            <td><?= h($r['sd_vertical'] ?? '') ?></td>
                            <td class="mono"><?= h($r['bid'] ?? '') ?></td>
                            <td>
                                <?php if (!$r['_rule_enabled']): ?>
                                    <span class="pill-badge pill-off">Off</span>
                                <?php else: ?>
                                    <span class="pill-badge pill-on">$<?= number_format((float)$r['_rule_bid'], 2) ?></span>
                                <?php endif; ?>
                            </td>
                            <td><?= h($r['_decision']) ?></td>
                            <td class="mono"><?= h($r['buyer_id'] ?? '') ?></td>
                            <td class="mono"><?= h($r['request_id'] ?? '') ?></td>
                            <td class="mono"><?= h($r['dial_to'] ?? '') ?></td>
                            <td class="small">
                                <div><strong>TW:</strong> <?= h($r['tw_events'] ?? '') ?></div>
                                <div><strong>SD:</strong> <?= h($r['sd_events'] ?? '') ?></div>
                            </td>
                        </tr>
                    <?php elseif ($log === 'sd'): ?>
                        <?php
                            $zipSource = zval($r, ['zip_source']);
                            $twilioZip = zval($r, ['twilio_zip']);
                        ?>
                        <tr>
                            <td class="mono"><?= h($r['ts'] ?? '') ?></td>
                            <td><?= h($r['event'] ?? '') ?></td>
                            <td class="mono"><?= h($r['callSid'] ?? '') ?></td>
                            <td class="mono"><?= h($r['caller_id'] ?? '') ?></td>
                            <td class="mono"><?= h($r['zip_code'] ?? '') ?></td>
                            <td><?= zip_source_badge_html($zipSource) ?></td>
                            <td class="mono"><?= h($twilioZip !== '' ? $twilioZip : '—') ?></td>
                            <td><?= h($r['service_category'] ?? '') ?></td>
                            <td class="mono"><?= h($r['bid'] ?? '') ?></td>
                            <td>
                                <?php if (!$r['_rule_enabled']): ?>
                                    <span class="pill-badge pill-off">Off</span>
                                <?php else: ?>
                                    <span class="pill-badge pill-on">$<?= number_format((float)$r['_rule_bid'], 2) ?></span>
                                <?php endif; ?>
                            </td>
                            <td><?= h($r['_decision']) ?></td>
                            <td class="mono"><?= h($r['buyer_id'] ?? '') ?></td>
                            <td class="mono"><?= h($r['request_id'] ?? '') ?></td>
                        </tr>
                    <?php else: ?>
                        <?php
                            $zipSource = zval($r, ['zip_source']);
                            $twilioZip = zval($r, ['twilio_zip']);
                        ?>
                        <tr>
                            <td class="mono"><?= h($r['ts'] ?? '') ?></td>
                            <td><?= h($r['event'] ?? '') ?></td>
                            <td class="mono"><?= h($r['callSid'] ?? '') ?></td>
                            <td class="mono"><?= h($r['from'] ?? '') ?></td>
                            <td class="mono"><?= h($r['to'] ?? '') ?></td>
                            <td><?= h($r['vertical'] ?? '') ?></td>
                            <td><?= h($r['step'] ?? '') ?></td>
                            <td class="mono"><?= h($r['digits'] ?? '') ?></td>
                            <td><?= zip_source_badge_html($zipSource) ?></td>
                            <td class="mono"><?= h($twilioZip !== '' ? $twilioZip : '—') ?></td>
                            <td class="threshold-col">
                                <?php if (!$r['_rule_enabled']): ?>
                                    <span class="pill-badge pill-off">Off</span>
                                <?php else: ?>
                                    <span class="pill-badge pill-on">$<?= number_format((float)$r['_rule_bid'], 2) ?></span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="d-flex justify-content-end gap-2 mt-3 flex-wrap">
            <?php if ($page > 1): ?>
                <a class="btn btn-outline-secondary" href="?<?= qs(['page' => $page - 1]) ?>">Prev</a>
            <?php endif; ?>
            <?php if ($page < $total_pages): ?>
                <a class="btn btn-outline-secondary" href="?<?= qs(['page' => $page + 1]) ?>">Next</a>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.getElementById('rangeSelect')?.addEventListener('change', function () {
    const show = this.value === 'custom';
    document.querySelectorAll('.custom-range').forEach(el => {
        el.style.display = show ? '' : 'none';
    });
});
</script>

<?php page_footer(); ?>