<?php
/**
 * TGM BANKING - ACB API LINKER (VIP EXPIRED EDITION)
 */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../Headphone/Head.php'; 
require_once "../Class/ACB.php"; 
$ACB = new ACB();

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

$user_id = $_SESSION['user_id'];

// 1. LẤY THÔNG TIN VÀ KIỂM TRA HẠN VIP TỰ ĐỘNG
$user_query = $conn->prepare("SELECT vip_package, vip_expired FROM users WHERE id = ?");
$user_query->execute([$user_id]);
$user_info = $user_query->fetch(PDO::FETCH_ASSOC);

$vip_status = 'FREE';
$vip_time_left = '';
$is_vip_valid = false;

if ($user_info) {
    $vip_status = strtoupper($user_info['vip_package'] ?? 'FREE');
    
    if ($vip_status !== 'FREE' && !empty($user_info['vip_expired'])) {
        $expired_time = strtotime($user_info['vip_expired']);
        $current_time = time();
        
        if ($current_time > $expired_time) {
            // Đã hết thời hạn VIP -> Hạ cấp xuống FREE trực tiếp trong DB
            $update_vip = $conn->prepare("UPDATE users SET vip_package = 'FREE', vip_expired = NULL WHERE id = ?");
            $update_vip->execute([$user_id]);
            $vip_status = 'FREE';
        } else {
            // Còn hạn VIP hợp lệ
            $is_vip_valid = true;
            $vip_time_left = ' (Hạn đến: ' . date("d/m/Y H:i", $expired_time) . ')';
        }
    }
}

// 🔥 CHẶN ĐỨNG TUYỆT ĐỐI: Không phải VIP hoặc hết hạn thì đá sang trang mua VIP
if (!$is_vip_valid) {
    echo '<script>
        alert("Sếp ơi! Tính năng này chỉ dành cho tài khoản VIP còn hạn. Vui lòng kích hoạt gói trước nhé!");
        window.location.href = "mua-vip.php";
    </script>';
    exit();
}

$vip_badges = [
    'FREE'  => 'bg-gray-500/10 text-gray-400 border-gray-500/30',
    'VIP1'  => 'bg-cyan-500/10 text-cyan-400 border-cyan-500/30 font-bold shadow-[0_0_10px_rgba(34,211,238,0.2)]',
    'VIP2'  => 'bg-purple-500/10 text-purple-400 border-purple-500/30 font-bold shadow-[0_0_10px_rgba(168,85,247,0.2)]',
    'VIP3'  => 'bg-indigo-500/10 text-indigo-400 border-indigo-500/30 font-bold shadow-[0_0_10px_rgba(99,102,241,0.2)]',
    'VIP12' => 'bg-rose-500/10 text-rose-400 border-rose-500/30 font-black shadow-[0_0_15px_rgba(244,63,94,0.4)]'
];
$current_badge = isset($vip_badges[$vip_status]) ? $vip_badges[$vip_status] : $vip_badges['FREE'];

// 2. LẤY DANH SÁCH TÀI KHOẢN ĐÃ LIÊN KẾT
$result = $conn->prepare("SELECT * FROM account_acb WHERE user_id = ? ORDER BY id DESC");
$result->execute([$user_id]);

// Xử lý xóa liên kết bank
if (isset($_GET['delete'])) {
    $id_del = (int)$_GET['delete'];
    $del = $conn->prepare("DELETE FROM account_acb WHERE id = ? AND user_id = ?");
    $del->execute([$id_del, $user_id]);
    echo '<script>window.location.href = "thue-acb.php";</script>';
    exit();
}
?>

<div class="absolute top-48 left-10 w-72 h-72 bg-cyan-500/5 rounded-full blur-3xl pointer-events-none"></div>
<div class="absolute top-96 right-10 w-72 h-72 bg-pink-500/5 rounded-full blur-3xl pointer-events-none"></div>

