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

// ডাটাবেস কোয়েরি এবং এরর হ্যান্ডলিং
$result = $conn->query("SELECT * FROM files ORDER BY id DESC");

// যদি কোয়েরি ফেইল করে তবে এরর মেসেজ দেখাবে
if (!$result) {
    echo "<div class='max-w-7xl mx-auto px-4 py-10 text-center'>
            <div class='cyber-card p-10 border-red-500/50 text-red-500'>
                <i class='fa-solid fa-database text-5xl mb-4'></i>
                <h3 class='text-xl font-bold uppercase tracking-widest'>Database Query Failed!</h3>
                <p class='text-xs mt-2 opacity-70'>Error: " . $conn->error . "</p>
                <p class='text-xs mt-4 uppercase'>অনুগ্রহ করে নিশ্চিত করুন যে আপনি setup.php ফাইলটি রান করেছেন।</p>
            </div>
          </div>";
    include 'common/footer.php';
    exit;
}
?>

<style>
    /* সাইবারপাঙ্ক স্টাইল */
    .timer-glow {
        color: #22d3ee;
        text-shadow: 0 0 10px rgba(34, 211, 238, 0.5);
        font-family: 'Orbitron', sans-serif;
    }
    .file-icon-bg {
        background: linear-gradient(135deg, rgba(6, 182, 212, 0.2) 0%, rgba(59, 130, 246, 0.1) 100%);
        border: 1px solid rgba(34, 211, 238, 0.3);
    }
    .search-input:focus {
        border-color: #22d3ee;
        box-shadow: 0 0 15px rgba(34, 211, 238, 0.3);
    }
    .price-tag {
        background: rgba(0, 0, 0, 0.6);
        border-left: 3px solid #22d3ee;
    }
</style>

