<?php
session_start();
require_once "config.php";
require_once __DIR__ . '/bot_digital_service_request_functions.php';

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

if (!isset($pdo) || !($pdo instanceof PDO)) {
    if (isset($conn) && $conn instanceof PDO) {
        $pdo = $conn;
    } elseif (isset($db) && $db instanceof PDO) {
        $pdo = $db;
    } else {
        die('Database connection not available in config.php');
    }
}

if (function_exists('botInstallDigitalServiceTables')) {
    botInstallDigitalServiceTables($pdo);
}

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

function statusBadgeClass(string $status): string {
    $status = strtoupper($status);
    return match ($status) {
        'NEW' => 'bg-primary-subtle text-primary',
        'UNDER_REVIEW', 'PENDING_REVIEW' => 'bg-info-subtle text-info-emphasis',
        'DOCUMENTS_REQUIRED', 'REUPLOAD_REQUIRED' => 'bg-warning-subtle text-warning-emphasis',
        'DOCUMENTS_RECEIVED', 'CUSTOMER_REPLIED' => 'bg-secondary-subtle text-secondary-emphasis',
        'APPROVED', 'SERVICE_ENABLED' => 'bg-success-subtle text-success-emphasis',
        'REJECTED' => 'bg-danger-subtle text-danger-emphasis',
        default => 'bg-light text-dark',
    };
}

function ds_resolve_token(): string {
    static $resolved = null;
    if ($resolved !== null) return $resolved;

    foreach ([__DIR__ . '/bot_token.php', dirname(__DIR__) . '/bot_token.php'] as $f) {
        if (is_file($f)) @require_once $f;
    }

    $candidates = [];
    foreach (['TELEGRAM_BOT_TOKEN','BOT_TOKEN','TELEGRAM_TOKEN'] as $c) {
        if (defined($c) && trim((string)constant($c)) !== '') $candidates[] = constant($c);
    }
    foreach (['token', 'botToken', 'telegram_token', 'telegramBotToken'] as $v) {
        if (isset($GLOBALS[$v]) && trim((string)$GLOBALS[$v]) !== '') $candidates[] = $GLOBALS[$v];
    }
    foreach (['TELEGRAM_BOT_TOKEN','BOT_TOKEN','TELEGRAM_TOKEN'] as $env) {
        $val = getenv($env);
        if (is_string($val) && trim($val) !== '') $candidates[] = $val;
    }

    foreach ($candidates as $candidate) {
        $candidate = trim((string)$candidate);
        if ($candidate !== '') {
            $resolved = $candidate;
            return $resolved;
        }
    }

    $resolved = '';
    return $resolved;
}

function ds_send_telegram($chatId, string $message): bool {
    $token = ds_resolve_token();
    $chatId = trim((string)$chatId);

    if ($token === '' || $chatId === '') {
        error_log("BOT ERROR: Digital service Telegram notification could not be sent because token or chat id is missing.");
        return false;
    }

    $url = "https://api.telegram.org/bot{$token}/sendMessage";
    $payload = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 20,
            CURLOPT_POSTFIELDS => $payload
        ]);
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($response === false) {
            error_log("BOT ERROR: Telegram send failed: " . $error);
            return false;
        }
        return true;
    }

    $context = stream_context_create([
        'http' => [
            'method'  => 'POST',
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'content' => http_build_query($payload),
            'timeout' => 20
        ]
    ]);

    return @file_get_contents($url, false, $context) !== false;
}

function ds_get_telegram_file_url(string $fileId): ?string {
    $fileId = trim($fileId);
    if ($fileId === '') return null;

    $token = ds_resolve_token();
    if ($token === '') return null;

    $url = "https://api.telegram.org/bot{$token}/getFile?file_id=" . urlencode($fileId);
    $response = false;

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 20,
        ]);
        $response = curl_exec($ch);
        curl_close($ch);
    } else {
        $response = @file_get_contents($url);
    }

    if ($response === false || $response === null || $response === '') {
        return null;
    }

    $json = json_decode($response, true);
    if (!is_array($json) || empty($json['ok']) || empty($json['result']['file_path'])) {
        return null;
    }

    $filePath = ltrim((string)$json['result']['file_path'], '/');
    if ($filePath === '') return null;

    return "https://api.telegram.org/file/bot{$token}/" . $filePath;
}

