<?php
/**
 * DICHVUGIARE.SHOP - HỆ THỐNG 12 CẤP ĐỘ VIP ĐẶC QUYỀN
 */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// CẤU HÌNH ĐẦY ĐỦ 12 CẤP ĐỘ VIP
$vip_packages = [
    'VIP1'  => ['name' => 'VIP 1',  'months' => 1,  'price' => 5000,  'hot' => false, 'color' => 'from-cyan-500 to-blue-600', 'text' => 'text-cyan-400'],
    'VIP2'  => ['name' => 'VIP 2',  'months' => 2,  'price' => 10000, 'hot' => false, 'color' => 'from-cyan-500 to-blue-600', 'text' => 'text-cyan-400'],
    'VIP3'  => ['name' => 'VIP 3',  'months' => 3,  'price' => 14000, 'hot' => true,  'color' => 'from-indigo-500 to-purple-600', 'text' => 'text-indigo-400'], 
    'VIP4'  => ['name' => 'VIP 4',  'months' => 4,  'price' => 18000, 'hot' => false, 'color' => 'from-indigo-500 to-purple-600', 'text' => 'text-indigo-400'],
    'VIP5'  => ['name' => 'VIP 5',  'months' => 5,  'price' => 22000, 'hot' => false, 'color' => 'from-indigo-500 to-purple-600', 'text' => 'text-indigo-400'],
    'VIP6'  => ['name' => 'VIP 6',  'months' => 6,  'price' => 25000, 'hot' => true,  'color' => 'from-purple-500 to-pink-600', 'text' => 'text-purple-400'], 
    'VIP7'  => ['name' => 'VIP 7',  'months' => 7,  'price' => 29000, 'hot' => false, 'color' => 'from-purple-500 to-pink-600', 'text' => 'text-purple-400'],
    'VIP8'  => ['name' => 'VIP 8',  'months' => 8,  'price' => 33000, 'hot' => false, 'color' => 'from-purple-500 to-pink-600', 'text' => 'text-purple-400'],
    'VIP9'  => ['name' => 'VIP 9',  'months' => 9,  'price' => 36000, 'hot' => false, 'color' => 'from-amber-500 to-orange-600', 'text' => 'text-amber-400'],
    'VIP10' => ['name' => 'VIP 10', 'months' => 10, 'price' => 39000, 'hot' => false, 'color' => 'from-amber-500 to-orange-600', 'text' => 'text-amber-400'],
    'VIP11' => ['name' => 'VIP 11', 'months' => 11, 'price' => 42000, 'hot' => false, 'color' => 'from-amber-500 to-orange-600', 'text' => 'text-amber-400'],
    'VIP12' => ['name' => 'VIP 12', 'months' => 12, 'price' => 45000, 'hot' => true,  'color' => 'from-red-500 to-amber-500', 'text' => 'text-rose-400'], 
];

// XỬ LÝ GỬI DỮ LIỆU AJAX MUA GÓI
if (isset($_POST['action']) && $_POST['action'] === 'buy_vip') {
    // Nhúng file cấu hình database của sếp (Tự động quét tìm file db.php)
    if (file_exists('DB.php')) { require_once 'DB.php'; } 
    else if (file_exists('../DB.php')) { require_once '../DB.php'; }
    else if (file_exists('Config/db.php')) { require_once 'Config/DB.php'; }
    else if (file_exists('../Config/DB.php')) { require_once '../Config/DB.php'; }

    header('Content-Type: application/json');
    
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['status' => 'error', 'msg' => 'Vui lòng đăng nhập để thực hiện giao dịch!']);
        exit();
    }

    $user_id = $_SESSION['user_id'];
    $pkg_key = isset($_POST['package']) ? strtoupper(trim($_POST['package'])) : '';

    if (!array_key_exists($pkg_key, $vip_packages)) {
        echo json_encode(['status' => 'error', 'msg' => 'Gói VIP không tồn tại trên hệ thống!']);
        exit();
    }

    $package = $vip_packages[$pkg_key];
    $price = $package['price'];
    $months_to_add = $package['months'];

    $stmt = $conn->prepare("SELECT money, vip_package, vip_expired FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        echo json_encode(['status' => 'error', 'msg' => 'Tài khoản người dùng không hợp lệ!']);
        exit();
    }

    if ($user['money'] < $price) {
        echo json_encode(['status' => 'error', 'msg' => 'Số dư không đủ! Sếp cần nạp thêm tiền để kích hoạt gói này.']);
        exit();
    }

    $current_time = time();
    $base_time = $current_time;

    if (strtoupper($user['vip_package'] ?? '') === $pkg_key && !empty($user['vip_expired'])) {
        $old_expired = strtotime($user['vip_expired']);
        if ($old_expired > $current_time) {
            $base_time = $old_expired;
        }
    }

    $new_expired_date = date("Y-m-d H:i:s", strtotime("+$months_to_add month", $base_time));

    try {
        $conn->beginTransaction();

        $minus_money = $conn->prepare("UPDATE users SET money = money - ? WHERE id = ? AND money >= ?");
        $minus_money->execute([$price, $user_id, $price]);

        if ($minus_money->rowCount() === 0) {
            throw new Exception('Giao dịch thất bại do số dư tài khoản thay đổi đột ngột!');
        }

        $update_vip = $conn->prepare("UPDATE users SET vip_package = ?, vip_expired = ? WHERE id = ?");
        $update_vip->execute([$pkg_key, $new_expired_date, $user_id]);

        $conn->commit();
        echo json_encode([
            'status' => 'success', 
            'msg' => 'Kích hoạt thành công ' . $package['name'] . '! Hạn dùng mới: ' . date('d/m/Y H:i', strtotime($new_expired_date))
        ]);
        exit();

    } catch (Exception $e) {
        $conn->rollBack();
        echo json_encode(['status' => 'error', 'msg' => $e->getMessage()]);
        exit();
    }
}

