<?php
include 'header.php';

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

require_once 'db/config.php';
require_once 'includes/currency_helper.php';
$user_id = $_SESSION['user_id'];

// Step 1: Handle initial order creation from deposit.php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount']) && !isset($_GET['order_id'])) {
    $amount = (float)$_POST['amount'];
    $type = $_POST['type'] ?? 'fiat';
    $currency = $_POST['currency'] ?? 'USDT';
    
    $fiat_rates = get_fiat_rates();
    $rate = $fiat_rates[$currency] ?? 1.0;
    $usdt_amount = ($rate > 0) ? ($amount / $rate) : $amount;
    
    $expires_at = date('Y-m-d H:i:s', strtotime('+30 minutes'));
    
    // Status starts as 'matching' (待匹配)
    $stmt = db()->prepare("INSERT INTO fiat_orders (user_id, amount, usdt_amount, exchange_rate, currency, status, expires_at, created_at) VALUES (?, ?, ?, ?, ?, 'matching', ?, CURRENT_TIMESTAMP)");
    $stmt->execute([$user_id, $amount, $usdt_amount, $rate, $currency, $expires_at]);
    $order_id = db()->lastInsertId();
    
    // Immediate notification to admin (用户一点击确认，后台立刻收到请求)
    $msg = "[RECHARGE_NOTIFICATION] 🚨 新充值申请! 用户 {$_SESSION['email']} (UID: {$_SESSION['uid']}) 正在等待匹配: **$amount $currency**。请尽快分配收款账户。";
    $stmt = db()->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'user', ?)");
    $stmt->execute([$user_id, $msg]);
    
    header("Location: matching.php?order_id=" . $order_id);
    exit;
}

$order_id = $_GET['order_id'] ?? null;
if (!$order_id) {
    header("Location: deposit.php");
    exit;
}

$stmt = db()->prepare("SELECT * FROM fiat_orders WHERE id = ? AND user_id = ?");
$stmt->execute([$order_id, $user_id]);
$order = $stmt->fetch();

if (!$order) {
    header("Location: deposit.php");
    exit;
}

if ($order['status'] === 'completed') {
    header("Location: profile.php");
    exit;
}

// Step 6: Handle Proof Submission (已提交凭证)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['proof'])) {
    $file = $_FILES['proof'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg', 'jpeg', 'png', 'gif'];
    
    if (in_array($ext, $allowed)) {
        $filename = 'proof_' . $order_id . '_' . time() . '.' . $ext;
        $target = 'assets/images/proofs/' . $filename;
        
        if (!is_dir('assets/images/proofs/')) mkdir('assets/images/proofs/', 0775, true);
        
        if (move_uploaded_file($file['tmp_name'], $target)) {
            $stmt = db()->prepare("UPDATE fiat_orders SET proof_image = ?, status = 'submitting' WHERE id = ?");
            $stmt->execute(['assets/images/proofs/' . $filename, $order_id]);
            
            $msg = "[RECHARGE_SUBMITTED] ✅ 用户已完成转账并提交凭证 (订单 #$order_id)。请进入后台核对。";
            $stmt = db()->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'user', ?)");
            $stmt->execute([$user_id, $msg]);
            
            header("Location: matching.php?order_id=" . $order_id);
            exit;
        }
    }
}

$stmt = db()->prepare("SELECT * FROM messages WHERE user_id = ? AND message NOT LIKE '[RECHARGE_%' ORDER BY created_at ASC");
$stmt->execute([$user_id]);
$messages = $stmt->fetchAll();
?>