<div class="relative z-10 space-y-8 max-w-7xl mx-auto px-2">
    
    <div class="text-center my-6 space-y-2">
        <h2 class="font-gaming text-xl sm:text-3xl font-black tracking-widest text-transparent bg-clip-text bg-gradient-to-r from-cyan-400 via-purple-400 to-pink-500 uppercase">
            ⚡ ACB API LINKER V2 ⚡
        </h2>
        
        <div class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full border <?= $current_badge ?> text-xs font-gaming tracking-wider uppercase">
            <i class="fa-solid fa-crown text-[10px]"></i> Cấp bậc: <?= $vip_status ?> MEMBER <?= $vip_time_left ?>
        </div>
    </div>

    <div class="bg-[#130924]/80 backdrop-blur-md p-6 sm:p-8 rounded-2xl border border-purple-900/40 neon-border-cyan space-y-5">
        <form id="formConnectBank" class="space-y-4">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-gray-400 text-xs uppercase font-gaming mb-2 tracking-wider">Tài khoản ACB</label>
                    <input type="text" id="acb_user" required autocomplete="off"
                        class="font-input w-full bg-[#0c0418] border border-purple-900/60 rounded-xl px-4 py-3 text-white placeholder-gray-600 focus:outline-none focus:border-cyan-400 transition-colors text-sm box-border" 
                        placeholder="Tên đăng nhập Bank...">
                </div>
                <div>
                    <label class="block text-gray-400 text-xs uppercase font-gaming mb-2 tracking-wider">Số tài khoản</label>
                    <input type="text" id="acb_stk" required autocomplete="off"
                        class="font-input w-full bg-[#0c0418] border border-purple-900/60 rounded-xl px-4 py-3 text-white placeholder-gray-600 focus:outline-none focus:border-cyan-400 transition-colors text-sm box-border" 
                        placeholder="Số tài khoản ngân hàng...">
                </div>
            </div>

            <div class="grid grid-cols-1 gap-4">
                <div>
                    <label class="block text-gray-400 text-xs uppercase font-gaming mb-2 tracking-wider">Mật khẩu ACB</label>
                    <input type="password" id="acb_pass" required
                        class="font-input w-full bg-[#0c0418] border border-purple-900/60 rounded-xl px-4 py-3 text-white placeholder-gray-600 focus:outline-none focus:border-cyan-400 transition-colors text-sm box-border" 
                        placeholder="••••••••">
                </div>
            </div>

            <button type="button" onclick="connectBank()" id="btnAction"
                class="w-full py-3.5 rounded-xl text-black font-gaming font-black tracking-widest text-sm uppercase bg-gradient-to-r from-cyan-400 to-blue-500 shadow-[0_0_15px_rgba(34,211,238,0.4)] hover:shadow-[0_0_25px_rgba(34,211,238,0.7)] transition-all transform hover:-translate-y-0.5 cursor-pointer">
                KÍCH HOẠT KẾT NỐI (MIỄN PHÍ VIP)
            </button>
        </form>
    </div>

    <div class="space-y-3">
        <h3 class="font-gaming text-sm sm:text-base font-bold tracking-widest text-purple-400 uppercase flex items-center gap-2">
            <span class="w-1.5 h-4 bg-purple-500 inline-block rounded-full"></span> Cổng API ACB Đang Hoạt Động
        </h3>

        <div class="w-full overflow-x-auto rounded-2xl bg-[#130924]/70 border border-purple-900/20 backdrop-blur-md">
            <table class="w-full border-collapse min-width-[1000px] text-center text-sm font-input">
                <thead>
                    <tr class="bg-black/40 font-gaming text-[11px] text-gray-400 tracking-wider uppercase border-b border-purple-900/30">
                        <th class="py-4 px-3 text-center">ID</th>
                        <th class="py-4 px-3 text-center">THÔNG TIN BANK</th>
                        <th class="py-4 px-3 text-center">SỐ DƯ (LIVE)</th>
                        <th class="py-4 px-3 text-center">API KEY</th>
                        <th class="py-4 px-3 text-center">HẠN THEO VIP</th>
                        <th class="py-4 px-3 text-center">TRẠNG THÁI</th>
                        <th class="py-4 px-3 text-center">THAO TÁC</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-purple-900/10">
                    <?php 
                    $has_rows = false;
                    while($row = $result->fetch(PDO::FETCH_ASSOC)): 
                        $has_rows = true;
                        
                        $is_live = (!empty($row['date_expired']) && strtotime($row['date_expired']) > time());
                        $display_bal = '<span class="text-rose-500 text-xs font-bold font-gaming uppercase">GÓI HẾT HẠN</span>';
                        
                        if ($is_live) {
                            $res_bal = $ACB->getsodu($row['token']);
                            $display_bal = '<span class="text-rose-500 text-xs font-bold font-gaming uppercase">HẾT HẠN PHIÊN</span>';
                            
                            if(isset($res_bal['data']) && is_array($res_bal['data'])){
                                foreach($res_bal['data'] as $account){
                                    if($account['accountNumber'] == $row['acb_stk']){
                                        $display_bal = '<span class="text-emerald-400 font-mono font-bold text-sm select-all">'.number_format($account['balance']).'</span> <small class="text-gray-500">đ</small>';
                                        break;
                                    }
                                }
                            }
                        }

                        $date_exp = !empty($row['date_expired']) ? date("d/m/Y H:i", strtotime($row['date_expired'])) : 'N/A';
                    ?>
                    <tr class="hover:bg-purple-950/10 transition-colors">
                        <td class="py-4 px-3 font-gaming font-bold text-cyan-400">#<?= $row['id'] ?></td>
                        <td class="py-4 px-3 text-center">
                            <div class="font-bold font-gaming text-sm text-cyan-300"><?= htmlspecialchars(strtoupper($row['acb_name'] ?? '')) ?></div>
                            <div class="font-mono text-xs text-gray-400 select-all"><?= htmlspecialchars($row['acb_stk'] ?? '') ?></div>
                        </td>
                        <td class="py-4 px-3"><?= $display_bal ?></td>
                        <td class="py-4 px-3">
                            <div class="inline-flex items-center gap-2 bg-emerald-500/5 px-3 py-1.5 rounded-lg border border-dashed border-emerald-500/20">
                                <span class="font-mono text-xs text-emerald-400 select-all" id="key-<?= $row['id'] ?>"><?= htmlspecialchars($row['api_key'] ?? '') ?></span>
                                <button class="text-cyan-400 hover:text-cyan-300 transition-colors cursor-pointer text-xs" onclick="copyKey('key-<?= $row['id'] ?>')" title="Copy API Key">
                                    <i class="fa-regular fa-copy"></i>
                                </button>
                            </div>
                        </td>
                        <td class="py-4 px-3 font-mono text-xs <?= $is_live ? 'text-emerald-400 font-bold' : 'text-rose-500 font-bold' ?>">
                            <?= $date_exp ?>
                        </td>
                        <td class="py-4 px-3">
                            <?php if($is_live): ?>
                                <span class="px-2.5 py-1 rounded bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 text-[10px] font-gaming font-bold tracking-wider">LIVE</span>
                            <?php else: ?>
                                <span class="px-2.5 py-1 rounded bg-rose-500/10 text-rose-500 border border-rose-500/20 text-[10px] font-gaming font-bold tracking-wider">EXPIRED</span>
                            <?php endif; ?>
                        </td>
                        <td class="py-4 px-3 text-center">
                            <div class="flex items-center justify-center gap-2">
                                <a href="mua-vip.php"
                                   class="inline-flex items-center justify-center h-8 px-2.5 rounded-lg bg-amber-500/10 text-amber-400 border border-amber-500/30 hover:bg-amber-400 hover:text-black font-gaming text-[10px] font-bold tracking-wider transition-all" title="Gia hạn VIP">
                                    <i class="fa-solid fa-arrow-up-trend-lines mr-1"></i> GIA HẠN VIP
                                </a>
                                <a href="get_history_acb?token=<?= urlencode($row['api_key'] ?? '') ?>" 
                                   class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-cyan-500/10 text-cyan-400 border border-cyan-500/30 hover:bg-cyan-400 hover:text-black transition-all text-xs" title="Lịch sử GD">
                                    <i class="fa-solid fa-clock-rotate-left"></i>
                                </a>
                                <button onclick="deleteLink(<?= $row['id'] ?>)" 
                                        class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-rose-500 hover:text-white transition-all text-xs cursor-pointer" title="Xóa Bank">
                                    <i class="fa-solid fa-trash-can"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; 
                    if (!$has_rows): ?>
                        <tr>
                            <td colspan="7" class="py-8 text-gray-500 font-gaming text-xs uppercase tracking-widest">Sếp chưa kết nối cổng ngân hàng nào trên hệ thống!</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