// NHÚNG GIA DIỆN HEADER (File Head.php này đã tự gọi db.php rồi nên ta không cần gọi lại nữa)
if (file_exists('Headphone/Head.php')) {
    require_once 'Headphone/Head.php';
} else {
    require_once '../Headphone/Head.php';
}

$current_vip = strtoupper($user_data['vip_package'] ?? 'FREE');
$current_expired = !empty($user_data['vip_expired']) ? strtotime($user_data['vip_expired']) : null;
?>

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

<div class="relative z-10 space-y-6 max-w-7xl mx-auto px-2">
    
    <div class="text-center space-y-2">
        <h2 class="font-gaming text-2xl sm:text-4xl font-black tracking-widest text-transparent bg-clip-text bg-gradient-to-r from-amber-400 via-orange-500 to-yellow-500 uppercase drop-shadow-[0_0_15px_rgba(245,158,11,0.3)]">
            👑 ĐẤT THÁNH ĐẶC QUYỀN VIP 👑
        </h2>
        <p class="text-gray-400 text-xs sm:text-sm tracking-widest uppercase font-gaming">
            Mở khóa 12 tầng VIP — Càng lên cao chi phí càng rẻ, đặc quyền càng sâu!
        </p>
    </div>

        <div class="bg-[#130924]/80 backdrop-blur-md p-5 rounded-2xl border border-purple-900/40 flex flex-col sm:flex-row justify-between items-center gap-4">
        <div class="flex items-center gap-4">
            <div class="w-12 h-12 rounded-xl bg-gradient-to-br from-amber-400 to-orange-500 flex items-center justify-center text-black shadow-[0_0_15px_rgba(245,158,11,0.3)]">
                <i class="fa-solid fa-crown text-xl animate-pulse"></i>
            </div>
            <div>
                <span class="text-xs font-gaming uppercase tracking-widest text-gray-400 block">Cấp bậc hiện tại:</span>
                <span class="font-gaming text-lg font-black text-transparent bg-clip-text bg-gradient-to-r from-amber-400 to-yellow-400 uppercase">
                    <?= !empty($current_vip) ? $current_vip : 'FREE' ?> MEMBER
                </span>
            </div>
        </div>
        <div class="text-center sm:text-right font-gaming">
            <span class="text-[10px] text-gray-500 uppercase tracking-wider block mb-0.5">Trạng thái bảo hộ</span>
            <span class="text-xs font-bold">
                <?php 
                $real_time = time();
                // Nếu có gói VIP và thời gian hết hạn hợp lệ ở tương lai
                if ($current_vip == 'FREE') {
                    echo '<span class="text-gray-400"><i class="fa-solid fa-shield-halved mr-1"></i> Chưa kích hoạt VIP tháng</span>';
                } else {
                    echo '<span class="text-gray-400"><i class="fa-solid fa-shield-halved mr-1"></i> Đã Kích Hoạt '.$current_vip.' tháng</span>';
                }
                ?>
            </span>
        </div>
    </div>



    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        <?php foreach ($vip_packages as $key => $pkg): 
            $is_active_pkg = ($current_vip === $key && $current_expired && $current_expired > time());
        ?>
            <div class="bg-[#130924]/90 rounded-xl border border-purple-900/30 transition-all duration-200 hover:scale-[1.03] flex flex-col justify-between overflow-hidden relative group <?= $is_active_pkg ? 'border-amber-400 shadow-[0_0_20px_rgba(245,158,11,0.2)]' : 'hover:border-purple-500/50' ?>">
                
                <?php if($pkg['hot']): ?>
                    <div class="absolute top-2 left-2 bg-gradient-to-r from-red-500 to-orange-500 text-black font-gaming text-[9px] font-black tracking-widest uppercase px-2 py-0.5 rounded shadow-[0_0_10px_rgba(239,68,68,0.5)] animate-bounce z-20">
                        🔥 HOT
                    </div>
                <?php endif; ?>

                <?php if($is_active_pkg): ?>
                    <div class="absolute top-2 right-2 bg-emerald-500 text-black font-gaming text-[8px] font-black tracking-widest px-1.5 py-0.5 rounded z-20">
                        ACTIVE
                    </div>
                <?php endif; ?>

                <div class="p-4 space-y-3 pt-8 relative">
                    <div class="text-center">
                        <span class="font-gaming text-[10px] font-bold uppercase tracking-widest <?= $pkg['text'] ?> block"><?= $key ?> LEVEL</span>
                        <h4 class="font-gaming text-base font-black text-white uppercase tracking-wider"><?= $pkg['name'] ?></h4>
                    </div>

                    <div class="bg-black/40 p-2.5 rounded-lg border border-purple-950/60 text-center">
                        <div class="font-gaming text-xl font-black text-white select-all">
                            <?= number_format($pkg['price'], 0, ',', '.') ?><span class="text-xs font-bold text-gray-400 ml-0.5">đ</span>
                        </div>
                        <span class="text-[9px] text-gray-500 font-gaming uppercase tracking-widest block mt-0.5">Thời gian: +<?= $pkg['months'] ?> Tháng</span>
                    </div>

                    <div class="text-center text-[10px] text-gray-400 font-input bg-purple-950/20 py-1 rounded border border-purple-900/10">
                        Chỉ khoảng: <span class="text-emerald-400 font-bold"><?= number_format(round($pkg['price'] / $pkg['months']), 0, ',', '.') ?>đ</span> / tháng
                    </div>
                </div>

                <div class="p-4 pt-0">
                    <button type="button" onclick="buyVipPackage('<?= $key ?>', '<?= $pkg['name'] ?>')"
                        class="w-full py-2.5 rounded-lg text-black font-gaming font-black tracking-widest text-[11px] uppercase bg-gradient-to-r <?= $pkg['color'] ?> shadow-md hover:brightness-110 transition-all cursor-pointer">
                        <?= $is_active_pkg ? 'GIA HẠN GÓI' : 'KÍCH HOẠT' ?>
                    </button>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="text-center text-gray-600 text-xs font-input py-2">
        <p>* Hệ thống áp dụng hình thức cộng dồn thời gian tự động nếu sếp mua trùng một mã VIP liên tục.</p>
        <p>Hệ thống tự động trừ tiền qua số dư tài khoản thời gian thực.</p>
    </div>
