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

// ১. ইউজার লগইন না থাকলে লগইন পেজে রিডাইরেক্ট (সাথে বর্তমান পেজের লিংক)
if (!isset($_SESSION['user_id'])) {
    $current_page = basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'];
    header("Location: login.php?redirect=" . urlencode($current_page));
    exit();
}

include 'common/header.php';

// ২. আইডি চেক করা
if (!isset($_GET['id'])) {
    echo "<div class='flex items-center justify-center min-h-[60vh] px-4'>
            <div class='cyber-card p-10 border-red-500/50 text-red-500 font-bold uppercase tracking-widest text-center w-full max-w-md'>
                <i class='fa-solid fa-triangle-exclamation text-4xl mb-4'></i><br>Invalid Access Protocol!
            </div>
          </div>";
    include 'common/footer.php';
    exit;
}

$id = $_GET['id'];
$stmt = $conn->prepare("SELECT * FROM files WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$file = $stmt->get_result()->fetch_assoc();

if (!$file) {
    echo "<div class='flex items-center justify-center min-h-[60vh] px-4'>
            <div class='cyber-card p-10 border-red-500/50 text-red-500 font-bold uppercase tracking-widest text-center w-full max-w-md'>
                <i class='fa-solid fa-database text-4xl mb-4'></i><br>Data Node Not Found!
            </div>
          </div>";
    include 'common/footer.php';
    exit;
}

// ৩. প্রাইস এবং পারচেজ স্ট্যাটাস চেক
$price = isset($file['price']) ? (float)$file['price'] : 0;
$discount = isset($file['discount']) ? (float)$file['discount'] : 0;
$final_price = $price - $discount;
$is_paid = ($final_price > 0);

$user_id = $_SESSION['user_id'];
$is_purchased = false;

if ($is_paid) {
    $p_stmt = $conn->prepare("SELECT id FROM purchases WHERE user_id = ? AND file_id = ?");
    $p_stmt->bind_param("ii", $user_id, $id);
    $p_stmt->execute();
    if ($p_stmt->get_result()->num_rows > 0) {
        $is_purchased = true;
    }
}

// ৪. টাইম এক্সপায়ার চেক
$expiry = strtotime($file['expiry_time']);
$is_expired = (time() > $expiry);

// ৫. পাসওয়ার্ড ভেরিফিকেশন লজিক
$access_granted = empty($file['password']);
$error_msg = "";
if (isset($_POST['check_password'])) {
    if ($_POST['user_password'] === $file['password']) {
        $access_granted = true;
    } else {
        $error_msg = "AUTHENTICATION FAILED: INVALID KEY";
    }
}
?>

<div class="max-w-5xl mx-auto px-4 py-8 md:py-16 space-y-8 animate-fade-in">
    
    <!-- ১. টপ টাইটেল কার্ড -->
    <div class="cyber-card p-6 md:p-10 flex flex-col md:flex-row items-center gap-6 md:gap-10 relative overflow-hidden group border-b-4 border-cyan-500/50">
        <div class="absolute -top-10 -left-10 w-40 h-40 bg-cyan-500/5 rounded-full blur-3xl group-hover:bg-cyan-500/10 transition-all"></div>
        
        <!-- ফাইল আইকন -->
        <div class="w-20 h-20 md:w-28 md:h-28 bg-slate-900 border-2 border-cyan-500/30 rounded-3xl flex items-center justify-center shadow-[0_0_30px_rgba(6,182,212,0.2)]">
            <i class="fa-solid fa-file-shield text-4xl md:text-6xl text-cyan-400"></i>
        </div>

        <!-- টাইটেল এবং ইনফো -->
        <div class="flex-1 text-center md:text-left">
            <h2 class="text-3xl md:text-5xl font-bold logo-font tracking-tighter text-white uppercase mb-4 leading-none glow-text">
                <?php echo $file['file_title']; ?>
            </h2>
            <div class="flex flex-wrap justify-center md:justify-start gap-3">
                <span class="bg-black/50 border border-white/10 text-gray-400 text-[10px] font-black tracking-widest px-4 py-1.5 rounded-full uppercase">
                    ID: #<?php echo $file['id']; ?>
                </span>
                <span class="bg-black/50 border border-white/10 text-gray-400 text-[10px] font-black tracking-widest px-4 py-1.5 rounded-full uppercase">
                    <i class="fa-regular fa-calendar mr-1"></i> <?php echo date('d M Y', strtotime($file['created_at'])); ?>
                </span>
                <?php if($is_paid): ?>
                <span class="bg-cyan-500/10 border border-cyan-500/30 text-cyan-400 text-[10px] font-black tracking-widest px-4 py-1.5 rounded-full uppercase">
                    Asset Value: ৳<?php echo $final_price; ?>
                </span>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?php if ($is_expired): ?>
        <!-- এক্সপায়ার স্টেট -->
        <div class="cyber-card p-12 text-center border-red-500/30 relative overflow-hidden">
            <div class="absolute inset-0 bg-red-500/5 animate-pulse"></div>
            <i class="fa-solid fa-clock-rotate-left text-red-500 text-6xl md:text-8xl mb-6"></i>
            <h3 class="text-xl md:text-3xl font-bold text-red-500 logo-font uppercase tracking-widest">Protocol Expired</h3>
            <p class="text-gray-500 text-xs mt-4 tracking-[3px] uppercase">Access to this data node has been terminated.</p>
            <a href="index.php" class="inline-block mt-10 bg-slate-800 text-white px-8 py-3 rounded-xl font-bold uppercase text-[10px] tracking-widest hover:bg-white hover:text-black transition-all">Return to Command Center</a>
        </div>

    <?php elseif (!$access_granted): ?>
        <!-- পাসওয়ার্ড ইনপুট স্টেট -->
        <div class="cyber-card p-8 md:p-12 border-orange-500/30 max-w-lg mx-auto relative">
            <div class="text-center mb-10">
                <div class="w-16 h-16 bg-orange-500/10 rounded-full flex items-center justify-center mx-auto mb-4 border border-orange-500/30">
                    <i class="fa-solid fa-lock text-orange-500 text-2xl animate-bounce"></i>
                </div>
                <h3 class="text-xl font-bold text-white uppercase logo-font tracking-widest">Restricted</h3>
                <p class="text-[10px] text-gray-500 uppercase tracking-[2px] mt-2">Enter Security Key to Decrypt Contents</p>
            </div>

            <?php if ($error_msg): ?>
                <div class="bg-red-500/10 border border-red-500/50 text-red-500 p-3 rounded-xl text-[10px] font-bold mb-6 text-center uppercase tracking-widest">
                    <i class="fa-solid fa-circle-exclamation mr-1"></i> <?php echo $error_msg; ?>
                </div>
            <?php endif; ?>

            <form action="" method="POST" class="space-y-6">
                <input type="password" name="user_password" required placeholder="KEY" 
                       class="w-full bg-slate-950/50 border border-white/10 rounded-xl py-5 text-white focus:border-orange-500 outline-none text-center tracking-[15px] text-2xl placeholder:tracking-normal placeholder:text-sm">
                <button type="submit" name="check_password" class="w-full bg-gradient-to-r from-orange-500 to-red-600 text-white font-bold py-5 rounded-xl shadow-lg hover:shadow-orange-500/30 transition-all uppercase tracking-widest text-xs">Execute Decryption</button>
            </form>
        </div>

    <?php else: ?>
        <!-- ডাউনলোড এবং টিউটোরিয়াল স্টেট -->
        <div class="space-y-10">
            
            <!-- ইউটিউব ভিডিও -->
            <?php if (!empty($file['youtube_url'])): ?>
                <div class="cyber-card overflow-hidden border-red-500/20 shadow-[0_0_40px_rgba(239,68,68,0.05)]">
                    <div class="p-4 bg-red-500/10 text-red-500 text-[10px] font-black uppercase tracking-[4px] flex items-center border-b border-white/5">
                        <i class="fa-brands fa-youtube mr-3 text-xl animate-pulse"></i> Visual Intelligence: Tutorial
                    </div>
                    <div class="aspect-video w-full bg-black">
                        <?php 
                            if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $file['youtube_url'], $match)) {
                                $video_id = $match[1];
                                echo "<iframe class='w-full h-full shadow-inner' src='https://www.youtube.com/embed/$video_id?rel=0&showinfo=0' frameborder='0' allowfullscreen></iframe>";
                            }
                        ?>
                    </div>
                </div>
            <?php endif; ?>

            <!-- অ্যাকশন প্যানেল -->
            <div class="cyber-card p-8 md:p-16 text-center relative border-green-500/30">
                <div class="absolute inset-0 bg-green-500/5 pointer-events-none"></div>
                
                <div class="mb-10">
                    <?php if(!$is_paid || $is_purchased): ?>
                        <span class="inline-flex items-center px-5 py-2 rounded-full bg-green-500/10 border border-green-500/30 text-[10px] font-black text-green-500 uppercase tracking-[4px]">
                            <span class="w-2 h-2 bg-green-500 rounded-full mr-3 animate-ping"></span> STATUS: AUTHORIZED
                        </span>
                    <?php else: ?>
                        <span class="inline-flex items-center px-5 py-2 rounded-full bg-yellow-500/10 border border-yellow-500/30 text-[10px] font-black text-yellow-500 uppercase tracking-[4px]">
                            <span class="w-2 h-2 bg-yellow-500 rounded-full mr-3 animate-pulse"></span> STATUS: PAYMENT REQUIRED
                        </span>
                    <?php endif; ?>
                </div>
                
                <h3 class="text-2xl md:text-4xl font-bold text-white uppercase tracking-[2px] mb-10 logo-font leading-tight">
                    <?php echo (!$is_paid || $is_purchased) ? "Asset Ready for<br><span class='text-cyan-400 glow-text'>Transmission</span>" : "Purchase Asset to<br><span class='text-purple-500 glow-text'>Unlock Data</span>"; ?>
                </h3>

                <div class="flex flex-col items-center gap-6">
                    <?php if(!$is_paid || $is_purchased): ?>
                        <a href="uploads/<?php echo $file['file_name']; ?>" download 
                           class="w-full max-w-md bg-gradient-to-r from-cyan-500 to-blue-600 text-white font-black py-6 md:py-8 rounded-3xl shadow-[0_0_30px_rgba(6,182,212,0.4)] hover:shadow-[0_0_50px_rgba(6,182,212,0.6)] hover:scale-105 active:scale-95 transition-all flex flex-col items-center justify-center">
                            <i class="fa-solid fa-cloud-arrow-down text-3xl mb-2 animate-bounce"></i>
                            <span class="text-xs uppercase tracking-[5px]">Start Download</span>
                        </a>
                    <?php else: ?>
                        <div class="w-full max-w-md space-y-4">
                            <a href="buy-file.php?id=<?php echo $id; ?>" 
                               class="block w-full bg-gradient-to-r from-purple-600 to-blue-600 text-white font-black py-6 md:py-8 rounded-3xl shadow-[0_0_30px_rgba(147,51,234,0.3)] hover:shadow-[0_0_50px_rgba(147,51,234,0.5)] hover:scale-105 active:scale-95 transition-all text-xs uppercase tracking-[5px]">
                                <i class="fa-solid fa-cart-shopping mr-3"></i> Unlock Asset (৳<?php echo $final_price; ?>)
                            </a>
                            <div class="flex justify-between items-center px-4">
                                <span class="text-[10px] text-gray-500 uppercase font-bold tracking-widest">Your Balance: ৳<?php echo number_format($_SESSION['user_balance'], 2); ?></span>
                                <a href="add-money.php" class="text-[10px] text-cyan-400 font-bold uppercase tracking-widest hover:text-white underline">Add Credits</a>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
                
                <p class="text-[9px] md:text-[11px] text-gray-500 mt-12 uppercase tracking-[4px] font-bold italic">
                    <i class="fa-solid fa-shield-halved mr-2 text-cyan-500/50"></i> Encrypted Served by TAMIM 1280 Hub
                </p>
            </div>
        </div>
    <?php endif; ?>
</div>

<style>
    /* গ্লাস-মরফিজম সাইবারপাঙ্ক ডিজাইন */
    .cyber-card {
        background: rgba(1, 10, 32, 0.8);
        backdrop-filter: blur(20px);
        -webkit-backdrop-filter: blur(20px);
        border: 1px solid rgba(255, 255, 255, 0.05);
        border-radius: 2rem;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
    }
    
    @media (min-width: 768px) {
        .cyber-card { border-radius: 3rem; }
    }

    .glow-text {
        text-shadow: 0 0 15px rgba(34, 211, 238, 0.6);
    }

    .animate-fade-in {
        animation: fadeIn 0.8s cubic-bezier(0.4, 0, 0.2, 1);
    }
    
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(30px); }
        to { opacity: 1; transform: translateY(0); }
    }

    input:focus {
        box-shadow: 0 0 20px rgba(249, 115, 22, 0.1);
    }
</style>

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