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

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

$agent_id   = (int)($_SESSION['agent_id'] ?? 0);
$agent_name = $_SESSION['agent_name'] ?? 'Support Officer';

$telegramBotToken = '';
if (defined('TELEGRAM_BOT_TOKEN') && is_string(TELEGRAM_BOT_TOKEN) && TELEGRAM_BOT_TOKEN !== '') {
    $telegramBotToken = TELEGRAM_BOT_TOKEN;
} elseif (!empty($GLOBALS['telegramBotToken']) && is_string($GLOBALS['telegramBotToken'])) {
    $telegramBotToken = $GLOBALS['telegramBotToken'];
} else {
    $telegramBotToken = '8367895377:AAGLCU-UwilSIlsfZgh_TjTTAdryK0uu5Xw';
}

$success = '';
$error   = '';

$ticketId = trim($_GET['ticket_id'] ?? $_POST['ticket_id'] ?? '');
$ticket = null;

function wtvr_send_telegram_message(string $botToken, string $chatId, string $message, ?array $inlineKeyboard = null): bool
{
    $payload = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];

    if ($inlineKeyboard) {
        $payload['reply_markup'] = json_encode(['inline_keyboard' => $inlineKeyboard]);
    }

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

    $result = @file_get_contents("https://api.telegram.org/bot{$botToken}/sendMessage", false, $context);
    return $result !== false;
}

$requestTypeOptions = [
    'beneficiary_wallet_statement' => 'Beneficiary Wallet Statement',
    'wallet_credit_screenshot' => 'Wallet Credit Screenshot',
    'pdf_statement' => 'PDF Statement',
    'other_supporting_proof' => 'Other Supporting Proof'
];