</div>

<script>
function buyVipPackage(packageKey, packageName) {
    Swal.fire({
        title: 'XÁC NHẬN MUA GÓI?',
        text: `Hệ thống tiến hành trừ tiền từ ví và kích hoạt đặc quyền [${packageName}] vào tài khoản của sếp ngay!`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#f59e0b',
        cancelButtonColor: '#374151',
        confirmButtonText: 'XÁC NHẬN MUA',
        cancelButtonText: 'HỦY',
        background: '#130924',
        color: '#fff'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'ĐANG CẤU HÌNH...',
                allowOutsideClick: false,
                background: '#130924',
                color: '#fff',
                didOpen: () => { Swal.showLoading(); }
            });

            let formData = new FormData();
            formData.append('action', 'buy_vip');
            formData.append('package', packageKey);

            // Fetch rỗng tuyệt đối an toàn đường dẫn 100%
            fetch('', { method: 'POST', body: formData })
            .then(res => {
                if (!res.ok) {
                    throw new Error(`Mã lỗi HTTP: ${res.status}`);
                }
                return res.text();
            })
            .then(text => {
                try {
                    let data = JSON.parse(text);
                    if (data.status === 'success') {
                        Swal.fire({
                            title: 'THÀNH CÔNG!',
                            text: data.msg,
                            icon: 'success',
                            background: '#130924',
                            color: '#fff'
                        }).then(() => {
                            window.location.href = 'dashboard.php';
                        });
                    } else {
                        Swal.fire({
                            title: 'THẤT BẠI',
                            text: data.msg,
                            icon: 'error',
                            background: '#130924',
                            color: '#fff'
                        });
                    }
                } catch (e) {
                    // Hiển thị trực tiếp lỗi hệ thống từ Server nếu có phát sinh
                    Swal.fire({
                        title: 'CHI TIẾT LỖI PHP LÀ:',
                        html: `<div class="text-left bg-black/50 p-2 rounded text-xs overflow-auto max-h-40 text-red-400 font-mono select-all">${text}</div>`,
                        icon: 'error',
                        background: '#130924',
                        color: '#fff'
                    });
                }
            })
            .catch(err => {
                Swal.fire({
                    title: 'LỖI ĐƯỜNG TRUYỀN',
                    text: err.message,
                    icon: 'error',
                    background: '#130924',
                    color: '#fff'
                });
            });
        }
    });
}
</script>

<?php 
if (file_exists('Headphone/Footer.php')) {
    require_once 'Headphone/Footer.php'; 
} else {
    require_once '../Headphone/Footer.php'; 
}
?>