function copyKey(id) {
    const text = document.getElementById(id).innerText;
    navigator.clipboard.writeText(text).then(() => {
        Swal.fire({ toast: true, position: 'top-end', icon: 'success', title: 'Đã sao chép thành công API Key!', showConfirmButton: false, timer: 1500, background: '#130924', color: '#00ff88' });
    });
}

async function connectBank() {
    const user = document.getElementById('acb_user').value;
    const pass = document.getElementById('acb_pass').value;
    const stk = document.getElementById('acb_stk').value;

    if(!user || !pass || !stk) {
        return Swal.fire({ title: 'THIẾU THÔNG TIN', text: 'Vui lòng điền đầy đủ dữ liệu cấu hình!', icon: 'warning', background: '#130924', color: '#fff' });
    }

    const btn = document.getElementById('btnAction');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-circle-notch fa-spin mr-1"></i> ĐANG THIẾT LẬP KẾT NỐI...';
    
    let formData = new FormData();
    formData.append('type', 'Login');
    formData.append('acb_user', user);
    formData.append('acb_pass', pass);
    formData.append('acb_stk', stk); // Không truyền biến months nữa

    fetch('Api-Bank/add-acb.php', { method: 'POST', body: formData })
    .then(res => res.json())
    .then(data => {
        if(data.status == 'success') {
            Swal.fire({ title: 'LIÊN KẾT THÀNH CÔNG', text: data.msg, icon: 'success', background: '#130924', color: '#fff' }).then(() => location.reload());
        } else {
            Swal.fire({ title: 'THẤT BẠI', text: data.msg, icon: 'error', background: '#130924', color: '#fff' });
            btn.disabled = false;
            btn.innerHTML = 'KÍCH HOẠT KẾT NỐI NGAY';
        }
    })
    .catch(err => {
        Swal.fire({ title: 'LỖI HỆ THỐNG', text: 'Không thể truyền tải dữ liệu tới máy chủ!', icon: 'error', background: '#130924', color: '#fff' });
        btn.disabled = false;
        btn.innerHTML = 'KÍCH HOẠT KẾT NỐI NGAY';
    });
}

function deleteLink(id) {
    Swal.fire({ title: 'XÁC NHẬN GỠ LINK?', text: "Sếp chắc chắn muốn gỡ cấu hình bank này chứ?", icon: 'warning', showCancelButton: true, confirmButtonColor: '#f43f5e', cancelButtonColor: '#374151', confirmButtonText: 'XÓA LIÊN KẾT', cancelButtonText: 'HỦY BỎ', background: '#130924', color: '#fff' })
    .then((result) => { if (result.isConfirmed) window.location.href = '?delete=' + id; });
}
</script>

<?php 
require_once '../Headphone/Footer.php'; 
?>