<main style="background: #0b0e11; min-height: calc(100vh - 64px); padding: 40px 20px;">
    
    <!-- Step 4: MANDATORY LOCK OVERLAY for matched status (已匹配) -->
    <?php if ($order['status'] === 'matched' || ($order['bank_account_info'] && $order['status'] === 'matching')): ?>
    <div id="mandatory-lock" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: #0b0e11; z-index: 100000; overflow-y: auto; padding: 20px;">
        <div style="max-width: 600px; margin: 20px auto;">
            <div style="background: #161a1e; border-radius: 32px; border: 1px solid rgba(255,255,255,0.1); overflow: hidden; box-shadow: 0 40px 100px rgba(0,0,0,0.8);">
                
                <!-- Success Header -->
                <div style="background: linear-gradient(135deg, #00c087, #008960); padding: 40px 30px; text-align: center; color: white; position: relative; overflow: hidden;">
                    <div style="position: absolute; top: -50px; right: -50px; width: 150px; height: 150px; background: rgba(255,255,255,0.05); border-radius: 50%;"></div>
                    <div style="width: 80px; height: 80px; background: rgba(255,255,255,0.2); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; border: 3px solid white; box-shadow: 0 10px 20px rgba(0,0,0,0.2);">
                        <i class="fas fa-check" style="font-size: 35px;"></i>
                    </div>
                    <h2 style="margin: 0; font-size: 2rem; font-weight: 900; letter-spacing: -0.5px;">账户匹配成功</h2>
                    <p style="margin: 10px 0 0; opacity: 0.9; font-size: 15px; font-weight: 500;">请按以下信息完成转账并上传凭证</p>
                </div>

                <div style="padding: 40px;">
                    <!-- Step Indicator -->
                    <div style="display: flex; justify-content: space-between; margin-bottom: 40px; position: relative;">
                        <div style="position: absolute; top: 12px; left: 0; width: 100%; height: 2px; background: rgba(255,255,255,0.05); z-index: 1;"></div>
                        <div style="z-index: 2; text-align: center; width: 33%;">
                            <div style="width: 26px; height: 26px; background: #00c087; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px; font-size: 12px; font-weight: bold; border: 4px solid #161a1e;">1</div>
                            <div style="font-size: 11px; color: #00c087; font-weight: bold;">查看账户</div>
                        </div>
                        <div style="z-index: 2; text-align: center; width: 33%;">
                            <div id="step-dot-2" style="width: 26px; height: 26px; background: #2b3139; color: #848e9c; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px; font-size: 12px; font-weight: bold; border: 4px solid #161a1e;">2</div>
                            <div id="step-text-2" style="font-size: 11px; color: #848e9c; font-weight: bold;">完成支付</div>
                        </div>
                        <div style="z-index: 2; text-align: center; width: 33%;">
                            <div id="step-dot-3" style="width: 26px; height: 26px; background: #2b3139; color: #848e9c; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px; font-size: 12px; font-weight: bold; border: 4px solid #161a1e;">3</div>
                            <div id="step-text-3" style="font-size: 11px; color: #848e9c; font-weight: bold;">上传凭证</div>
                        </div>
                    </div>

                    <!-- Amount Highlight -->
                    <div style="background: rgba(240, 185, 11, 0.05); padding: 30px; border-radius: 24px; border: 1px solid rgba(240, 185, 11, 0.2); text-align: center; margin-bottom: 35px; box-shadow: inset 0 0 20px rgba(0,0,0,0.2);">
                        <div style="font-size: 12px; color: #f0b90b; font-weight: bold; margin-bottom: 15px; text-transform: uppercase; letter-spacing: 2px;">应转账金额 / Amount Due</div>
                        <div style="font-size: 3rem; font-weight: 900; color: white; display: flex; align-items: baseline; justify-content: center; gap: 10px;">
                            <?php echo number_format($order['amount'], 2); ?> <span style="font-size: 20px; color: #f0b90b;"><?php echo $order['currency']; ?></span>
                        </div>
                        <div style="font-size: 13px; color: #848e9c; margin-top: 15px;"><i class="fas fa-exclamation-circle"></i> 请务必转入精确金额，包含小数点</div>
                    </div>

                    <!-- Bank Details -->
                    <div style="background: #0b0e11; padding: 30px; border-radius: 24px; border: 1px solid rgba(255,255,255,0.05); margin-bottom: 35px; position: relative;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
                            <div style="font-weight: 800; color: #848e9c; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;"><i class="fas fa-university" style="margin-right: 8px;"></i> 收款账户信息</div>
                            <button onclick="copyToClipboard('<?php echo str_replace(["\r", "\n"], ' ', $order['bank_account_info']); ?>')" style="background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: white; padding: 8px 16px; border-radius: 12px; font-size: 12px; cursor: pointer; transition: 0.2s; font-weight: bold;">
                                <i class="fas fa-copy"></i> 复制
                            </button>
                        </div>
                        <div style="font-size: 1.2rem; line-height: 2; color: white; font-family: 'Roboto Mono', monospace; background: rgba(255,255,255,0.02); padding: 20px; border-radius: 16px;">
                            <?php echo nl2br(htmlspecialchars($order['bank_account_info'])); ?>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div id="action-area">
                        <button onclick="showUploadForm()" style="width: 100%; padding: 24px; background: #00c087; color: white; border: none; border-radius: 20px; font-size: 1.3rem; font-weight: 900; cursor: pointer; box-shadow: 0 15px 35px rgba(0,192,135,0.4); transition: 0.3s; transform: perspective(1px) translateZ(0);">
                            我已完成转账，去上传凭证
                        </button>
                        <p style="text-align: center; color: #5e6673; font-size: 12px; margin-top: 20px;">
                            <i class="fas fa-lock"></i> 资金安全由区块链技术加密保护
                        </p>
                    </div>

                    <!-- Step 5: Hidden Upload Form (上传转账凭证界面) -->
                    <div id="upload-form-container" style="display: none; animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1);">
                        <div style="text-align: center; margin-bottom: 30px;">
                            <h3 style="margin: 0 0 10px 0; font-size: 1.5rem; font-weight: 900;">上传转账凭证</h3>
                            <p style="color: #848e9c; font-size: 14px;">请上传包含交易单号、金额、时间的支付截图</p>
                        </div>
                        <form method="POST" enctype="multipart/form-data" id="main-proof-form">
                            <div id="upload-dropzone" style="background: #0b0e11; border: 2px dashed rgba(255,255,255,0.1); border-radius: 24px; padding: 50px 30px; text-align: center; cursor: pointer; margin-bottom: 30px; transition: 0.3s;" onclick="document.getElementById('file-input').click()">
                                <div id="file-idle">
                                    <div style="width: 80px; height: 80px; background: rgba(132, 142, 156, 0.1); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px;">
                                        <i class="fas fa-cloud-upload-alt" style="font-size: 40px; color: #848e9c;"></i>
                                    </div>
                                    <div style="font-weight: 900; font-size: 18px; color: white;">点击选择转账截图</div>
                                    <div style="font-size: 13px; color: #5e6673; margin-top: 8px;">支持 JPG, PNG, JPEG 格式</div>
                                </div>
                                <div id="file-selected" style="display: none;">
                                    <div style="width: 80px; height: 80px; background: rgba(0, 192, 135, 0.1); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px;">
                                        <i class="fas fa-file-image" style="font-size: 40px; color: #00c087;"></i>
                                    </div>
                                    <div style="font-weight: 900; font-size: 18px; color: #00c087;" id="selected-name"></div>
                                    <div style="font-size: 13px; color: #848e9c; margin-top: 8px;">文件已就绪，点击重新选择</div>
                                </div>
                                <input type="file" name="proof" id="file-input" accept="image/*" style="display: none;" onchange="updateFilePreview(this)">
                            </div>
                            
                            <!-- 逻辑限制：没有图片不允许提交 -->
                            <button type="submit" id="final-submit" disabled style="width: 100%; padding: 22px; background: #2b3139; color: #5e6673; border: none; border-radius: 20px; font-size: 1.2rem; font-weight: 900; cursor: not-allowed; transition: 0.3s; box-shadow: 0 10px 30px rgba(0,0,0,0.2);">
                                确认提交并通知客服
                            </button>
                            <button type="button" onclick="hideUploadForm()" style="width: 100%; margin-top: 20px; background: transparent; color: #848e9c; border: none; font-size: 14px; cursor: pointer; font-weight: bold;">
                                <i class="fas fa-arrow-left"></i> 返回查看账户
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div style="max-width: 1200px; margin: 0 auto; background: #161a1e; border: 1px solid rgba(255,255,255,0.08); border-radius: 32px; height: 85vh; display: grid; grid-template-columns: 1fr 400px; overflow: hidden; box-shadow: 0 40px 100px rgba(0,0,0,0.6);">
        
        <!-- Left Panel: Status Info -->
        <div style="display: flex; flex-direction: column; background: #0b0e11; border-right: 1px solid rgba(255,255,255,0.08);">
            
            <div style="padding: 25px 40px; border-bottom: 1px solid rgba(255,255,255,0.08); background: #161a1e; display: flex; align-items: center; justify-content: space-between;">
                <div style="display: flex; align-items: center; gap: 15px;">
                    <div style="width: 45px; height: 45px; background: var(--primary-color); border-radius: 12px; display: flex; align-items: center; justify-content: center; color: white;">
                        <i class="fas fa-shield-alt"></i>
                    </div>
                    <div>
                        <div style="font-weight: 800; font-size: 16px;">安全充值通道</div>
                        <div style="font-size: 10px; color: #848e9c; font-family: monospace;">#<?php echo $order_id; ?></div>
                    </div>
                </div>
                <div style="text-align: right;">
                    <div id="countdown" style="font-size: 1.4rem; font-weight: 900; color: #f0b90b; font-family: monospace;">30:00</div>
                    <div style="font-size: 10px; color: #848e9c;">剩余支付时间</div>
                </div>
            </div>

            <div style="flex: 1; overflow-y: auto; padding: 60px;">
                <!-- Step 2: 前端显示“匹配中” (待匹配) -->
                <?php if ($order['status'] === 'matching' && !$order['bank_account_info']): ?>
                    <div style="text-align: center;">
                        <div class="loader-container" style="margin-bottom: 40px;">
                            <div class="loader"></div>
                            <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center;">
                                <i class="fas fa-user-clock" style="font-size: 40px; color: var(--primary-color);"></i>
                            </div>
                        </div>
                        <h2 style="font-size: 2.2rem; font-weight: 900; margin-bottom: 20px;">正在为您匹配收款账户</h2>
                        <div style="background: rgba(255,255,255,0.02); padding: 25px; border-radius: 20px; border: 1px solid rgba(255,255,255,0.05); max-width: 500px; margin: 0 auto;">
                            <p style="color: #848e9c; font-size: 16px; line-height: 1.8; margin: 0;">
                                系统正在为您对接在线财务专员，匹配成功后将自动弹出收款账户详情，请保持页面开启不要离开。
                            </p>
                        </div>
                        <div style="margin-top: 40px; display: flex; justify-content: center; gap: 15px;">
                            <div class="dot-typing"></div>
                        </div>
                    </div>
                <?php elseif ($order['status'] === 'submitting'): ?>
                    <div style="text-align: center;">
                        <div style="width: 140px; height: 140px; background: rgba(0, 192, 135, 0.1); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 35px; border: 2px solid rgba(0, 192, 135, 0.2);">
                            <i class="fas fa-file-invoice-dollar" style="font-size: 60px; color: #00c087;"></i>
                        </div>
                        <h2 style="font-size: 2.2rem; font-weight: 900; margin-bottom: 20px;">支付凭证已提交</h2>
                        <p style="color: #848e9c; font-size: 16px; line-height: 1.8; max-width: 500px; margin: 0 auto;">
                            我们已收到您的转账凭证，财务人员正在核实入账情况。通常在 5-10 分钟内完成，完成后您的余额将自动增加。
                        </p>
                        <div style="margin-top: 50px; display: flex; gap: 20px; justify-content: center;">
                            <a href="profile.php" style="background: var(--primary-color); color: white; padding: 18px 45px; border-radius: 16px; text-decoration: none; font-weight: 900; box-shadow: 0 10px 25px rgba(0,82,255,0.3);">查看我的钱包</a>
                            <a href="chat.php" style="background: #2b3139; color: white; padding: 18px 45px; border-radius: 16px; text-decoration: none; font-weight: 900;">联系人工客服</a>
                        </div>
                    </div>
                <?php elseif ($order['status'] === 'rejected'): ?>
                    <div style="text-align: center;">
                        <div style="width: 140px; height: 140px; background: rgba(246, 70, 93, 0.1); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 35px; border: 2px solid rgba(246, 70, 93, 0.2);">
                            <i class="fas fa-times-circle" style="font-size: 60px; color: #f6465d;"></i>
                        </div>
                        <h2 style="font-size: 2.2rem; font-weight: 900; margin-bottom: 20px; color: #f6465d;">订单审核未通过</h2>
                        <p style="color: #848e9c; font-size: 16px; line-height: 1.8; max-width: 500px; margin: 0 auto;">
                            非常抱歉，您的充值申请未能通过。可能是因为凭证不清晰、金额不匹配或转账未到账。
                        </p>
                        <a href="deposit.php" style="display: inline-block; margin-top: 50px; background: #f6465d; color: white; padding: 18px 45px; border-radius: 16px; text-decoration: none; font-weight: 900;">重新发起充值</a>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Right Panel: Chat -->
        <div style="display: flex; flex-direction: column; background: #161a1e;">
            <div style="padding: 20px 25px; border-bottom: 1px solid rgba(255,255,255,0.08); background: #1e2329; display: flex; align-items: center; gap: 12px;">
                <div style="width: 10px; height: 10px; background: #00c087; border-radius: 50%; box-shadow: 0 0 10px #00c087;"></div>
                <div style="font-weight: bold; font-size: 14px;">在线客服 (Online)</div>
            </div>

            <div id="chat-box" style="flex: 1; overflow-y: auto; padding: 25px; display: flex; flex-direction: column; gap: 15px; background: #0b0e11;">
                <?php foreach ($messages as $m):
                    $align = $m['sender'] === 'user' ? 'flex-end' : 'flex-start';
                    $bg = $m['sender'] === 'user' ? 'var(--primary-color)' : '#2b3139';
                ?>
                    <div style="align-self: <?php echo $align; ?>; max-width: 85%;">
                        <div style="padding: 12px 16px; border-radius: 15px; background: <?php echo $bg; ?>; color: white; font-size: 14px; line-height: 1.5;">
                            <?php echo nl2br(htmlspecialchars($m['message'])); ?>
                        </div>
                        <div style="font-size: 10px; color: #5e6673; margin-top: 5px; text-align: <?php echo $m['sender'] === 'user' ? 'right' : 'left'; ?>;">
                            <?php echo date('H:i', strtotime($m['created_at'])); ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <div style="padding: 20px; background: #1e2329;">
                <form id="chat-form" style="display: flex; gap: 10px;">
                    <input type="text" id="chat-input" placeholder="输入消息..." style="flex: 1; background: #0b0e11; border: 1px solid rgba(255,255,255,0.1); border-radius: 10px; padding: 12px 15px; color: white; outline: none;">
                    <button type="submit" style="background: var(--primary-color); border: none; color: white; width: 45px; height: 45px; border-radius: 10px; cursor: pointer;">
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </form>
            </div>
        </div>
    </div>