function ds_is_image_upload(array $upload): bool {
    $fileType = strtolower((string)($upload['file_type'] ?? ''));
    $mimeType = strtolower((string)($upload['mime_type'] ?? ''));
    $fileName = strtolower((string)($upload['file_name'] ?? ''));

    if ($fileType === 'photo') return true;
    if (str_starts_with($mimeType, 'image/')) return true;
    if (preg_match('/\.(jpg|jpeg|png|gif|webp)$/', $fileName)) return true;

    return false;
}



$ticketId = (int)($_GET['id'] ?? 0);
if ($ticketId <= 0) {
    exit('Invalid ticket id.');
}

$notice = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['save_status'])) {
            $status = strtoupper(trim((string)($_POST['status'] ?? '')));
            $allowed = function_exists('botDigitalServiceStatuses')
                ? botDigitalServiceStatuses()
                : ['NEW','UNDER_REVIEW','DOCUMENTS_REQUIRED','DOCUMENTS_RECEIVED','CUSTOMER_REPLIED','APPROVED','REJECTED','SERVICE_ENABLED'];

            if (!in_array($status, $allowed, true)) {
                throw new RuntimeException('Invalid status selected.');
            }

            $stmt = $pdo->prepare("UPDATE digital_service_tickets 
                                   SET status = :status,
                                       service_enabled = CASE WHEN :status = 'SERVICE_ENABLED' THEN 1 ELSE service_enabled END,
                                       enabled_at = CASE WHEN :status = 'SERVICE_ENABLED' THEN NOW() ELSE enabled_at END,
                                       updated_at = NOW() 
                                   WHERE id = :id");
            $stmt->execute([':status' => $status, ':id' => $ticketId]);

            $ticketRefStmt = $pdo->prepare("SELECT reference_no, telegram_chat_id FROM digital_service_tickets WHERE id = :id LIMIT 1");
            $ticketRefStmt->execute([':id' => $ticketId]);
            $tk = $ticketRefStmt->fetch(PDO::FETCH_ASSOC) ?: [];
            $reference = (string)($tk['reference_no'] ?? 'N/A');
            $chatId = (string)($tk['telegram_chat_id'] ?? '');

            $telegramText = "📌 <b>Request Status Updated</b>\n\n"
                . "<b>Reference Number</b>\n" . e($reference) . "\n\n"
                . "<b>New Status</b>\n" . e(str_replace('_', ' ', $status));

            if ($status === 'SERVICE_ENABLED') {
                $telegramText .= "\n\nYour digital banking service request has been approved and enabled successfully.";
            }

            ds_send_telegram($chatId, $telegramText);
            $notice = 'Ticket status updated successfully.';
        }

        if (isset($_POST['send_reply'])) {
            $reply = trim((string)($_POST['reply_message'] ?? ''));
            $officerName = trim((string)($_POST['officer_name'] ?? 'Banking Officer')) ?: 'Banking Officer';
            if ($reply === '') {
                throw new RuntimeException('Reply message is required.');
            }

            if (function_exists('botAddDigitalServiceOfficerReply')) {
                botAddDigitalServiceOfficerReply($pdo, $ticketId, $reply, $officerName, 'UNDER_REVIEW');
            } else {
                $stmt = $pdo->prepare("INSERT INTO digital_service_ticket_messages
                    (ticket_id, sender_type, sender_name, message, created_at)
                    VALUES (:ticket_id, 'officer', :sender_name, :message, NOW())");
                $stmt->execute([
                    ':ticket_id' => $ticketId,
                    ':sender_name' => $officerName,
                    ':message' => $reply
                ]);

                $stmt = $pdo->prepare("UPDATE digital_service_tickets SET status = 'UNDER_REVIEW', updated_at = NOW() WHERE id = :id");
                $stmt->execute([':id' => $ticketId]);
            }

            $ticketRefStmt = $pdo->prepare("SELECT reference_no, telegram_chat_id FROM digital_service_tickets WHERE id = :id LIMIT 1");
            $ticketRefStmt->execute([':id' => $ticketId]);
            $tk = $ticketRefStmt->fetch(PDO::FETCH_ASSOC) ?: [];
            $reference = (string)($tk['reference_no'] ?? 'N/A');
            $chatId = (string)($tk['telegram_chat_id'] ?? '');

            $telegramText = "📩 <b>Officer Reply Received</b>\n\n"
                . "<b>Reference Number</b>\n" . e($reference) . "\n\n"
                . "<b>Officer Message</b>\n" . e($reply);

            ds_send_telegram($chatId, $telegramText);
            $notice = 'Officer reply saved successfully.';
        }

        if (isset($_POST['request_document'])) {
            $documentLabel = trim((string)($_POST['document_label'] ?? ''));
            $notes = trim((string)($_POST['document_notes'] ?? ''));
            $officerName = trim((string)($_POST['officer_name'] ?? 'Banking Officer')) ?: 'Banking Officer';
            if ($documentLabel === '') {
                throw new RuntimeException('Document name is required.');
            }

            if (function_exists('botRequestDigitalServiceDocuments')) {
                botRequestDigitalServiceDocuments($pdo, $ticketId, $documentLabel, $notes, $officerName);
            } else {
                $stmt = $pdo->prepare("INSERT INTO digital_service_ticket_documents
                    (ticket_id, requested_by, document_name, document_description, is_required, is_received, created_at)
                    VALUES (:ticket_id, 'officer', :document_name, :document_description, 1, 0, NOW())");
                $stmt->execute([
                    ':ticket_id' => $ticketId,
                    ':document_name' => $documentLabel,
                    ':document_description' => ($notes !== '' ? $notes : null)
                ]);

                $stmt = $pdo->prepare("INSERT INTO digital_service_ticket_messages
                    (ticket_id, sender_type, sender_name, message, created_at)
                    VALUES (:ticket_id, 'officer', :sender_name, :message, NOW())");
                $stmt->execute([
                    ':ticket_id' => $ticketId,
                    ':sender_name' => $officerName,
                    ':message' => "Required document requested: {$documentLabel}" . ($notes !== '' ? " | Instructions: {$notes}" : '')
                ]);

                $stmt = $pdo->prepare("UPDATE digital_service_tickets SET status = 'DOCUMENTS_REQUIRED', updated_at = NOW() WHERE id = :id");
                $stmt->execute([':id' => $ticketId]);
            }

            $ticketRefStmt = $pdo->prepare("SELECT reference_no, telegram_chat_id FROM digital_service_tickets WHERE id = :id LIMIT 1");
            $ticketRefStmt->execute([':id' => $ticketId]);
            $tk = $ticketRefStmt->fetch(PDO::FETCH_ASSOC) ?: [];
            $reference = (string)($tk['reference_no'] ?? 'N/A');
            $chatId = (string)($tk['telegram_chat_id'] ?? '');

            $telegramText = "📄 <b>Required Documents Requested</b>\n\n"
                . "<b>Reference Number</b>\n" . e($reference) . "\n\n"
                . "<b>Required Document</b>\n" . e($documentLabel);

            if ($notes !== '') {
                $telegramText .= "\n\n<b>Officer Instructions</b>\n" . e($notes);
            }

            $telegramText .= "\n\nPlease upload the required document directly in this Telegram chat."
                . "\n\nAccepted format:"
                . "\n• Clear photo"
                . "\n• Scanned image"
                . "\n• PDF document";

            ds_send_telegram($chatId, $telegramText);
            $notice = 'Required document request saved successfully.';
        }


        if (isset($_POST['request_video_verification'])) {
            $videoInstructions = trim((string)($_POST['video_instructions'] ?? ''));
            $officerName = trim((string)($_POST['officer_name'] ?? 'Banking Officer')) ?: 'Banking Officer';

            if ($videoInstructions === '') {
                $videoInstructions = "Please record a clear video selfie while holding your original identification document. In the video, clearly show your face, hold your original ID card or passport, state your full name, state your document number, and say: I am requesting activation of my FinoviaPay digital banking service.";
            }

            $documentLabel = 'Recorded Video Selfie Verification';

            if (function_exists('botRequestDigitalServiceDocuments')) {
                botRequestDigitalServiceDocuments($pdo, $ticketId, $documentLabel, $videoInstructions, $officerName);
            } else {
                $stmt = $pdo->prepare("INSERT INTO digital_service_ticket_documents
                    (ticket_id, requested_by, document_name, document_description, is_required, is_received, created_at)
                    VALUES (:ticket_id, 'officer', :document_name, :document_description, 1, 0, NOW())");
                $stmt->execute([
                    ':ticket_id' => $ticketId,
                    ':document_name' => $documentLabel,
                    ':document_description' => $videoInstructions
                ]);

                $stmt = $pdo->prepare("INSERT INTO digital_service_ticket_messages
                    (ticket_id, sender_type, sender_name, message, created_at)
                    VALUES (:ticket_id, 'officer', :sender_name, :message, NOW())");
                $stmt->execute([
                    ':ticket_id' => $ticketId,
                    ':sender_name' => $officerName,
                    ':message' => "Video verification requested: {$documentLabel} | Instructions: {$videoInstructions}"
                ]);

                $stmt = $pdo->prepare("UPDATE digital_service_tickets SET status = 'DOCUMENTS_REQUIRED', updated_at = NOW() WHERE id = :id");
                $stmt->execute([':id' => $ticketId]);
            }

            $ticketRefStmt = $pdo->prepare("SELECT reference_no, telegram_chat_id FROM digital_service_tickets WHERE id = :id LIMIT 1");
            $ticketRefStmt->execute([':id' => $ticketId]);
            $tk = $ticketRefStmt->fetch(PDO::FETCH_ASSOC) ?: [];
            $reference = (string)($tk['reference_no'] ?? 'N/A');
            $chatId = (string)($tk['telegram_chat_id'] ?? '');

            $telegramText = "🎥 <b>Recorded Video Selfie Verification Required</b>\n\n"
                . "<b>Reference Number</b>\n" . e($reference) . "\n\n"
                . "A banking officer has requested a recorded video selfie for verification of your digital banking service activation request.\n\n"
                . "<b>Please follow these instructions carefully:</b>\n"
                . "• Show your face clearly in the video\n"
                . "• Hold your original ID card or passport in your hand\n"
                . "• Clearly say your full name\n"
                . "• Clearly say your document number\n"
                . "• Say: I am requesting activation of my FinoviaPay digital banking service.\n\n"
                . "<b>Officer Instructions</b>\n" . e($videoInstructions) . "\n\n"
                . "Please upload your recorded video selfie directly in this Telegram chat.";

            ds_send_telegram($chatId, $telegramText);
            $notice = 'Recorded video selfie verification request sent successfully.';
        }

        if (isset($_POST['review_upload'])) {
            $uploadId = (int)($_POST['upload_id'] ?? 0);
            $reviewStatus = strtoupper(trim((string)($_POST['review_status'] ?? '')));
            $reviewNote = trim((string)($_POST['officer_review_note'] ?? ''));
            $allowed = ['APPROVED','REJECTED','REUPLOAD_REQUIRED'];

            if ($uploadId <= 0 || !in_array($reviewStatus, $allowed, true)) {
                throw new RuntimeException('Invalid upload review request.');
            }

            $stmt = $pdo->prepare("SELECT u.*, t.reference_no, t.telegram_chat_id
                                   FROM digital_service_uploaded_documents u
                                   INNER JOIN digital_service_tickets t ON t.id = u.ticket_id
                                   WHERE u.id = :id AND u.ticket_id = :ticket_id
                                   LIMIT 1");
            $stmt->execute([':id' => $uploadId, ':ticket_id' => $ticketId]);
            $uploadRow = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$uploadRow) {
                throw new RuntimeException('Uploaded document not found.');
            }

            $pdo->beginTransaction();

            $stmt = $pdo->prepare("UPDATE digital_service_uploaded_documents
                                   SET review_status = :review_status,
                                       officer_review_note = :officer_review_note,
                                       reviewed_at = NOW()
                                   WHERE id = :id");
            $stmt->execute([
                ':review_status' => $reviewStatus,
                ':officer_review_note' => ($reviewNote !== '' ? $reviewNote : null),
                ':id' => $uploadId
            ]);

            $stmt = $pdo->prepare("INSERT INTO digital_service_ticket_messages
                (ticket_id, sender_type, sender_name, message, created_at)
                VALUES (:ticket_id, 'officer', :sender_name, :message, NOW())");
            $stmt->execute([
                ':ticket_id' => $ticketId,
                ':sender_name' => trim((string)($_POST['officer_name_hidden'] ?? ($_SESSION['agent_name'] ?? 'Banking Officer'))),
                ':message' => "Officer reviewed uploaded document. Review result: {$reviewStatus}" . ($reviewNote !== '' ? " | Note: {$reviewNote}" : '')
            ]);

            $ticketStatus = 'UNDER_REVIEW';
            if ($reviewStatus === 'REUPLOAD_REQUIRED') $ticketStatus = 'DOCUMENTS_REQUIRED';
            if ($reviewStatus === 'REJECTED') $ticketStatus = 'REJECTED';

            $stmt = $pdo->prepare("UPDATE digital_service_tickets SET status = :status, updated_at = NOW() WHERE id = :id");
            $stmt->execute([':status' => $ticketStatus, ':id' => $ticketId]);

            $pdo->commit();

            $reference = (string)($uploadRow['reference_no'] ?? 'N/A');
            $chatId = (string)($uploadRow['telegram_chat_id'] ?? '');

            $telegramText = "📄 <b>Document Review Update</b>\n\n"
                . "<b>Reference Number</b>\n" . e($reference) . "\n\n"
                . "<b>Review Result</b>\n" . e(str_replace('_', ' ', $reviewStatus));

            if ($reviewNote !== '') {
                $telegramText .= "\n\n<b>Officer Note</b>\n" . e($reviewNote);
            }

            if ($reviewStatus === 'APPROVED') {
                $telegramText .= "\n\nYour document has been accepted and moved for further banking review.";
            } elseif ($reviewStatus === 'REUPLOAD_REQUIRED') {
                $telegramText .= "\n\nPlease upload a clearer or corrected document directly in this Telegram chat.";
            } else {
                $telegramText .= "\n\nYour document could not be accepted. Please contact customer service if you need help.";
            }

            ds_send_telegram($chatId, $telegramText);
            $notice = 'Uploaded document review saved successfully.';
        }

    } catch (Throwable $ex) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $error = $ex->getMessage();
    }
}

$ticket = function_exists('botGetDigitalServiceTicketById') ? botGetDigitalServiceTicketById($pdo, $ticketId) : null;
if (!$ticket) {
    $stmt = $pdo->prepare("SELECT * FROM digital_service_tickets WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $ticketId]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
}
if (!$ticket) {
    exit('Ticket not found.');
}

$messages = function_exists('botGetDigitalServiceTicketMessages') ? botGetDigitalServiceTicketMessages($pdo, $ticketId) : [];
if (!$messages) {
    $stmt = $pdo->prepare("SELECT * FROM digital_service_ticket_messages WHERE ticket_id = :ticket_id ORDER BY id ASC");
    $stmt->execute([':ticket_id' => $ticketId]);
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$documents = function_exists('botGetDigitalServiceRequestedDocuments') ? botGetDigitalServiceRequestedDocuments($pdo, $ticketId) : [];
if (!$documents) {
    $stmt = $pdo->prepare("SELECT * FROM digital_service_ticket_documents WHERE ticket_id = :ticket_id ORDER BY id DESC");
    $stmt->execute([':ticket_id' => $ticketId]);
    $documents = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$stmt = $pdo->prepare("SELECT * FROM digital_service_uploaded_documents WHERE ticket_id = :ticket_id ORDER BY id DESC");
$stmt->execute([':ticket_id' => $ticketId]);
$uploads = $stmt->fetchAll(PDO::FETCH_ASSOC);

$statuses = function_exists('botDigitalServiceStatuses')
    ? botDigitalServiceStatuses()
    : ['NEW','UNDER_REVIEW','DOCUMENTS_REQUIRED','DOCUMENTS_RECEIVED','CUSTOMER_REPLIED','APPROVED','REJECTED','SERVICE_ENABLED'];

$ticketReference = (string)($ticket['reference_no'] ?? $ticket['reference'] ?? 'N/A');
$assignedOfficer = (string)($ticket['assigned_officer_name'] ?? ($_SESSION['agent_name'] ?? 'Banking Officer'));
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= e($ticketReference) ?> - Digital Service Request</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;
        }
        body{background:var(--bg);font-size:15px;}
        .page-wrap{max-width:1200px;margin:0 auto;}
        .hero-card,.panel-card,.msg-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;}
        .panel-card,.msg-card{background:#fff;}
        .chip{display:inline-flex;align-items:center;gap:.45rem;background:rgba(255,255,255,.15);padding:.42rem .8rem;border-radius:999px;font-size:.82rem;border:1px solid rgba(255,255,255,.14);}
        .meta-label{font-size:.78rem;color:#76829b;text-transform:uppercase;letter-spacing:.04em;}
        .meta-value{font-weight:600;color:#223251;word-break:break-word;}
        .btn-main{background:var(--brand);border-color:var(--brand);} .btn-main:hover{background:#0d448f;border-color:#0d448f;}
        .form-control,.form-select,.btn{min-height:48px;border-radius:14px;}
        textarea.form-control{min-height:120px;}
        .msg-customer{border-left:4px solid #0f4fa8;}
        .msg-officer{border-left:4px solid #198754;}
        .msg-system{border-left:4px solid #ffc107;}
        @media (max-width:767.98px){
            .page-wrap{padding-left:10px;padding-right:10px;}
        }
    </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 justify-content-between gap-3 align-items-start">
            <div>
                <span class="chip">Enablement Review Desk</span>
                <h1 class="h3 mt-3 mb-2">Request <?= e($ticketReference) ?></h1>
                <div class="opacity-75">Officer review panel for digital banking activation requests.</div>
            </div>
            <a href="admin_digital_service_tickets_mobile.php" class="btn btn-light">Back to Tickets</a>
        </div>
    </div>

    <?php if ($notice): ?><div class="alert alert-success rounded-4"><?= e($notice) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger rounded-4"><?= e($error) ?></div><?php endif; ?>

    <div class="row g-3 g-md-4">
        <div class="col-12 col-lg-5">
            <div class="panel-card p-3 p-md-4 mb-3">
                <div class="d-flex justify-content-between gap-2 align-items-start mb-3">
                    <div>
                        <div class="meta-label">Customer Name</div>
                        <div class="meta-value"><?= e((string)($ticket['customer_name'] ?? 'Customer')) ?></div>
                    </div>
                    <span class="badge rounded-pill <?= statusBadgeClass((string)($ticket['status'] ?? 'NEW')) ?> px-3 py-2"><?= e((string)($ticket['status'] ?? 'NEW')) ?></span>
                </div>
                <div class="row g-3">
                    <div class="col-6">
                        <div class="meta-label">Document Type</div>
                        <div class="meta-value"><?= e((string)($ticket['document_type'] ?? '')) ?></div>
                    </div>
                    <div class="col-6">
                        <div class="meta-label">Document Number</div>
                        <div class="meta-value"><?= e((string)($ticket['document_number'] ?? '')) ?></div>
                    </div>
                    <div class="col-6">
                        <div class="meta-label">Officer</div>
                        <div class="meta-value"><?= e($assignedOfficer !== '' ? $assignedOfficer : 'Unassigned') ?></div>
                    </div>
                    <div class="col-6">
                        <div class="meta-label">Created</div>
                        <div class="meta-value"><?= e((string)($ticket['created_at'] ?? '')) ?></div>
                    </div>
                    <div class="col-12">
                        <div class="meta-label">Initial Request</div>
                        <div class="mt-1 text-body" style="white-space:pre-wrap;"><?= e((string)($ticket['request_message'] ?? '')) ?></div>
                    </div>
                    <div class="col-12">
                        <div class="meta-label">Telegram Chat ID</div>
                        <div class="meta-value"><?= e((string)($ticket['telegram_chat_id'] ?? 'Not Available')) ?></div>
                    </div>
                </div>
            </div>

            <div class="panel-card p-3 p-md-4 mb-3">
                <h5 class="mb-3">Update Status</h5>
                <form method="post">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Status</label>
                        <select name="status" class="form-select">
                            <?php foreach ($statuses as $status): ?>
                                <option value="<?= e($status) ?>" <?= (($ticket['status'] ?? '') === $status ? 'selected' : '') ?>><?= e($status) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <button type="submit" name="save_status" value="1" class="btn btn-main text-white w-100 fw-semibold">Save Status</button>
                </form>
            </div>

            <div class="panel-card p-3 p-md-4 mb-3">
                <h5 class="mb-3">Request Required Documentation</h5>
                <form method="post">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Officer Name</label>
                        <input type="text" name="officer_name" class="form-control" value="<?= e($assignedOfficer ?: 'Banking Officer') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Document Name</label>
                        <input type="text" name="document_label" class="form-control" placeholder="Passport scan, proof of address, selfie verification etc.">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Notes / Instructions</label>
                        <textarea name="document_notes" class="form-control" rows="4" placeholder="Write officer instructions for the required document"></textarea>
                    </div>
                    <button type="submit" name="request_document" value="1" class="btn btn-warning w-100 fw-semibold">Save Document Request</button>
                </form>
            </div>

            <div class="panel-card p-3 p-md-4">
                <h5 class="mb-3">Requested Documents</h5>
                <?php if (!$documents): ?>
                    <div class="text-muted">No requested documents recorded yet.</div>
                <?php else: ?>
                    <?php foreach ($documents as $doc): ?>
                        <div class="msg-card p-3 mb-3">
                            <div class="d-flex justify-content-between gap-2 flex-wrap mb-2">
                                <div class="fw-semibold"><?= e((string)($doc['document_label'] ?? $doc['document_name'] ?? 'Document')) ?></div>
                                <div class="small text-muted"><?= e((string)($doc['created_at'] ?? '')) ?></div>
                            </div>
                            <div class="meta-label">Status</div>
                            <div class="meta-value mb-2"><?= e((string)($doc['status'] ?? (($doc['is_received'] ?? 0) ? 'RECEIVED' : 'PENDING'))) ?></div>
                            <div class="meta-label">Notes</div>
                            <div class="text-body"><?= e((string)($doc['notes'] ?? $doc['document_description'] ?? '')) ?></div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="col-12 col-lg-7">
            <div class="panel-card p-3 p-md-4 mb-3">
                <h5 class="mb-3">Officer Reply</h5>
                <form method="post">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Officer Name</label>
                        <input type="text" name="officer_name" class="form-control" value="<?= e($assignedOfficer ?: 'Banking Officer') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Reply Message</label>
                        <textarea name="reply_message" class="form-control" rows="5" placeholder="Write the officer reply or verification note"></textarea>
                    </div>
                    <button type="submit" name="send_reply" value="1" class="btn btn-success w-100 fw-semibold">Save Officer Reply</button>
                </form>
            </div>

            <div class="panel-card p-3 p-md-4 mb-3">
                <h5 class="mb-3">Conversation</h5>
                <?php if (!$messages): ?>
                    <div class="text-muted">No messages recorded yet.</div>
                <?php else: ?>
                    <?php foreach ($messages as $msg):
                        $senderType = strtolower((string)($msg['sender_type'] ?? 'customer'));
                        $class = $senderType === 'officer' ? 'msg-officer' : ($senderType === 'system' ? 'msg-system' : 'msg-customer');
                    ?>
                        <div class="msg-card <?= $class ?> p-3 mb-3">
                            <div class="d-flex justify-content-between gap-2 flex-wrap">
                                <div class="fw-semibold"><?= e((string)($msg['sender_name'] ?? ucfirst($senderType))) ?></div>
                                <div class="small text-muted"><?= e((string)($msg['created_at'] ?? '')) ?></div>
                            </div>
                            <div class="mt-2" style="white-space:pre-wrap;"><?= e((string)($msg['message_text'] ?? $msg['message'] ?? '')) ?></div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="panel-card p-3 p-md-4 mb-3">
                <h5 class="mb-3">Request Video Verification</h5>
                <form method="post">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Officer Name</label>
                        <input type="text" name="officer_name" class="form-control" value="<?= e($assignedOfficer ?: 'Banking Officer') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Video Verification Instructions</label>
                        <textarea name="video_instructions" class="form-control" rows="5" placeholder="Write instructions for the customer video selfie verification">Please record a clear video selfie while holding your original identification document. In the video, clearly show your face, hold your original ID card or passport, state your full name, state your document number, and say: I am requesting activation of my FinoviaPay digital banking service.</textarea>
                    </div>
                    <button type="submit" name="request_video_verification" value="1" class="btn btn-danger w-100 fw-semibold">Request Recorded Video Selfie</button>
                </form>
            </div>

            <div class="panel-card p-3 p-md-4">
                <h5 class="mb-3">Uploaded Documents</h5>
                <?php if (!$uploads): ?>
                    <div class="text-muted">Customer has not uploaded any documents yet.</div>
                <?php else: ?>
                    <?php foreach ($uploads as $upload): ?>
                        <div class="msg-card p-3 mb-3">
                            <div class="d-flex justify-content-between gap-2 flex-wrap mb-2">
                                <div class="fw-semibold"><?= e((string)($upload['file_name'] ?? 'Telegram Upload')) ?></div>
                                <span class="badge rounded-pill <?= statusBadgeClass((string)($upload['review_status'] ?? 'PENDING_REVIEW')) ?> px-3 py-2"><?= e((string)($upload['review_status'] ?? 'PENDING_REVIEW')) ?></span>
                            </div>

                            <div class="row g-3">
                                <div class="col-6">
                                    <div class="meta-label">File Type</div>
                                    <div class="meta-value"><?= e((string)($upload['file_type'] ?? 'document')) ?></div>
                                </div>
                                <div class="col-6">
                                    <div class="meta-label">Uploaded At</div>
                                    <div class="meta-value"><?= e((string)($upload['uploaded_at'] ?? '')) ?></div>
                                </div>
                                <div class="col-12">
                                    <div class="meta-label">Telegram File ID</div>
                                    <div class="meta-value"><?= e((string)($upload['telegram_file_id'] ?? '')) ?></div>
                                </div>
                                <?php $telegramFileUrl = ds_get_telegram_file_url((string)($upload['telegram_file_id'] ?? '')); ?>
                                <?php if ($telegramFileUrl): ?>
                                    <div class="col-12">
                                        <div class="meta-label">Document Preview</div>
                                        <?php if (ds_is_image_upload($upload)): ?>
                                            <div class="mt-2">
                                                <img src="<?= e($telegramFileUrl) ?>" alt="Uploaded document preview" class="img-fluid rounded-4 border">
                                            </div>
                                        <?php else: ?>
                                            <a href="<?= e($telegramFileUrl) ?>" target="_blank" class="btn btn-outline-primary mt-2">Open Uploaded Document</a>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="col-12">
                                        <div class="meta-label">Document Access</div>
                                        <div class="text-muted">Preview abhi load nahi ho saki. Telegram file ID save ho chuki hai.</div>
                                    </div>
                                <?php endif; ?>
                                <?php if (!empty($upload['caption_text'])): ?>
                                    <div class="col-12">
                                        <div class="meta-label">Customer Note</div>
                                        <div class="text-body" style="white-space:pre-wrap;"><?= e((string)$upload['caption_text']) ?></div>
                                    </div>
                                <?php endif; ?>
                                <?php if (!empty($upload['officer_review_note'])): ?>
                                    <div class="col-12">
                                        <div class="meta-label">Officer Review Note</div>
                                        <div class="text-body" style="white-space:pre-wrap;"><?= e((string)$upload['officer_review_note']) ?></div>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <form method="post" class="mt-3">
                                <input type="hidden" name="upload_id" value="<?= (int)$upload['id'] ?>">
                                <input type="hidden" name="officer_name_hidden" value="<?= e($assignedOfficer ?: 'Banking Officer') ?>">
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Review Decision</label>
                                    <select name="review_status" class="form-select">
                                        <option value="APPROVED">Approve Document</option>
                                        <option value="REUPLOAD_REQUIRED">Request Re-Upload</option>
                                        <option value="REJECTED">Reject Document</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Officer Review Note</label>
                                    <textarea name="officer_review_note" class="form-control" rows="4" placeholder="Write short review note for the customer"></textarea>
                                </div>
                                <button type="submit" name="review_upload" value="1" class="btn btn-main text-white w-100 fw-semibold">Save Upload Review</button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
</body>
</html>
