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

$pageTitle = 'Retry Channel Sync';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('retry_table_exists')) {
    function retry_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('retry_flash')) {
    function retry_flash(string $type, string $message): void {
        $_SESSION['channel_retry_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('retry_get_flash')) {
    function retry_get_flash(): array {
        $items = $_SESSION['channel_retry_flash'] ?? [];
        unset($_SESSION['channel_retry_flash']);
        return $items;
    }
}
if (!function_exists('retry_pretty_json')) {
    function retry_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;
    }
}
if (!function_exists('retry_log')) {
    function retry_log(PDO $pdo, ?int $connectionId, string $provider, string $syncType, string $syncDirection, string $status, array $requestPayload, array $responsePayload, string $message): int {
        $stmt = $pdo->prepare("
            INSERT INTO channel_sync_log
            (connection_id, provider, sync_type, sync_direction, status, request_payload, response_payload, message, started_at, completed_at)
            VALUES
            (:connection_id, :provider, :sync_type, :sync_direction, :status, :request_payload, :response_payload, :message, NOW(), NOW())
        ");
        $stmt->execute([
            ':connection_id' => $connectionId ?: null,
            ':provider' => $provider,
            ':sync_type' => $syncType,
            ':sync_direction' => $syncDirection,
            ':status' => $status,
            ':request_payload' => json_encode($requestPayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
            ':response_payload' => json_encode($responsePayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
            ':message' => $message,
        ]);
        return (int)$pdo->lastInsertId();
    }
}
if (!function_exists('retry_stub')) {
    function retry_stub(array $log, array $requestPayload, bool $forceSuccess = false): array {
        $syncType = (string)($log['sync_type'] ?? 'unknown');
        $provider = (string)($log['provider'] ?? 'unknown');

        if ($forceSuccess) {
            return [
                'ok' => true,
                'mode' => 'retry_preview_success',
                'provider' => $provider,
                'sync_type' => $syncType,
                'message' => 'Retry preview completed successfully. No external provider was called.',
            ];
        }

        return [
            'ok' => false,
            'mode' => 'retry_stub',
            'provider' => $provider,
            'sync_type' => $syncType,
            'message' => 'Retry is in safe stub mode. Provider-specific live connector is not configured yet.',
            'original_payload_keys' => array_keys($requestPayload),
        ];
    }
}

$errors = [];
$logId = (int)($_GET['log_id'] ?? $_POST['log_id'] ?? 0);
$log = null;
$connection = null;
$requestPayload = [];
$responsePayload = [];

if (!retry_table_exists($pdo, 'channel_sync_log')) {
    $errors[] = 'channel_sync_log table does not exist.';
}

if ($logId <= 0) {
    $errors[] = 'No log ID supplied.';
}

if (!$errors) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                csl.*,
                cc.connection_name,
                cc.api_base_url,
                cc.external_property_id,
                cc.is_active AS connection_active
            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' => $logId]);
        $log = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$log) {
            throw new RuntimeException('Sync log not found.');
        }

        $requestPayload = json_decode((string)$log['request_payload'], true);
        if (!is_array($requestPayload)) $requestPayload = [];

        $responsePayload = json_decode((string)$log['response_payload'], true);
        if (!is_array($responsePayload)) $responsePayload = [];

    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

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

        if (!$log) {
            throw new RuntimeException('Original log could not be loaded.');
        }

        $mode = (string)($_POST['retry_mode'] ?? 'safe_preview');
        $forceSuccess = $mode === 'safe_preview';
        $allowLive = $mode === 'live_stub';

        /*
         * We keep this safe:
         * - safe_preview always succeeds and logs preview.
         * - live_stub attempts the same action category but still blocks real provider calls.
         */
        $result = retry_stub($log, $requestPayload, $forceSuccess);

        $newStatus = !empty($result['ok']) ? 'success' : 'failed';
        $message = !empty($result['ok'])
            ? 'Retry preview successful. Original log #' . (int)$log['id'] . '.'
            : 'Retry attempted but blocked in safe stub mode. Original log #' . (int)$log['id'] . '.';

        $retryPayload = [
            'retry_of_log_id' => (int)$log['id'],
            'retry_mode' => $mode,
            'original_sync_type' => $log['sync_type'],
            'original_request_payload' => $requestPayload,
        ];

        $newLogId = retry_log(
            $pdo,
            (int)($log['connection_id'] ?? 0),
            (string)($log['provider'] ?? 'unknown'),
            'retry_' . (string)($log['sync_type'] ?? 'unknown'),
            (string)($log['sync_direction'] ?? 'manual'),
            $newStatus,
            $retryPayload,
            $result,
            $message
        );

        if ($newStatus === 'success') {
            retry_flash('success', 'Retry preview logged successfully. New log ID: ' . $newLogId);
        } else {
            retry_flash('warning', 'Retry logged but live provider call is still blocked. New log ID: ' . $newLogId);
        }

        header('Location: channel_retry.php?log_id=' . (int)$newLogId);
        exit;

    } catch (Throwable $e) {
        retry_flash('danger', $e->getMessage());
        header('Location: channel_retry.php?log_id=' . $logId);
        exit;
    }
}

$flashes = retry_get_flash();

function retry_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','preview'], 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-arrow-repeat"></i> Channel Manager</div>
            <div class="hero-title mt-2">Retry Channel Sync</div>
            <div class="hero-subtitle mt-2">
                Safely retry failed channel sync actions and log the new attempt.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="channel_sync_log.php" class="btn btn-light me-2">
                <i class="bi bi-clock-history me-2"></i>Sync Log
            </a>
            <a href="channel_settings.php" class="btn btn-outline-light">
                <i class="bi bi-gear me-2"></i>Settings
            </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; ?>

<?php if ($log): ?>
<div class="alert alert-warning">
    <strong>Safe retry mode:</strong> This file does not call Booking.com, Expedia, Airbnb or NightsBridge directly yet.
    It creates a clean retry log and blocks live calls until provider-specific connectors are added.
</div>

<div class="row g-4">
    <div class="col-xl-8">
        <div class="card panel-card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Original Sync Log #<?php echo (int)$log['id']; ?></h5>
                <span class="badge <?php echo h(retry_badge_class($log['status'])); ?>">
                    <?php echo h(ucwords($log['status'])); ?>
                </span>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-4">
                        <div class="detail-label">Connection</div>
                        <div class="detail-value"><?php echo h($log['connection_name'] ?: 'No connection'); ?></div>
                    </div>
                    <div class="col-md-4">
                        <div class="detail-label">Provider</div>
                        <div class="detail-value"><?php echo h(ucwords(str_replace('_', ' ', $log['provider']))); ?></div>
                    </div>
                    <div class="col-md-4">
                        <div class="detail-label">Type</div>
                        <div class="detail-value"><?php echo h(ucwords(str_replace('_', ' ', $log['sync_type']))); ?></div>
                    </div>
                    <div class="col-md-4">
                        <div class="detail-label">Direction</div>
                        <div class="detail-value"><?php echo h(ucwords($log['sync_direction'])); ?></div>
                    </div>
                    <div class="col-md-4">
                        <div class="detail-label">Started</div>
                        <div class="detail-value"><?php echo h($log['started_at']); ?></div>
                    </div>
                    <div class="col-md-4">
                        <div class="detail-label">Completed</div>
                        <div class="detail-value"><?php echo h($log['completed_at'] ?: 'Not completed'); ?></div>
                    </div>
                </div>

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

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Payloads</h5></div>
            <div class="card-body">
                <div class="row g-4">
                    <div class="col-xl-6">
                        <h6 class="fw-bold">Original Request</h6>
                        <pre class="payload-box"><?php echo h(retry_pretty_json($log['request_payload'])); ?></pre>
                    </div>
                    <div class="col-xl-6">
                        <h6 class="fw-bold">Original Response</h6>
                        <pre class="payload-box"><?php echo h(retry_pretty_json($log['response_payload'])); ?></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Retry Action</h5></div>
            <div class="card-body">
                <form method="post" onsubmit="return confirm('Retry this channel sync action?');">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="log_id" value="<?php echo (int)$log['id']; ?>">

                    <div class="mb-3">
                        <label class="form-label">Retry Mode</label>
                        <select name="retry_mode" class="form-select">
                            <option value="safe_preview">Safe Preview Retry</option>
                            <option value="live_stub">Live Stub Retry</option>
                        </select>
                        <div class="small text-muted mt-1">
                            Safe Preview creates a successful retry log. Live Stub records an attempted provider retry but still blocks real API calls.
                        </div>
                    </div>

                    <button class="btn btn-primary w-100">
                        <i class="bi bi-arrow-repeat me-2"></i>Retry Sync
                    </button>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Retry Routing</h5></div>
            <div class="card-body small">
                <?php
                $syncType = (string)$log['sync_type'];
                $route = 'Unknown';
                if (str_contains($syncType, 'availability')) $route = 'Availability push retry';
                elseif (str_contains($syncType, 'rate')) $route = 'Rate push retry';
                elseif (str_contains($syncType, 'booking_pull')) $route = 'Booking pull retry';
                elseif (str_contains($syncType, 'webhook')) $route = 'Webhook import retry';
                elseif (str_contains($syncType, 'create_reservation')) $route = 'Reservation conversion retry';
                ?>
                <p><strong>Detected route:</strong><br><?php echo h($route); ?></p>
                <p class="text-muted mb-0">
                    Provider-specific live retry logic will be added after the actual OTA connector is approved and configured.
                </p>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

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

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