<?php
session_start();
require_once 'config.php';

if (!isset($_SESSION['agent_id']) && !isset($_SESSION['admin_id']) && !isset($_SESSION['is_admin_logged_in'])) {
    header('Location: login.php');
    exit;
}

@require_once __DIR__ . '/bot_token.php';

function e(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function formatDateSafe(?string $value): string {
    if (!$value || $value === '0000-00-00 00:00:00') return '—';
    $ts = strtotime($value);
    return $ts ? date('d M Y, h:i A', $ts) : $value;
}

function formatStatusLabel(string $status): string {
    return ucwords(strtolower(str_replace('_', ' ', trim($status))));
}

function statusBadgeClass(string $status): string {
    return match (strtoupper(trim($status))) {
        'PENDING_REVIEW' => 'bg-primary-subtle text-primary',
        'UNDER_REVIEW' => 'bg-info-subtle text-info-emphasis',
        'ADDITIONAL_INFO_REQUIRED' => 'bg-warning-subtle text-warning-emphasis',
        'APPROVED' => 'bg-success-subtle text-success-emphasis',
        'REJECTED' => 'bg-danger-subtle text-danger-emphasis',
        'CANCELLED' => 'bg-dark-subtle text-dark',
        default => 'bg-light text-dark',
    };
}

function dbMode(): string {
    global $pdo, $conn;
    if (isset($pdo) && $pdo instanceof PDO) return 'pdo';
    if (isset($conn) && $conn instanceof mysqli) return 'mysqli';
    die('Database connection not available in config.php');
}

function dbFetchAllRows(string $sql, array $params = []): array {
    global $pdo, $conn;
    if (dbMode() === 'pdo') {
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    $stmt = $conn->prepare($sql);
    if (!$stmt) return [];
    if ($params) {
        $types = '';
        $bind = [];
        foreach ($params as $p) {
            $types .= is_int($p) ? 'i' : 's';
            $bind[] = $p;
        }
        $stmt->bind_param($types, ...$bind);
    }
    $stmt->execute();
    $res = $stmt->get_result();
    $rows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
    $stmt->close();
    return $rows;
}

function dbFetchOneRow(string $sql, array $params = []): ?array {
    $rows = dbFetchAllRows($sql, $params);
    return $rows[0] ?? null;
}

function dbExecuteStatement(string $sql, array $params = []): bool {
    global $pdo, $conn;
    if (dbMode() === 'pdo') {
        $stmt = $pdo->prepare($sql);
        return $stmt->execute($params);
    }
    $stmt = $conn->prepare($sql);
    if (!$stmt) return false;
    if ($params) {
        $types = '';
        $bind = [];
        foreach ($params as $p) {
            $types .= is_int($p) ? 'i' : 's';
            $bind[] = $p;
        }
        $stmt->bind_param($types, ...$bind);
    }
    $ok = $stmt->execute();
    $stmt->close();
    return $ok;
}


function dbFetchOneValue(string $sql, array $params = []): mixed {
    $row = dbFetchOneRow($sql, $params);
    if (!$row) return null;
    return array_values($row)[0] ?? null;
}

function columnExists(string $table, string $column): bool {
    static $cache = [];
    $key = $table . '.' . $column;
    if (array_key_exists($key, $cache)) return $cache[$key];
    $exists = dbFetchOneValue("SELECT COUNT(*) AS cnt FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?", [$table, $column]);
    $cache[$key] = ((int)$exists > 0);
    return $cache[$key];
}

function verificationTelegramSelectSql(): string {
    $parts = [];
    if (columnExists('bot_int_transfer_verifications', 'telegram_chat_id')) {
        $parts[] = "v.telegram_chat_id";
    } else {
        $parts[] = "'' AS telegram_chat_id";
    }
    if (columnExists('bot_int_transfer_verifications', 'telegram_user_id')) {
        $parts[] = "v.telegram_user_id";
    } else {
        $parts[] = "'' AS telegram_user_id";
    }
    if (columnExists('bot_int_transfer_verifications', 'telegram_username')) {
        $parts[] = "v.telegram_username";
    } else {
        $parts[] = "'' AS telegram_username";
    }
    return ', ' . implode(', ', $parts);
}

function fetchVerificationRowById(int $id): ?array {
    return dbFetchOneRow(
        "SELECT v.*, u.name AS user_name, u.email AS user_email, u.mobile AS user_mobile" . verificationTelegramSelectSql() . "
"
        . " FROM bot_int_transfer_verifications v
"
        . " LEFT JOIN users u ON u.id = v.user_id
"
        . " WHERE v.id = ? LIMIT 1",
        [$id]
    );
}

function customerTelegramChatId(array $row): string {
    foreach (['telegram_chat_id', 'telegram_user_id'] as $key) {
        $value = trim((string)($row[$key] ?? ''));
        if ($value !== '') return $value;
    }
    return '';
}

function customerTelegramIdentitySummary(array $row): string {
    $chatId = trim((string)($row['telegram_chat_id'] ?? ''));
    $userId = trim((string)($row['telegram_user_id'] ?? ''));
    $username = trim((string)($row['telegram_username'] ?? ''));

    $parts = [];
    if ($chatId !== '') $parts[] = 'Chat ID: ' . $chatId;
    if ($userId !== '') $parts[] = 'User ID: ' . $userId;
    if ($username !== '') $parts[] = 'Username: @' . ltrim($username, '@');

    return $parts ? implode(' | ', $parts) : '—';
}

function dataRow(string $label, string $value): void {
    echo '<div class="data-row"><div class="data-label">' . e($label) . '</div><div class="data-value">' . e($value) . '</div></div>';
}

function maskDocumentNumber(?string $value): string {
    $value = trim((string)$value);
    if ($value === '') return '—';
    $len = strlen($value);
    if ($len <= 4) return str_repeat('*', max(0, $len - 1)) . substr($value, -1);
    return str_repeat('*', max(0, $len - 4)) . substr($value, -4);
}

function normalizeServerPreviewPath(?string $path): ?string {
    $path = trim((string)$path);
    if ($path === '') return null;
    if (preg_match('~^https?://~i', $path)) return $path;
    $publicPath = str_replace('\\', '/', $path);
    if (str_starts_with($publicPath, __DIR__)) {
        $publicPath = substr($publicPath, strlen(__DIR__));
    }
    if (!str_starts_with($publicPath, '/')) {
        $publicPath = '/' . ltrim($publicPath, '/');
    }
    return $publicPath;
}

function previewType(?string $path, string $title): string {
    $path = strtolower((string)$path);
    $title = strtolower($title);
    if (str_contains($title, 'video') || preg_match('/\.(mp4|mov|webm|m4v|3gp)$/', $path)) return 'video';
    if (preg_match('/\.(jpg|jpeg|png|gif|webp)$/', $path)) return 'image';
    return 'other';
}

function telegramApiToken(): string {
    global $token;
    if (isset($token) && trim((string)$token) !== '') {
        return trim((string)$token);
    }
    return '';
}

function sendTelegramMessageToCustomer(string $chatId, string $message, ?array $replyMarkup = null): array {
    $token = telegramApiToken();
    if ($token === '') {
        return ['ok' => false, 'error' => 'Telegram bot token not available.'];
    }

    $payload = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true,
    ];
    if ($replyMarkup) {
        $payload['reply_markup'] = json_encode($replyMarkup, JSON_UNESCAPED_UNICODE);
    }

    $ch = curl_init("https://api.telegram.org/bot{$token}/sendMessage");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_TIMEOUT => 30,
    ]);
    $response = curl_exec($ch);
    $curlErr = curl_error($ch);
    $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($response === false) {
        return ['ok' => false, 'error' => 'cURL error: ' . $curlErr];
    }

    $decoded = json_decode($response, true);
    if ($httpCode !== 200 || !is_array($decoded) || empty($decoded['ok'])) {
        return ['ok' => false, 'error' => $decoded['description'] ?? ('Telegram API HTTP ' . $httpCode)];
    }

    return ['ok' => true];
}