if ($ticketId !== '') {
    try {
        $stmt = $pdo->prepare("
            SELECT *
            FROM telegram_bot_wallet_transfer_tickets
            WHERE ticket_id = :ticket_id
            LIMIT 1
        ");
        $stmt->execute([':ticket_id' => $ticketId]);
        $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$ticket) {
            $error = 'The selected wallet transfer ticket could not be found.';
        }
    } catch (Throwable $e) {
        $error = 'Failed to load ticket information: ' . $e->getMessage();
    }
} else {
    $error = 'No wallet transfer ticket was selected.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $ticket) {
    $requestType = trim($_POST['request_type'] ?? '');
    $requestTitle = trim($_POST['request_title'] ?? '');
    $requestMessage = trim($_POST['request_message'] ?? '');

    if (!isset($requestTypeOptions[$requestType])) {
        $error = 'Please select a valid request type.';
    } elseif ($requestTitle === '') {
        $error = 'Please enter a professional request title.';
    } elseif ($requestMessage === '') {
        $error = 'Please enter the request message for the customer.';
    } else {
        try {
            $stmtInsert = $pdo->prepare("
                INSERT INTO telegram_bot_wallet_transfer_verification_requests
                (
                    ticket_id,
                    transfer_reference,
                    user_id,
                    telegram_id,
                    request_type,
                    request_title,
                    request_message,
                    status,
                    requested_by_agent_id,
                    requested_by_agent_name,
                    created_at,
                    updated_at
                )
                VALUES
                (
                    :ticket_id,
                    :transfer_reference,
                    :user_id,
                    :telegram_id,
                    :request_type,
                    :request_title,
                    :request_message,
                    'pending',
                    :requested_by_agent_id,
                    :requested_by_agent_name,
                    NOW(),
                    NULL
                )
            ");

            $stmtInsert->execute([
                ':ticket_id' => $ticket['ticket_id'],
                ':transfer_reference' => $ticket['transfer_reference'] ?? null,
                ':user_id' => (int)$ticket['user_id'],
                ':telegram_id' => $ticket['telegram_id'] ?? null,
                ':request_type' => $requestType,
                ':request_title' => $requestTitle,
                ':request_message' => $requestMessage,
                ':requested_by_agent_id' => $agent_id,
                ':requested_by_agent_name' => $agent_name,
            ]);

            $verificationRequestId = (int)$pdo->lastInsertId();

            try {
                $stmtMsg = $pdo->prepare("
                    INSERT INTO telegram_bot_wallet_transfer_ticket_messages
                    (ticket_id, sender_type, sender_name, message, created_at)
                    VALUES
                    (:ticket_id, 'system', :sender_name, :message, NOW())
                ");
                $stmtMsg->execute([
                    ':ticket_id' => $ticket['ticket_id'],
                    ':sender_name' => $agent_name,
                    ':message' => 'Additional verification requested: ' . $requestTitle
                ]);
            } catch (Throwable $e) {
            }

            $telegramId = trim((string)($ticket['telegram_id'] ?? ''));
            if ($telegramId !== '') {
                $telegramMessage  = "🏦 <b>FinoviaPay Verification Request</b>\n\n";
                $telegramMessage .= "A FinoviaPay officer has requested an additional supporting document regarding your wallet transfer support case.\n\n";
                $telegramMessage .= "<b>Ticket ID</b>\n" . htmlspecialchars((string)$ticket['ticket_id'], ENT_QUOTES, 'UTF-8') . "\n\n";
                $telegramMessage .= "<b>Transfer Reference</b>\n" . htmlspecialchars((string)($ticket['transfer_reference'] ?? '-'), ENT_QUOTES, 'UTF-8') . "\n\n";
                $telegramMessage .= "<b>Requested Document</b>\n" . htmlspecialchars($requestTypeOptions[$requestType], ENT_QUOTES, 'UTF-8') . "\n\n";
                $telegramMessage .= "<b>Request Title</b>\n" . htmlspecialchars($requestTitle, ENT_QUOTES, 'UTF-8') . "\n\n";
                $telegramMessage .= "<b>Reason / Officer Message</b>\n" . htmlspecialchars($requestMessage, ENT_QUOTES, 'UTF-8') . "\n\n";
                $telegramMessage .= "<b>Accepted Formats</b>\nPDF, screenshot, or photo\n\n";
                $telegramMessage .= "Please use the secure upload option below to submit the requested supporting document.";

                $buttons = [
                    [
                        ['text' => '📤 Upload Requested Document', 'callback_data' => 'wtvr_upload_' . $verificationRequestId]
                    ],
                    [
                        ['text' => '🔎 View Latest Transfers', 'callback_data' => 'latest_wallet_transfers']
                    ]
                ];

                wtvr_send_telegram_message($telegramBotToken, $telegramId, $telegramMessage, $buttons);
            }

            $success = 'Verification request created successfully and the customer has been notified on Telegram.';
        } catch (Throwable $e) {
            $error = 'Failed to create verification request: ' . $e->getMessage();
        }
    }
}

$recentRequests = [];
if ($ticket) {
    try {
        $stmtRecent = $pdo->prepare("
            SELECT *
            FROM telegram_bot_wallet_transfer_verification_requests
            WHERE ticket_id = :ticket_id
            ORDER BY id DESC
            LIMIT 20
        ");
        $stmtRecent->execute([':ticket_id' => $ticket['ticket_id']]);
        $recentRequests = $stmtRecent->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) {
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wallet Transfer Verification Request - FinoviaPay</title>
    <style>
        *{box-sizing:border-box}
        body{margin:0;background:#f4f7fb;font-family:Arial,Helvetica,sans-serif;color:#111827}
        .topbar{background:linear-gradient(135deg,#0b4f8a,#0a7b83);color:#fff;padding:18px 16px;box-shadow:0 2px 8px rgba(0,0,0,.10)}
        .topbar h1{margin:0;font-size:22px}
        .topbar p{margin:6px 0 0 0;font-size:13px;opacity:.94}
        .container{max-width:1280px;margin:0 auto;padding:18px}
        .back-link{display:inline-block;margin-bottom:14px;text-decoration:none;color:#0b4f8a;font-weight:700}
        .alert{padding:12px 14px;border-radius:10px;font-size:14px;margin-bottom:12px}
        .alert-success{background:#eaf7ee;color:#166534;border:1px solid #bbf7d0}
        .alert-error{background:#fef2f2;color:#991b1b;border:1px solid #fecaca}
        .layout{display:grid;grid-template-columns:420px 1fr;gap:16px}
        .card{background:#fff;border:1px solid #e5e7eb;border-radius:16px;box-shadow:0 2px 12px rgba(15,23,42,.06);overflow:hidden}
        .card-head{padding:16px 18px;border-bottom:1px solid #eef2f7;background:#fbfcfe}
        .card-head h2{margin:0;font-size:18px}
        .card-head p{margin:6px 0 0 0;font-size:13px;color:#6b7280}
        .card-body{padding:18px}
        .meta{display:grid;grid-template-columns:1fr 1fr;gap:10px}
        .meta-box{background:#f9fafb;border:1px solid #eef2f7;border-radius:10px;padding:10px}
        .meta-label{font-size:11px;color:#6b7280;margin-bottom:5px}
        .meta-value{font-size:13px;font-weight:600;color:#111827;word-break:break-word}
        select,input[type=text],textarea,button{width:100%;padding:12px;border-radius:10px;font-size:14px}
        select,input[type=text],textarea{border:1px solid #d1d5db;background:#fff}
        textarea{min-height:150px;resize:vertical}
        button{border:none;background:#0b4f8a;color:#fff;font-weight:700;cursor:pointer}
        .space{height:14px}
        .request-list{display:grid;gap:12px}
        .req-item{border:1px solid #e5e7eb;border-radius:12px;padding:12px;background:#fff}
        .req-title{font-size:14px;font-weight:700;color:#0f172a;margin-bottom:6px}
        .req-sub{font-size:12px;color:#6b7280;line-height:1.7}
        .badge{display:inline-block;padding:6px 10px;border-radius:999px;font-size:12px;font-weight:700}
        .badge-pending{background:#fff7ed;color:#9a3412}
        .badge-uploaded{background:#eff6ff;color:#1d4ed8}
        .badge-reviewed{background:#f5f3ff;color:#6d28d9}
        .badge-accepted{background:#ecfdf5;color:#047857}
        .badge-rejected{background:#fef2f2;color:#b91c1c}
        .empty{padding:28px 16px;border:1px dashed #cbd5e1;border-radius:12px;text-align:center;color:#6b7280;background:#fff}
        @media (max-width:1100px){.layout{grid-template-columns:1fr}}
        @media (max-width:640px){.container{padding:12px}.meta{grid-template-columns:1fr}.topbar h1{font-size:19px}}
    </style>
</head>
<body>
    <div class="topbar">
        <h1>FinoviaPay Wallet Transfer Verification Request</h1>
        <p>Create an additional verification request for the customer and collect supporting proof such as wallet statements, screenshots, or PDF evidence.</p>
    </div>

    <div class="container">
        <a class="back-link" href="telegram_bot_wallet_transfer_ticket_detail.php?ticket_id=<?php echo urlencode((string)$ticketId); ?>">← Back to Ticket Detail</a>

        <?php if ($success !== ''): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>

        <?php if ($error !== ''): ?>
            <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <?php if ($ticket): ?>
            <div class="layout">
                <div class="card">
                    <div class="card-head">
                        <h2>Ticket & Transfer Information</h2>
                        <p>Review the current wallet transfer support case before requesting additional verification proof.</p>
                    </div>
                    <div class="card-body">
                        <div class="meta">
                            <div class="meta-box">
                                <div class="meta-label">Ticket ID</div>
                                <div class="meta-value"><?php echo htmlspecialchars($ticket['ticket_id'] ?? '-'); ?></div>
                            </div>
                            <div class="meta-box">
                                <div class="meta-label">Transfer Reference</div>
                                <div class="meta-value"><?php echo htmlspecialchars($ticket['transfer_reference'] ?? '-'); ?></div>
                            </div>
                            <div class="meta-box">
                                <div class="meta-label">Customer Name</div>
                                <div class="meta-value"><?php echo htmlspecialchars($ticket['customer_name'] ?? '-'); ?></div>
                            </div>
                            <div class="meta-box">
                                <div class="meta-label">Customer Email</div>
                                <div class="meta-value"><?php echo htmlspecialchars($ticket['customer_email'] ?? '-'); ?></div>
                            </div>
                            <div class="meta-box">
                                <div class="meta-label">Issue Category</div>
                                <div class="meta-value"><?php echo htmlspecialchars($ticket['issue_category'] ?? '-'); ?></div>
                            </div>
                            <div class="meta-box">
                                <div class="meta-label">Telegram ID</div>
                                <div class="meta-value"><?php echo htmlspecialchars($ticket['telegram_id'] ?? '-'); ?></div>
                            </div>
                        </div>

                        <div class="space"></div>

                        <?php if (!empty($recentRequests)): ?>
                            <div class="request-list">
                                <?php foreach ($recentRequests as $req): ?>
                                    <?php
                                        $statusClass = 'badge-pending';
                                        if (($req['status'] ?? '') === 'uploaded') $statusClass = 'badge-uploaded';
                                        elseif (($req['status'] ?? '') === 'reviewed') $statusClass = 'badge-reviewed';
                                        elseif (($req['status'] ?? '') === 'accepted') $statusClass = 'badge-accepted';
                                        elseif (($req['status'] ?? '') === 'rejected') $statusClass = 'badge-rejected';
                                    ?>
                                    <div class="req-item">
                                        <div class="req-title"><?php echo htmlspecialchars($req['request_title'] ?? '-'); ?></div>
                                        <div class="req-sub">
                                            Type: <?php echo htmlspecialchars($requestTypeOptions[$req['request_type']] ?? ($req['request_type'] ?? '-')); ?><br>
                                            Created: <?php echo htmlspecialchars($req['created_at'] ?? '-'); ?><br>
                                            Status:
                                            <span class="badge <?php echo $statusClass; ?>">
                                                <?php echo htmlspecialchars(ucwords(str_replace('_', ' ', (string)($req['status'] ?? 'pending')))); ?>
                                            </span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <div class="empty">No previous verification requests have been created for this wallet transfer ticket.</div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="card">
                    <div class="card-head">
                        <h2>Create Verification Request</h2>
                        <p>Send a professional document request to the customer and ask for a wallet statement, screenshot, PDF statement, or other supporting proof.</p>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <input type="hidden" name="ticket_id" value="<?php echo htmlspecialchars($ticket['ticket_id']); ?>">

                            <label style="display:block;font-size:13px;color:#475569;margin-bottom:6px;">Request Type</label>
                            <select name="request_type" required>
                                <option value="">Select request type</option>
                                <?php foreach ($requestTypeOptions as $value => $label): ?>
                                    <option value="<?php echo htmlspecialchars($value); ?>" <?php echo (($_POST['request_type'] ?? '') === $value) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>

                            <div class="space"></div>

                            <label style="display:block;font-size:13px;color:#475569;margin-bottom:6px;">Request Title</label>
                            <input type="text" name="request_title" value="<?php echo htmlspecialchars($_POST['request_title'] ?? ''); ?>" placeholder="Example: Beneficiary Wallet Statement Required" required>

                            <div class="space"></div>

                            <label style="display:block;font-size:13px;color:#475569;margin-bottom:6px;">Officer Message / Reason</label>
                            <textarea name="request_message" placeholder="Write a clear professional request explaining why the customer must upload the requested proof." required><?php echo htmlspecialchars($_POST['request_message'] ?? ''); ?></textarea>

                            <div class="space"></div>

                            <button type="submit">Create Verification Request & Notify Customer</button>
                        </form>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