<div class="max-w-7xl mx-auto px-4 py-10 sm:px-6 lg:px-8">
    
    <!-- হেডার এবং সার্চ বার -->
    <div class="flex flex-col md:flex-row md:items-center justify-between mb-10 gap-6">
        <div>
            <h2 class="text-2xl md:text-3xl font-bold logo-font tracking-wider">
                AVAILABLE <span class="text-cyan-400 glow-text">FILES</span>
            </h2>
            <p class="text-gray-500 text-sm mt-1 uppercase tracking-widest font-semibold">Secure encrypted data hub</p>
        </div>

        <div class="flex flex-col sm:flex-row items-center gap-4 w-full md:w-auto">
            <div class="relative w-full sm:w-64 md:w-80">
                <i class="fa-solid fa-magnifying-glass absolute left-4 top-1/2 -translate-y-1/2 text-cyan-400/50"></i>
                <input type="text" id="fileSearch" placeholder="SEARCH BY NAME..." 
                    class="w-full bg-slate-950/50 border border-white/10 rounded-xl py-3 pl-12 pr-4 text-white outline-none search-input transition-all uppercase text-xs tracking-widest font-bold">
            </div>

            <div class="cyber-card px-4 py-2 border-cyan-500/30 flex items-center space-x-3 w-full sm:w-auto justify-center">
                <span class="w-2 h-2 bg-cyan-400 rounded-full animate-ping"></span>
                <span class="text-sm font-bold text-cyan-400 tracking-tighter uppercase">Total: <span id="totalCount"><?php echo $result->num_rows; ?></span></span>
            </div>
        </div>
    </div>
    
    <!-- ফাইল গ্রিড -->
    <div id="fileGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        
        <?php while($row = $result->fetch_assoc()): 
            $expiry_timestamp = strtotime($row['expiry_time']);
            $is_expired = (time() > $expiry_timestamp);
            $card_id = "timer-" . $row['id'];
            
            // ডাটাবেস থেকে প্রাইস আনা
            $original_price = isset($row['price']) ? (float)$row['price'] : 0;
            $discount = isset($row['discount']) ? (float)$row['discount'] : 0;
            $final_price = $original_price - $discount;
        ?>
        
        <!-- ফাইল কার্ড -->
        <div class="cyber-card p-5 flex flex-col justify-between group file-item transition-all duration-300" data-title="<?php echo strtolower($row['file_title']); ?>">
            
            <div class="flex items-start space-x-4 mb-4">
                <div class="file-icon-bg p-4 rounded-xl text-cyan-400 group-hover:scale-110 transition-transform duration-300 shadow-[0_0_15px_rgba(34,211,238,0.1)]">
                    <i class="fa-solid fa-file-shield text-3xl"></i>
                </div>
                
                <div class="flex-1 min-w-0">
                    <h3 class="font-bold text-white text-lg truncate mb-1 tracking-wide group-hover:text-cyan-400 transition-colors" title="<?php echo $row['file_title']; ?>">
                        <?php echo $row['file_title']; ?>
                    </h3>
                    <div class="flex items-center text-[10px] text-gray-500 uppercase tracking-widest font-bold">
                        <i class="fa-solid fa-fingerprint mr-1 text-cyan-500/50"></i>
                        FILE ID: #<?php echo $row['id']; ?>
                    </div>
                </div>
            </div>

            <!-- প্রাইস সেকশন -->
            <div class="mb-4 price-tag p-3 rounded-r-lg flex justify-between items-center bg-black/40">
                <div class="flex flex-col">
                    <span class="text-[9px] text-gray-400 uppercase font-black tracking-widest">Pricing Model</span>
                    <div class="flex items-center gap-2">
                        <?php if($original_price > 0): ?>
                            <span class="text-white font-bold text-lg tracking-tighter">৳<?php echo number_format($final_price, 0); ?></span>
                            <?php if($discount > 0): ?>
                                <span class="text-gray-500 text-xs line-through">৳<?php echo $original_price; ?></span>
                            <?php endif; ?>
                        <?php else: ?>
                            <span class="text-green-400 font-bold text-sm uppercase glow-text">Free Access</span>
                        <?php endif; ?>
                    </div>
                </div>
                <?php if($original_price > 0 && $discount > 0): ?>
                    <div class="bg-red-500/20 border border-red-500/40 px-2 py-1 rounded text-[10px] font-black text-red-500">
                        -<?php echo round(($discount/$original_price)*100); ?>%
                    </div>
                <?php endif; ?>
            </div>

            <!-- টাইমার সেকশন -->
            <div class="mb-6 bg-black/60 border border-white/5 rounded-lg p-3 relative overflow-hidden">
                <div class="text-[10px] text-gray-500 uppercase font-bold mb-2 flex justify-between">
                    <span>Time Remaining</span>
                    <span class="text-cyan-500/50">Live Sync</span>
                </div>
                
                <?php if($is_expired): ?>
                    <div class="text-red-500 font-bold text-center py-1 tracking-widest uppercase text-sm">
                        <i class="fa-solid fa-circle-exclamation mr-1"></i> Access Expired
                    </div>
                <?php else: ?>
                    <div id="<?php echo $card_id; ?>" class="timer-glow text-xl font-bold text-center tracking-widest" data-time="<?php echo $expiry_timestamp; ?>">
                        00d 00h 00m 00s
                    </div>
                <?php endif; ?>
            </div>
            
            <div class="mt-auto">
                <?php if($is_expired): ?>
                    <button disabled class="w-full bg-red-500/10 border border-red-500/30 text-red-500 font-bold text-xs uppercase py-3 rounded-lg cursor-not-allowed opacity-60">
                        Locked / Expired
                    </button>
                <?php else: ?>
                    <a href="view-file.php?id=<?php echo $row['id']; ?>" 
                       class="cyber-button block text-center w-full text-white font-bold py-3 rounded-lg text-sm uppercase tracking-[2px] transition-all">
                        <i class="fa-solid fa-unlock-keyhole mr-2"></i> Access File
                    </a>
                <?php endif; ?>
            </div>
        </div>
        
        <?php endwhile; ?>
    </div>

    <?php if($result->num_rows == 0): ?>
        <div class="text-center py-24 cyber-card border-dashed border-cyan-500/20">
            <i class="fa-solid fa-box-open text-6xl text-cyan-500/20 mb-4"></i>
            <h3 class="text-xl font-bold text-gray-500 uppercase tracking-[4px]">No Data Found</h3>
        </div>
    <?php endif; ?>

</div>

<script>
// ১. লাইভ সার্চ লজিক
document.getElementById('fileSearch').addEventListener('input', function() {
    const searchTerm = this.value.toLowerCase();
    const fileItems = document.querySelectorAll('.file-item');
    let visibleCount = 0;
    fileItems.forEach(item => {
        const title = item.getAttribute('data-title');
        if (title.includes(searchTerm)) {
            item.style.display = 'flex';
            visibleCount++;
        } else {
            item.style.display = 'none';
        }
    });
    document.getElementById('totalCount').innerText = visibleCount;
});

// ২. কাউন্টডাউন টাইমার
function updateCountdowns() {
    document.querySelectorAll('[id^="timer-"]').forEach(timer => {
        const expiryTime = parseInt(timer.getAttribute('data-time')) * 1000;
        const now = new Date().getTime();
        const distance = expiryTime - now;
        if (distance < 0) {
            timer.innerHTML = "<span class='text-red-500'>EXPIRED</span>";
            return;
        }
        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);
        timer.innerHTML = (days > 0 ? days + "d " : "") + hours + "h " + minutes + "m " + seconds + "s";
    });
}
setInterval(updateCountdowns, 1000);
updateCountdowns();
</script>

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