<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Channel Sync Log';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}

if (!function_exists('log_table_exists')) {
    function log_table_exists(PDO $pdo, string $tableName): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
        ");
        $stmt->execute([':table_name' => $tableName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('log_flash')) {
    function log_flash(string $type, string $message): void {
        $_SESSION['channel_sync_log_flash'][] = ['type' => $type, 'message' => $message];
    }
}

if (!function_exists('log_get_flash')) {
    function log_get_flash(): array {
        $items = $_SESSION['channel_sync_log_flash'] ?? [];
        unset($_SESSION['channel_sync_log_flash']);
        return $items;
    }
}

if (!function_exists('log_pretty_json')) {
    function log_pretty_json(?string $value): string {
        $value = (string)$value;
        if (trim($value) === '') {
            return '';
        }

        $decoded = json_decode($value, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        }

        return $value;
    }
}

$errors = [];

try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS channel_sync_log (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            connection_id INT UNSIGNED NULL,
            provider VARCHAR(50) NOT NULL,
            sync_type VARCHAR(80) NOT NULL,
            sync_direction VARCHAR(30) NOT NULL,
            status VARCHAR(30) NOT NULL,
            request_payload MEDIUMTEXT NULL,
            response_payload MEDIUMTEXT NULL,
            message TEXT NULL,
            started_at DATETIME NOT NULL,
            completed_at DATETIME NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_channel_log_connection (connection_id),
            INDEX idx_channel_log_provider (provider),
            INDEX idx_channel_log_status (status),
            INDEX idx_channel_log_started (started_at)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare channel_sync_log table: ' . $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) {
            verify_csrf();
        }

        $action = (string)($_POST['action'] ?? '');

        if ($action === 'clear_old_logs') {
            $days = max(7, (int)($_POST['days'] ?? 90));
            $stmt = $pdo->prepare("
                DELETE FROM channel_sync_log
                WHERE started_at < DATE_SUB(NOW(), INTERVAL :days DAY)
            ");
            $stmt->bindValue(':days', $days, PDO::PARAM_INT);
            $stmt->execute();

            log_flash('success', $stmt->rowCount() . ' old log record(s) deleted.');
            header('Location: channel_sync_log.php');
            exit;
        }

        if ($action === 'delete_log') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) {
                throw new RuntimeException('Invalid log selected.');
            }

            $stmt = $pdo->prepare("DELETE FROM channel_sync_log WHERE id = :id");
            $stmt->execute([':id' => $id]);

            log_flash('success', 'Log entry deleted.');
            header('Location: channel_sync_log.php');
            exit;
        }

        if ($action === 'mark_reviewed') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) {
                throw new RuntimeException('Invalid log selected.');
            }

            $stmt = $pdo->prepare("
                UPDATE channel_sync_log
                SET status = 'reviewed',
                    message = CONCAT(COALESCE(message,''), '\nReviewed by user at ', NOW())
                WHERE id = :id
            ");
            $stmt->execute([':id' => $id]);

            log_flash('success', 'Log marked as reviewed.');
            header('Location: channel_sync_log.php');
            exit;
        }

    } catch (Throwable $e) {
        log_flash('danger', $e->getMessage());
        header('Location: channel_sync_log.php');
        exit;
    }
}