</main>

<style>
    @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    @keyframes slideUp { from { transform: translateY(40px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
    .loader-container { position: relative; width: 120px; height: 120px; margin: 0 auto; }
    .loader { width: 120px; height: 120px; border: 4px solid rgba(0,82,255,0.05); border-top-color: var(--primary-color); border-radius: 50%; animation: spin 1.5s cubic-bezier(0.68, -0.55, 0.265, 1.55) infinite; }
    
    .dot-typing { position: relative; left: -9999px; width: 10px; height: 10px; border-radius: 5px; background-color: var(--primary-color); color: var(--primary-color); box-shadow: 9984px 0 0 0 var(--primary-color), 9999px 0 0 0 var(--primary-color), 10014px 0 0 0 var(--primary-color); animation: dot-typing 1.5s infinite linear; }
    @keyframes dot-typing { 0% { box-shadow: 9984px 0 0 0 var(--primary-color), 9999px 0 0 0 var(--primary-color), 10014px 0 0 0 var(--primary-color); } 16.667% { box-shadow: 9984px -10px 0 0 var(--primary-color), 9999px 0 0 0 var(--primary-color), 10014px 0 0 0 var(--primary-color); } 33.333% { box-shadow: 9984px 0 0 0 var(--primary-color), 9999px 0 0 0 var(--primary-color), 10014px 0 0 0 var(--primary-color); } 50% { box-shadow: 9984px 0 0 0 var(--primary-color), 9999px -10px 0 0 var(--primary-color), 10014px 0 0 0 var(--primary-color); } 66.667% { box-shadow: 9984px 0 0 0 var(--primary-color), 9999px 0 0 0 var(--primary-color), 10014px 0 0 0 var(--primary-color); } 83.333% { box-shadow: 9984px 0 0 0 var(--primary-color), 9999px 0 0 0 var(--primary-color), 10014px -10px 0 0 var(--primary-color); } 100% { box-shadow: 9984px 0 0 0 var(--primary-color), 9999px 0 0 0 var(--primary-color), 10014px 0 0 0 var(--primary-color); } }
    
    body { overflow: hidden; } 
</style>

<script>
    // Copy function
    function copyToClipboard(text) {
        const el = document.createElement('textarea');
        el.value = text;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        alert('复制成功 / Copied');
    }

    // Force Lock Logic
    const isMatched = <?php echo ($order['bank_account_info'] ? 'true' : 'false'); ?>;
    const status = '<?php echo $order['status']; ?>';
    
    if (isMatched && status !== 'submitting' && status !== 'completed' && status !== 'rejected') {
        // Prevent back button and refresh alert
        window.history.pushState(null, null, window.location.href);
        window.onpopstate = function() {
            window.history.pushState(null, null, window.location.href);
        };
        window.onbeforeunload = function() {
            return "交易正在进行中，请勿离开！";
        };
    }

    // Polling for status updates
    setInterval(() => {
        fetch('api/check_order_status.php?order_id=<?php echo $order_id; ?>')
            .then(r => r.json())
            .then(data => {
                if (data.status === 'completed') {
                    window.onbeforeunload = null;
                    location.href = 'profile.php';
                } else if (data.status === 'rejected' && status !== 'rejected') {
                    location.reload();
                } else if (data.status === 'matched' && status === 'matching') {
                    location.reload(); // Trigger mandatory Step 4 popup
                } else if (data.bank_account_info && !isMatched) {
                    location.reload(); // Admin matched while polling
                }
            });
    }, 3000);

    // Countdown logic
    let expiresAt = new Date('<?php echo $order['expires_at']; ?>').getTime();
    function updateCountdown() {
        let now = new Date().getTime();
        let diff = expiresAt - now;
        let el = document.getElementById('countdown');
        if (!el) return;
        if (diff <= 0) { el.innerText = "00:00"; el.style.color = "#f6465d"; return; }
        let mins = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        let secs = Math.floor((diff % (1000 * 60)) / 1000);
        el.innerText = (mins < 10 ? "0" + mins : mins) + ":" + (secs < 10 ? "0" + secs : secs);
    }
    updateCountdown();
    setInterval(updateCountdown, 1000);

    // Upload Form Handlers
    function showUploadForm() {
        document.getElementById('action-area').style.display = 'none';
        document.getElementById('upload-form-container').style.display = 'block';
        
        // Update Steps
        document.getElementById('step-dot-2').style.background = '#00c087';
        document.getElementById('step-dot-2').style.color = 'white';
        document.getElementById('step-text-2').style.color = '#00c087';
    }
    
    function hideUploadForm() {
        document.getElementById('action-area').style.display = 'block';
        document.getElementById('upload-form-container').style.display = 'none';
        
        // Revert Steps
        document.getElementById('step-dot-2').style.background = '#2b3139';
        document.getElementById('step-dot-2').style.color = '#848e9c';
        document.getElementById('step-text-2').style.color = '#848e9c';
    }
    
    function updateFilePreview(input) {
        if (input.files && input.files[0]) {
            document.getElementById('file-idle').style.display = 'none';
            document.getElementById('file-selected').style.display = 'block';
            document.getElementById('selected-name').innerText = input.files[0].name;
            
            const btn = document.getElementById('final-submit');
            btn.disabled = false;
            btn.style.background = '#00c087';
            btn.style.color = 'white';
            btn.style.cursor = 'pointer';
            btn.style.boxShadow = '0 10px 20px rgba(0,192,135,0.2)';
            
            // Step 3 active
            document.getElementById('step-dot-3').style.background = '#00c087';
            document.getElementById('step-dot-3').style.color = 'white';
            document.getElementById('step-text-3').style.color = '#00c087';
            
            // Highlight dropzone
            document.getElementById('upload-dropzone').style.borderColor = '#00c087';
            document.getElementById('upload-dropzone').style.background = 'rgba(0,192,135,0.02)';
        }
    }

    // Chat Logic
    const chatBox = document.getElementById('chat-box');
    chatBox.scrollTop = chatBox.scrollHeight;

    document.getElementById('chat-form').onsubmit = function(e) {
        e.preventDefault();
        const input = document.getElementById('chat-input');
        const msg = input.value.trim();
        if (!msg) return;

        const time = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
        const html = `
            <div style="align-self: flex-end; max-width: 85%;">
                <div style="padding: 12px 16px; border-radius: 15px; background: var(--primary-color); color: white; font-size: 14px; line-height: 1.5;">${msg}</div>
                <div style="font-size: 10px; color: #5e6673; margin-top: 5px; text-align: right;">
                    ${time}
                </div>
            </div>
        `;
        chatBox.insertAdjacentHTML('beforeend', html);
        chatBox.scrollTop = chatBox.scrollHeight;
        input.value = '';

        fetch('chat.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'message=' + encodeURIComponent(msg)
        });
    };
</script>

<?php include 'footer.php'; ?>