<?php
require_once 'common/config.php';
include 'common/header.php';

// ১. লগইন চেক
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$file_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$error_msg = "";
$success_msg = "";

// ২. ফাইল এবং ইউজার ডাটা চেক
$f_stmt = $conn->prepare("SELECT * FROM files WHERE id = ?");
$f_stmt->bind_param("i", $file_id);
$f_stmt->execute();
$file = $f_stmt->get_result()->fetch_assoc();

if (!$file) {
    $error_msg = "CRITICAL_ERROR: Asset Node Not Found!";
} else {
    // প্রাইজ ক্যালকুলেশন
    $price = $file['price'] - $file['discount'];
    
    // ইউজার অলরেডি কিনেছে কিনা চেক
    $p_check = $conn->query("SELECT id FROM purchases WHERE user_id = $user_id AND file_id = $file_id");
    
    if ($p_check->num_rows > 0) {
        header("Location: view-file.php?id=$file_id");
        exit();
    }

    // ইউজারের লেটেস্ট ব্যালেন্স চেক
    $u_res = $conn->query("SELECT balance FROM users WHERE id = $user_id");
    $user_data = $u_res->fetch_assoc();

    if ($user_data['balance'] < $price) {
        $error_msg = "TRANSACTION_FAILED: Insufficient Credits! Current Balance: ৳" . number_format($user_data['balance'], 2);
    } else {
        // ৩. ট্রানজেকশন শুরু (টাকা কাটা এবং পারচেজ রেকর্ড করা)
        $conn->begin_transaction();

        try {
            // টাকা কাটা
            $conn->query("UPDATE users SET balance = balance - $price WHERE id = $user_id");
            // পারচেজ টেবিলে এন্ট্রি
            $conn->query("INSERT INTO purchases (user_id, file_id) VALUES ($user_id, $file_id)");
            
            $conn->commit();
            $success_msg = "DECRYPTION_SUCCESS: Asset Unlocked Successfully!";
            
            // ৩ সেকেন্ড পর রিডাইরেক্ট
            header("Refresh: 2; url=view-file.php?id=$file_id");
        } catch (Exception $e) {
            $conn->rollback();
            $error_msg = "SYSTEM_FAILURE: Transaction Aborted!";
        }
    }
}
?>

<div class="flex items-center justify-center min-h-[calc(100vh-80px)] px-4">
    <div class="cyber-card w-full max-w-2xl p-8 md:p-12 text-center relative overflow-hidden border-b-4 <?php echo $error_msg ? 'border-red-500/50' : 'border-cyan-500/50'; ?>">
        
        <?php if ($error_msg): ?>
            <!-- এরর স্টেট -->
            <div class="relative z-10">
                <div class="w-20 h-20 bg-red-500/10 rounded-full flex items-center justify-center mx-auto mb-6 border border-red-500/30">
                    <i class="fa-solid fa-triangle-exclamation text-4xl text-red-500"></i>
                </div>
                <h2 class="text-2xl font-bold logo-font text-white uppercase mb-4">Access Denied</h2>
                <p class="text-xs md:text-sm text-red-400 font-bold uppercase tracking-[2px] mb-8"><?php echo $error_msg; ?></p>
                <div class="flex flex-col sm:flex-row gap-4 justify-center">
                    <a href="add-money.php" class="bg-cyan-600 hover:bg-cyan-500 text-white px-8 py-3 rounded-xl font-bold text-[10px] uppercase tracking-widest transition-all">Add Credits</a>
                    <a href="index.php" class="bg-slate-800 text-gray-400 px-8 py-3 rounded-xl font-bold text-[10px] uppercase tracking-widest transition-all">Cancel</a>
                </div>
            </div>
        <?php elseif ($success_msg): ?>
            <!-- সাকসেস স্টেট (প্রসেসিং এনিমেশনসহ) -->
            <div class="relative z-10">
                <div class="processing-loader mx-auto mb-8"></div>
                <h2 class="text-2xl md:text-3xl font-bold logo-font text-cyan-400 uppercase mb-4 animate-pulse">Decrypting Asset...</h2>
                <p class="text-[10px] md:text-xs text-gray-500 font-black uppercase tracking-[4px]"><?php echo $success_msg; ?></p>
                <p class="text-[9px] text-cyan-500/50 mt-10 uppercase tracking-[2px]">Redirecting to Secure Node...</p>
            </div>
        <?php endif; ?>

        <!-- ব্যাকগ্রাউন্ড গ্লো -->
        <div class="absolute inset-0 bg-gradient-to-b from-cyan-500/5 to-transparent pointer-events-none"></div>
    </div>
</div>

<style>
    .cyber-card {
        background: rgba(1, 10, 32, 0.9);
        backdrop-filter: blur(25px);
        border: 1px solid rgba(255, 255, 255, 0.05);
        border-radius: 2.5rem;
    }

    /* প্রসেসিং সার্কেল এনিমেশন */
    .processing-loader {
        width: 80px;
        height: 80px;
        border: 4px solid rgba(34, 211, 238, 0.1);
        border-left-color: #22d3ee;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        position: relative;
    }
    .processing-loader::after {
        content: '';
        position: absolute;
        inset: 10px;
        border: 2px solid rgba(34, 211, 238, 0.05);
        border-right-color: #22d3ee;
        border-radius: 50%;
        animation: spin 2s linear reverse infinite;
    }

    @keyframes spin {
        to { transform: rotate(360deg); }
    }
</style>

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