function buildCustomerStatusMessage(array $row, string $status, string $officerMessage, string $reviewedBy): string {
    $customerName = trim((string)($row['full_name'] ?: $row['user_name'] ?: 'Customer'));
    $reference = trim((string)($row['reference_code'] ?? '—'));
    $statusLabel = formatStatusLabel($status);
    $serviceEnabled = (int)($row['service_enabled'] ?? 0) === 1;

    $headline = match ($status) {
        'APPROVED' => '✅ <b>International Transfer Verification Approved</b>',
        'REJECTED' => '❌ <b>International Transfer Verification Not Approved</b>',
        'ADDITIONAL_INFO_REQUIRED' => '📌 <b>Additional Information / Re-Upload Required</b>',
        'UNDER_REVIEW' => '🔎 <b>Verification Under Review</b>',
        'CANCELLED' => '⛔ <b>Verification Request Cancelled</b>',
        default => '📄 <b>Verification Status Update</b>',
    };

    $serviceLine = $serviceEnabled
        ? "<b>Service Access:</b> International Transfer service has been enabled on your account.\n"
        : "<b>Service Access:</b> International Transfer service is currently not enabled on your account.\n";

    $defaultMessage = match ($status) {
        'APPROVED' => 'We are pleased to inform you that your International Transfer verification request has been approved successfully. You may now proceed to use International Transfer services through your FinoviaPay Telegram banking channel, subject to your available account limits and applicable service controls.',
        'REJECTED' => 'We regret to inform you that your International Transfer verification request could not be approved at this time. Kindly review the officer remarks below carefully. You may submit a fresh verification request once the required corrections have been completed.',
        'ADDITIONAL_INFO_REQUIRED' => 'Your verification request has been reviewed and additional information is required before we can proceed further. Please review the officer remarks below carefully and complete the requested re-upload / correction at the earliest convenience.',
        'UNDER_REVIEW' => 'Your verification request has been received successfully and is currently under review by our Compliance Department. You will be notified once the review process has been completed.',
        'CANCELLED' => 'Your International Transfer verification request has been marked as cancelled. If this was not expected, please contact FinoviaPay Customer Care for assistance.',
        default => 'Your International Transfer verification request has been updated. Please review the latest status and officer remarks below.',
    };

    $officerMessage = trim($officerMessage) !== '' ? trim($officerMessage) : $defaultMessage;

    return $headline . "\n\n"
        . 'Dear <b>' . e($customerName) . "</b>,\n\n"
        . '<b>Reference ID:</b> ' . e($reference) . "\n"
        . '<b>Current Status:</b> ' . e($statusLabel) . "\n"
        . $serviceLine . "\n"
        . e($officerMessage) . "\n\n"
        . '<b>Reviewed By:</b> ' . e($reviewedBy) . "\n"
        . '<b>Support Note:</b> If you require any assistance, please contact FinoviaPay Customer Care through the Telegram banking desk and quote your reference ID above.' . "\n\n"
        . '— <b>FinoviaPay Compliance Department</b>\nWorldwide Digital Internet Banking';
}