$connections = [];
try {
    if (log_table_exists($pdo, 'channel_connections')) {
        $connections = $pdo->query("
            SELECT id, connection_name, provider
            FROM channel_connections
            ORDER BY provider ASC, connection_name ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $connections = [];
}

$filterConnectionId = (int)($_GET['connection_id'] ?? 0);
$filterProvider = trim((string)($_GET['provider'] ?? ''));
$filterStatus = trim((string)($_GET['status'] ?? ''));
$filterType = trim((string)($_GET['sync_type'] ?? ''));
$dateFrom = trim((string)($_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'))));
$dateTo = trim((string)($_GET['date_to'] ?? date('Y-m-d')));

if (strtotime($dateFrom) === false) {
    $dateFrom = date('Y-m-d', strtotime('-30 days'));
}
if (strtotime($dateTo) === false) {
    $dateTo = date('Y-m-d');
}

$where = "1=1";
$params = [];

if ($filterConnectionId > 0) {
    $where .= " AND csl.connection_id = :connection_id ";
    $params[':connection_id'] = $filterConnectionId;
}

if ($filterProvider !== '') {
    $where .= " AND csl.provider = :provider ";
    $params[':provider'] = $filterProvider;
}

if ($filterStatus !== '') {
    $where .= " AND csl.status = :status ";
    $params[':status'] = $filterStatus;
}

if ($filterType !== '') {
    $where .= " AND csl.sync_type = :sync_type ";
    $params[':sync_type'] = $filterType;
}

$where .= " AND DATE(csl.started_at) BETWEEN :date_from AND :date_to ";
$params[':date_from'] = $dateFrom;
$params[':date_to'] = $dateTo;

$logs = [];
$summary = [
    'total' => 0,
    'success' => 0,
    'failed' => 0,
    'pending' => 0,
    'reviewed' => 0,
];

try {
    $stmt = $pdo->prepare("
        SELECT
            csl.*,
            cc.connection_name,
            cc.external_property_id
        FROM channel_sync_log csl
        LEFT JOIN channel_connections cc ON cc.id = csl.connection_id
        WHERE $where
        ORDER BY csl.started_at DESC, csl.id DESC
        LIMIT 500
    ");
    $stmt->execute($params);
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($logs as $row) {
        $summary['total']++;
        $status = strtolower((string)$row['status']);
        if (isset($summary[$status])) {
            $summary[$status]++;
        }
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load sync logs: ' . $e->getMessage();
}

$providers = [];
$syncTypes = [];
$statuses = [];

try {
    $providers = $pdo->query("SELECT DISTINCT provider FROM channel_sync_log WHERE provider <> '' ORDER BY provider ASC")->fetchAll(PDO::FETCH_COLUMN);
} catch (Throwable $e) {}

try {
    $syncTypes = $pdo->query("SELECT DISTINCT sync_type FROM channel_sync_log WHERE sync_type <> '' ORDER BY sync_type ASC")->fetchAll(PDO::FETCH_COLUMN);
} catch (Throwable $e) {}

try {
    $statuses = $pdo->query("SELECT DISTINCT status FROM channel_sync_log WHERE status <> '' ORDER BY status ASC")->fetchAll(PDO::FETCH_COLUMN);
} catch (Throwable $e) {}

$viewId = (int)($_GET['view_id'] ?? 0);
$viewLog = null;

if ($viewId > 0) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                csl.*,
                cc.connection_name,
                cc.external_property_id
            FROM channel_sync_log csl
            LEFT JOIN channel_connections cc ON cc.id = csl.connection_id
            WHERE csl.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $viewId]);
        $viewLog = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    } catch (Throwable $e) {
        $viewLog = null;
    }
}

$flashes = log_get_flash();

function log_badge_class(string $status): string {
    $status = strtolower($status);
    if (in_array($status, ['success','ready','sent','imported'], true)) return 'text-bg-success';
    if (in_array($status, ['failed','error','rejected'], true)) return 'text-bg-danger';
    if (in_array($status, ['pending','queued','warning'], true)) return 'text-bg-warning';
    if ($status === 'reviewed') return 'text-bg-info';
    return 'text-bg-secondary';
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-clock-history"></i> Channel Manager</div>
            <div class="hero-title mt-2">Channel Sync Log</div>
            <div class="hero-subtitle mt-2">
                Audit every channel push, pull, import, webhook and provider response from one place.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="channel_settings.php" class="btn btn-light me-2">
                <i class="bi bi-gear me-2"></i>Settings
            </a>
            <a href="channel_mapping.php" class="btn btn-outline-light">
                <i class="bi bi-diagram-3 me-2"></i>Mappings
            </a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?>"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-list-ul"></i></div>
            <div><div class="metric-label">Total Logs</div><div class="metric-value"><?php echo (int)$summary['total']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-check-circle"></i></div>
            <div><div class="metric-label">Success</div><div class="metric-value"><?php echo (int)$summary['success']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-x-octagon"></i></div>
            <div><div class="metric-label">Failed</div><div class="metric-value"><?php echo (int)$summary['failed']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-hourglass-split"></i></div>
            <div><div class="metric-label">Pending</div><div class="metric-value"><?php echo (int)$summary['pending']; ?></div></div>
        </div>
    </div>
</div>

<div class="card panel-card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-3">
                <label class="form-label">Connection</label>
                <select name="connection_id" class="form-select">
                    <option value="0">All connections</option>
                    <?php foreach ($connections as $connection): ?>
                        <option value="<?php echo (int)$connection['id']; ?>" <?php echo $filterConnectionId === (int)$connection['id'] ? 'selected' : ''; ?>>
                            <?php echo h($connection['connection_name']); ?> - <?php echo h($connection['provider']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Provider</label>
                <select name="provider" class="form-select">
                    <option value="">All</option>
                    <?php foreach ($providers as $provider): ?>
                        <option value="<?php echo h($provider); ?>" <?php echo $filterProvider === $provider ? 'selected' : ''; ?>>
                            <?php echo h(ucwords(str_replace('_', ' ', $provider))); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Sync Type</label>
                <select name="sync_type" class="form-select">
                    <option value="">All</option>
                    <?php foreach ($syncTypes as $type): ?>
                        <option value="<?php echo h($type); ?>" <?php echo $filterType === $type ? 'selected' : ''; ?>>
                            <?php echo h(ucwords(str_replace('_', ' ', $type))); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Status</label>
                <select name="status" class="form-select">
                    <option value="">All</option>
                    <?php foreach ($statuses as $status): ?>
                        <option value="<?php echo h($status); ?>" <?php echo $filterStatus === $status ? 'selected' : ''; ?>>
                            <?php echo h(ucwords($status)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-1">
                <label class="form-label">From</label>
                <input type="date" name="date_from" class="form-control" value="<?php echo h($dateFrom); ?>">
            </div>

            <div class="col-md-1">
                <label class="form-label">To</label>
                <input type="date" name="date_to" class="form-control" value="<?php echo h($dateTo); ?>">
            </div>

            <div class="col-md-1 d-grid">
                <button class="btn btn-primary"><i class="bi bi-funnel"></i></button>
            </div>
        </form>
    </div>
</div>

<?php if ($viewLog): ?>
<div class="card panel-card mb-4 border-primary">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Log Detail #<?php echo (int)$viewLog['id']; ?></h5>
        <a href="channel_sync_log.php" class="btn btn-sm btn-outline-secondary">Close</a>
    </div>
    <div class="card-body">
        <div class="row g-3 mb-3">
            <div class="col-md-3">
                <div class="detail-label">Connection</div>
                <div class="detail-value"><?php echo h($viewLog['connection_name'] ?: 'No connection'); ?></div>
            </div>
            <div class="col-md-3">
                <div class="detail-label">Provider</div>
                <div class="detail-value"><?php echo h($viewLog['provider']); ?></div>
            </div>
            <div class="col-md-3">
                <div class="detail-label">Type</div>
                <div class="detail-value"><?php echo h($viewLog['sync_type']); ?></div>
            </div>
            <div class="col-md-3">
                <div class="detail-label">Status</div>
                <span class="badge <?php echo h(log_badge_class($viewLog['status'])); ?>"><?php echo h(ucwords($viewLog['status'])); ?></span>
            </div>
        </div>

        <div class="mb-3">
            <div class="detail-label">Message</div>
            <div class="p-3 rounded bg-light border"><?php echo nl2br(h($viewLog['message'] ?: 'No message')); ?></div>
        </div>

        <div class="row g-4">
            <div class="col-xl-6">
                <h6 class="fw-bold">Request Payload</h6>
                <pre class="payload-box"><?php echo h(log_pretty_json($viewLog['request_payload'])); ?></pre>
            </div>
            <div class="col-xl-6">
                <h6 class="fw-bold">Response Payload</h6>
                <pre class="payload-box"><?php echo h(log_pretty_json($viewLog['response_payload'])); ?></pre>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-xl-9">
        <div class="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Sync Activity</h5>
                <span class="text-muted small">Showing latest 500 matching records</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Time</th>
                            <th>Connection</th>
                            <th>Provider</th>
                            <th>Type</th>
                            <th>Direction</th>
                            <th>Status</th>
                            <th>Message</th>
                            <th class="text-end">Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$logs): ?>
                            <tr><td colspan="8" class="text-center text-muted py-4">No sync logs found.</td></tr>
                        <?php else: ?>
                            <?php foreach ($logs as $row): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo h($row['started_at']); ?></strong>
                                        <div class="small text-muted">
                                            <?php echo $row['completed_at'] ? 'Done: ' . h($row['completed_at']) : 'Not completed'; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <?php echo h($row['connection_name'] ?: 'No connection'); ?>
                                        <div class="small text-muted"><?php echo h($row['external_property_id'] ?: ''); ?></div>
                                    </td>
                                    <td><?php echo h(ucwords(str_replace('_', ' ', $row['provider']))); ?></td>
                                    <td><?php echo h(ucwords(str_replace('_', ' ', $row['sync_type']))); ?></td>
                                    <td><?php echo h(ucwords(str_replace('_', ' ', $row['sync_direction']))); ?></td>
                                    <td>
                                        <span class="badge <?php echo h(log_badge_class($row['status'])); ?>">
                                            <?php echo h(ucwords($row['status'])); ?>
                                        </span>
                                    </td>
                                    <td class="small text-muted log-message">
                                        <?php echo h(mb_strimwidth((string)$row['message'], 0, 110, '...')); ?>
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm">
                                            <a href="channel_sync_log.php?view_id=<?php echo (int)$row['id']; ?>" class="btn btn-outline-primary" title="View">
                                                <i class="bi bi-eye"></i>
                                            </a>

                                            <?php if (strtolower((string)$row['status']) === 'failed'): ?>
                                                <a href="channel_retry.php?log_id=<?php echo (int)$row['id']; ?>" class="btn btn-outline-warning" title="Retry">
                                                    <i class="bi bi-arrow-repeat"></i>
                                                </a>
                                            <?php endif; ?>

                                            <form method="post" class="d-inline">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="mark_reviewed">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                <button class="btn btn-outline-info" title="Mark Reviewed">
                                                    <i class="bi bi-check2-square"></i>
                                                </button>
                                            </form>

                                            <form method="post" class="d-inline" onsubmit="return confirm('Delete this log entry?');">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="delete_log">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                <button class="btn btn-outline-danger" title="Delete">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Maintenance</h5></div>
            <div class="card-body">
                <form method="post" onsubmit="return confirm('Delete old channel logs?');">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="clear_old_logs">
                    <label class="form-label">Delete logs older than</label>
                    <select name="days" class="form-select mb-3">
                        <option value="30">30 days</option>
                        <option value="60">60 days</option>
                        <option value="90" selected>90 days</option>
                        <option value="180">180 days</option>
                        <option value="365">1 year</option>
                    </select>
                    <button class="btn btn-outline-danger w-100">
                        <i class="bi bi-trash me-2"></i>Clean Old Logs
                    </button>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Next Sync Files</h5></div>
            <div class="card-body">
                <div class="small text-muted mb-3">
                    These will be built after the log screen:
                </div>
                <div class="list-group list-group-flush">
                    <div class="list-group-item px-0">channel_push_availability.php</div>
                    <div class="list-group-item px-0">channel_push_rates.php</div>
                    <div class="list-group-item px-0">channel_pull_bookings.php</div>
                    <div class="list-group-item px-0">channel_webhook.php</div>
                    <div class="list-group-item px-0">channel_retry.php</div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.detail-label{
    font-size:.75rem;
    text-transform:uppercase;
    letter-spacing:.06em;
    color:#64748b;
    font-weight:800;
}
.detail-value{
    font-weight:800;
    color:#111827;
}
.payload-box{
    background:#0f172a;
    color:#e5e7eb;
    border-radius:16px;
    padding:16px;
    max-height:420px;
    overflow:auto;
    font-size:12px;
}
.log-message{
    max-width:260px;
}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