$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
if ($id <= 0) die('Invalid verification request ID.');

$successMsg = '';
$errorMsg = '';
$warningMsg = '';

$row = fetchVerificationRowById($id);
if (!$row) die('Verification request not found.');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_verification'])) {
    $newStatus = trim((string)($_POST['status'] ?? ''));
    $adminNotes = trim((string)($_POST['admin_notes'] ?? ''));
    $officerMessage = trim((string)($_POST['officer_message'] ?? ''));
    $notifyCustomer = isset($_POST['notify_customer']) ? 1 : 0;
    $serviceEnabled = isset($_POST['service_enabled']) ? 1 : 0;
    $reviewedBy = (string)($_SESSION['agent_name'] ?? $_SESSION['admin_name'] ?? $_SESSION['username'] ?? 'Admin Officer');

    $allowed = ['PENDING_REVIEW','UNDER_REVIEW','ADDITIONAL_INFO_REQUIRED','APPROVED','REJECTED','CANCELLED'];
    if (!in_array($newStatus, $allowed, true)) {
        $errorMsg = 'Invalid status selected.';
    } else {
        if ($newStatus === 'APPROVED') {
            $serviceEnabled = 1;
        }
        if (in_array($newStatus, ['REJECTED', 'ADDITIONAL_INFO_REQUIRED', 'CANCELLED', 'PENDING_REVIEW', 'UNDER_REVIEW'], true) && !isset($_POST['service_enabled'])) {
            $serviceEnabled = 0;
        }

        $historyRemarks = trim($adminNotes);
        if ($officerMessage !== '') {
            $historyRemarks .= ($historyRemarks !== '' ? "\n\n" : '') . 'Customer Message: ' . $officerMessage;
        }
        if ($historyRemarks === '') {
            $historyRemarks = 'Status updated from officer review panel.';
        }

        $ok = dbExecuteStatement(
            "UPDATE bot_int_transfer_verifications SET status = ?, service_enabled = ?, admin_notes = ?, reviewed_by = ?, reviewed_at = NOW() WHERE id = ? LIMIT 1",
            [$newStatus, $serviceEnabled, $adminNotes, $reviewedBy, $id]
        );

        if ($ok) {
            dbExecuteStatement(
                "INSERT INTO bot_int_transfer_verification_status_history (verification_id, status_code, status_title, remarks, changed_by, created_at) VALUES (?, ?, ?, ?, ?, NOW())",
                [$id, $newStatus, formatStatusLabel($newStatus), $historyRemarks, $reviewedBy]
            );

            $successMsg = 'Verification request updated successfully.';

            $chatId = customerTelegramChatId($row);
            if ($notifyCustomer && $chatId !== '') {
                $notifyRow = $row;
                $notifyRow['service_enabled'] = $serviceEnabled;
                $result = sendTelegramMessageToCustomer(
                    $chatId,
                    buildCustomerStatusMessage($notifyRow, $newStatus, $officerMessage, $reviewedBy),
                    [
                        'inline_keyboard' => [
                            [
                                ['text' => '📊 Check Verification Status', 'callback_data' => 'int_transfer_verification_status'],
                            ],
                            [
                                ['text' => '🆘 Speak with Customer Service', 'callback_data' => 'talk_to_agent'],
                            ],
                            [
                                ['text' => '🏦 Back to Main Menu', 'callback_data' => 'main_menu'],
                            ],
                        ]
                    ]
                );

                if ($result['ok']) {
                    $successMsg .= ' Customer Telegram notification sent successfully.';
                } else {
                    $warningMsg = 'Verification was updated, but Telegram notification could not be delivered: ' . ($result['error'] ?? 'Unknown error');
                }
            } elseif ($notifyCustomer && $chatId === '') {
                $warningMsg = 'Verification was updated, but no Telegram chat identity was saved on this verification request. Please ensure the customer submits a fresh request after the Telegram identity columns are enabled and mapped in the bot flow.';
            }

            $row = fetchVerificationRowById($id);
        } else {
            $errorMsg = 'Unable to update verification request.';
        }
    }
}

$historyRows = dbFetchAllRows(
    "SELECT * FROM bot_int_transfer_verification_status_history WHERE verification_id = ? ORDER BY id DESC",
    [$id]
);

$customerPreviewMessage = buildCustomerStatusMessage(
    $row,
    (string)($row['status'] ?? 'PENDING_REVIEW'),
    '',
    (string)($row['reviewed_by'] ?: 'FinoviaPay Compliance Officer')
);
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>International Transfer Verification View</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root{--brand:#0f4fa8;--brand2:#153b73;--bg:#f4f7fb;--line:#eef2f7;}
        body{background:var(--bg);font-size:15px;color:#213250;}
        .page-wrap{max-width:1200px;margin:0 auto;}
        .hero-card,.panel-card,.info-card{border:0;border-radius:22px;box-shadow:0 14px 35px rgba(15,42,89,.08)}
        .hero-card{background:linear-gradient(135deg,var(--brand2),var(--brand));color:#fff;overflow:hidden}
        .hero-chip{display:inline-flex;align-items:center;gap:.4rem;background:rgba(255,255,255,.14);border:1px solid rgba(255,255,255,.18);padding:.42rem .8rem;border-radius:999px;font-size:.82rem}
        .panel-card,.info-card{background:#fff}
        .data-row{display:flex;justify-content:space-between;gap:14px;padding:12px 0;border-bottom:1px solid var(--line)}
        .data-row:last-child{border-bottom:0}
        .data-label{font-size:.82rem;color:#75839b;text-transform:uppercase;letter-spacing:.04em}
        .data-value{font-weight:600;color:#213250;text-align:right;word-break:break-word}
        .file-box{border:1px solid #e6edf7;border-radius:18px;padding:14px;height:100%;background:#fff}
        .timeline-item{position:relative;padding-left:22px;padding-bottom:18px;margin-left:8px;border-left:2px solid #dce6f5}
        .timeline-item:last-child{padding-bottom:0}
        .timeline-dot{position:absolute;left:-8px;top:2px;width:14px;height:14px;border-radius:50%;background:var(--brand);box-shadow:0 0 0 3px #fff}
        .btn-main{background:var(--brand);border-color:var(--brand)} .btn-main:hover{background:#0c448d;border-color:#0c448d}
        textarea.form-control, select.form-select{border-radius:14px}
        .preview-wrap{border:1px dashed #d9e5f5;border-radius:16px;padding:8px;background:#f9fbff;margin-bottom:12px}
        .preview-wrap img,.preview-wrap video{width:100%;max-height:280px;object-fit:contain;border-radius:12px;background:#f1f5fb}
        .message-preview{white-space:pre-line;background:#f8fbff;border:1px solid #e5edf9;border-radius:16px;padding:14px}
        .note-box{background:#fff8e6;border:1px solid #f4ddb0;color:#805b00;border-radius:16px;padding:12px}
        @media (max-width: 767.98px){
            .page-wrap{padding-left:10px;padding-right:10px}
            .hero-card .display-title{font-size:1.35rem;line-height:1.3}
            .data-row{flex-direction:column;gap:4px}
            .data-value{text-align:left}
        }
    </style>
</head>
<body>
<div class="container-fluid py-3 py-md-4 page-wrap">
    <div class="hero-card p-3 p-md-4 mb-3 mb-md-4">
        <div class="d-flex flex-column flex-md-row align-items-start justify-content-between gap-3">
            <div>
                <a href="admin_int_transfer_verifications.php" class="btn btn-light btn-sm px-3 py-2 mb-3">Back to Requests</a>
                <span class="hero-chip">Compliance Review Record</span>
                <h1 class="display-title h3 mt-3 mb-2">International Transfer Verification View</h1>
                <div class="opacity-75">Review AML details, uploaded verification materials, officer notes, customer notification message, and service activation status from one page.</div>
            </div>
            <div class="d-flex flex-column align-items-start align-items-md-end gap-2">
                <span class="badge rounded-pill bg-light text-dark px-3 py-2"><?= e((string)$row['reference_code']) ?></span>
                <span class="badge rounded-pill <?= statusBadgeClass((string)$row['status']) ?> px-3 py-2"><?= e(formatStatusLabel((string)$row['status'])) ?></span>
            </div>
        </div>
    </div>

    <?php if ($successMsg): ?><div class="alert alert-success border-0 shadow-sm"><?= e($successMsg) ?></div><?php endif; ?>
    <?php if ($warningMsg): ?><div class="alert alert-warning border-0 shadow-sm"><?= e($warningMsg) ?></div><?php endif; ?>
    <?php if ($errorMsg): ?><div class="alert alert-danger border-0 shadow-sm"><?= e($errorMsg) ?></div><?php endif; ?>

    <div class="row g-3 mb-3 mb-md-4">
        <div class="col-6 col-md-3"><div class="info-card p-3 h-100"><div class="data-label">Service Access</div><div class="fs-5 fw-bold"><?= (int)$row['service_enabled'] === 1 ? 'Enabled' : 'Disabled' ?></div></div></div>
        <div class="col-6 col-md-3"><div class="info-card p-3 h-100"><div class="data-label">Submitted</div><div class="fs-6 fw-bold"><?= e(formatDateSafe((string)$row['created_at'])) ?></div></div></div>
        <div class="col-6 col-md-3"><div class="info-card p-3 h-100"><div class="data-label">Reviewed</div><div class="fs-6 fw-bold"><?= e(formatDateSafe((string)$row['reviewed_at'])) ?></div></div></div>
        <div class="col-6 col-md-3"><div class="info-card p-3 h-100"><div class="data-label">Telegram ID</div><div class="fs-6 fw-bold"><?= e(customerTelegramIdentitySummary($row)) ?></div></div></div>
    </div>

    <div class="row g-3 g-md-4">
        <div class="col-12 col-lg-8">
            <div class="panel-card p-3 p-md-4 mb-3 mb-md-4">
                <h5 class="fw-bold mb-3">Customer & AML Information</h5>
                <?php dataRow('Customer Name', (string)($row['full_name'] ?: $row['user_name'] ?: '—')); ?>
                <?php dataRow('Registered Email', (string)($row['user_email'] ?: '—')); ?>
                <?php dataRow('Registered Mobile', (string)($row['user_mobile'] ?: '—')); ?>
                <?php dataRow('Date of Birth', (string)($row['date_of_birth'] ?: '—')); ?>
                <?php dataRow('Country of Residence', (string)($row['country_of_residence'] ?: '—')); ?>
                <?php dataRow('Nationality', (string)($row['nationality'] ?: '—')); ?>
                <?php dataRow('Occupation', (string)($row['occupation'] ?: '—')); ?>
                <?php dataRow('Source of Funds', (string)($row['source_of_funds'] ?: '—')); ?>
                <?php dataRow('Expected Monthly Volume', $row['expected_monthly_volume_eur'] !== null ? 'EUR ' . number_format((float)$row['expected_monthly_volume_eur'], 2) : '—'); ?>
                <?php dataRow('Transfer Purpose', (string)($row['transfer_purpose'] ?: '—')); ?>
                <?php dataRow('Beneficiary Relationship', (string)($row['beneficiary_relationship'] ?: '—')); ?>
                <?php dataRow('PEP Declaration', (string)($row['is_pep'] ?: '—')); ?>
                <?php dataRow('Third-Party Acting', (string)($row['is_third_party'] ?: '—')); ?>
                <?php dataRow('Legal Funds Confirmed', (string)($row['legal_funds_confirmed'] ?: '—')); ?>
                <?php dataRow('Prior Transfer Experience', (string)($row['prior_transfer_experience'] ?: '—')); ?>
            </div>

            <div class="panel-card p-3 p-md-4 mb-3 mb-md-4">
                <h5 class="fw-bold mb-3">Identity Document Information</h5>
                <?php dataRow('Document Type', (string)($row['document_type'] ?: '—')); ?>
                <?php dataRow('Document Number', maskDocumentNumber((string)($row['document_number'] ?: ''))); ?>
                <?php dataRow('Document Expiry Date', (string)($row['document_expiry_date'] ?: '—')); ?>
            </div>

            <div class="panel-card p-3 p-md-4 mb-3 mb-md-4">
                <h5 class="fw-bold mb-3">Uploaded Verification Materials</h5>
                <div class="row g-3">
                    <?php
                    $files = [
                        ['Document Front Side', $row['document_front_file_id'] ?? '', $row['document_front_file_path'] ?? ''],
                        ['Document Back Side', $row['document_back_file_id'] ?? '', $row['document_back_file_path'] ?? ''],
                        ['Selfie with Document', $row['selfie_file_id'] ?? '', $row['selfie_file_path'] ?? ''],
                        ['Video Verification', $row['video_file_id'] ?? '', $row['video_file_path'] ?? ''],
                    ];
                    foreach ($files as [$title, $fid, $fpath]):
                        $previewPath = normalizeServerPreviewPath((string)$fpath);
                        $ptype = previewType((string)$previewPath, (string)$title);
                    ?>
                    <div class="col-12 col-md-6">
                        <div class="file-box">
                            <div class="d-flex justify-content-between align-items-start gap-2 mb-3">
                                <div class="fw-bold"><?= e($title) ?></div>
                                <span class="badge <?= ($fid || $fpath) ? 'bg-success-subtle text-success-emphasis' : 'bg-secondary-subtle text-secondary-emphasis' ?>"><?= ($fid || $fpath) ? 'Received' : 'Not Uploaded' ?></span>
                            </div>
                            <?php if ($previewPath && $ptype === 'image'): ?>
                                <div class="preview-wrap"><a href="<?= e($previewPath) ?>" target="_blank"><img src="<?= e($previewPath) ?>" alt="<?= e($title) ?> preview"></a></div>
                            <?php elseif ($previewPath && $ptype === 'video'): ?>
                                <div class="preview-wrap"><video controls preload="metadata"><source src="<?= e($previewPath) ?>"></video></div>
                            <?php endif; ?>
                            <div class="data-label mb-1">Telegram File ID</div>
                            <div class="small mb-3" style="word-break:break-all;"><?= e((string)($fid ?: '—')) ?></div>
                            <div class="data-label mb-1">Server Path</div>
                            <div class="small" style="word-break:break-all;"><?= e((string)($fpath ?: '—')) ?></div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <div class="col-12 col-lg-4">
            <div class="panel-card p-3 p-md-4 mb-3 mb-md-4">
                <h5 class="fw-bold mb-3">Review & Update</h5>
                <form method="post">
                    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Status</label>
                        <select name="status" class="form-select" required>
                            <?php foreach (['PENDING_REVIEW','UNDER_REVIEW','ADDITIONAL_INFO_REQUIRED','APPROVED','REJECTED','CANCELLED'] as $item): ?>
                                <option value="<?= e($item) ?>" <?= $row['status'] === $item ? 'selected' : '' ?>><?= e(formatStatusLabel($item)) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" name="service_enabled" id="service_enabled" value="1" <?= (int)$row['service_enabled'] === 1 ? 'checked' : '' ?>>
                        <label class="form-check-label fw-semibold" for="service_enabled">Enable International Transfer Service</label>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Internal Officer Notes</label>
                        <textarea name="admin_notes" class="form-control" rows="5" placeholder="Enter compliance notes, review findings, approval comments, or rejection reason."><?= e((string)($row['admin_notes'] ?? '')) ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Customer Telegram Message</label>
                        <textarea name="officer_message" class="form-control" rows="6" placeholder="Write the message that should be delivered to the customer on Telegram with full briefing."></textarea>
                        <div class="form-text">Use this for re-upload instructions, approval wording, rejection reason, or any compliance briefing you want the customer to receive.</div>
                    </div>
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" name="notify_customer" id="notify_customer" value="1" checked>
                        <label class="form-check-label fw-semibold" for="notify_customer">Send status update to customer on Telegram</label>
                    </div>
                    <div class="note-box small mb-3">
                        <strong>Notification behavior:</strong> Approved requests automatically enable the service. Rejected / Re-upload / Cancelled statuses keep service access disabled unless you manually change it later.
                    </div>
                    <button type="submit" name="update_verification" value="1" class="btn btn-main text-white w-100 fw-semibold">Update Verification Request</button>
                </form>
            </div>

            <div class="panel-card p-3 p-md-4 mb-3 mb-md-4">
                <h5 class="fw-bold mb-3">Customer Message Preview</h5>
                <div class="message-preview"><?= nl2br(e(strip_tags(html_entity_decode($customerPreviewMessage, ENT_QUOTES, 'UTF-8')))) ?></div>
            </div>

            <div class="panel-card p-3 p-md-4">
                <h5 class="fw-bold mb-3">Status Timeline</h5>
                <?php if (!$historyRows): ?>
                    <div class="text-muted">No status history available yet.</div>
                <?php else: ?>
                    <?php foreach ($historyRows as $item): ?>
                        <div class="timeline-item">
                            <span class="timeline-dot"></span>
                            <div class="fw-semibold"><?= e((string)($item['status_title'] ?: formatStatusLabel((string)$item['status_code']))) ?></div>
                            <div class="small text-muted mb-1"><?= e(formatDateSafe((string)$item['created_at'])) ?></div>
                            <div class="small mb-1"><?= nl2br(e((string)($item['remarks'] ?: 'No additional remarks.'))) ?></div>
                            <div class="small text-muted">Changed by: <?= e((string)($item['changed_by'] ?: 'System')) ?></div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
</body>
</html>
