<?php
require_once 'includes/header.php';

$product_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$product = null;
$category_name = "জেনারেল";

// ১. ডাটাবেস থেকে প্রোডাক্ট খোঁজা
if ($product_id) {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? AND status = 1");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
}

// ২. যদি প্রোডাক্ট না পাওয়া যায় (ডাটাবেস এরর বা ডেমো মোড), তবে ফেইক/ডেমো ডাটা তৈরি করা
if (!$product) {
    $product = [
        'id' => 0,
        'category_id' => 0,
        'name' => 'ডেমো প্রোডাক্ট (Demo Product)',
        'base_price' => 100.00,
        'description' => 'এটি একটি ডেমো প্রোডাক্ট। ডাটাবেস থেকে কোনো রিয়েল প্রোডাক্ট আইডি না পাওয়ায় এটি দেখানো হচ্ছে। আপনি নিশ্চিন্তে ডিজাইন চেক করতে পারেন।',
        'image' => '', // কোনো ছবি নেই, ডিফল্ট আইকন দেখাবে
        'options' => null 
    ];
} else {
    // ক্যাটাগরি নাম আনা (যদি রিয়েল প্রোডাক্ট হয়)
    $stmt_cat = $pdo->prepare("SELECT name FROM categories WHERE id = ?");
    $stmt_cat->execute([$product['category_id']]);
    $category_name = $stmt_cat->fetchColumn();
}

// ডিফল্ট প্রিন্টিং অপশন (যদি ডাটাবেসে স্পেসিফিক অপশন না থাকে)
$default_options = [
    'Size' => ['Standard', 'Custom Size', 'A4', 'A5'],
    'Paper Type' => ['Standard (80gsm)', 'Premium (100gsm)', 'Card (300gsm)', 'PVC'],
    'Lamination' => ['None', 'Matte', 'Glossy'],
    'Print Side' => ['Single Side', 'Both Side']
];

// ডাটাবেসের অপশন ডিকোড করা
$product_options = !empty($product['options']) ? json_decode($product['options'], true) : $default_options;
?>

<!-- Breadcrumb -->
<div class="bg-gray-100 py-3 border-b border-gray-200">
    <div class="container mx-auto px-4">
        <ul class="flex items-center text-sm font-bangla text-gray-600">
            <li><a href="index.php" class="hover:text-primary"><i class="fa-solid fa-house mr-1"></i> হোম</a></li>
            <li><span class="mx-2 text-gray-400">/</span></li>
            <li><a href="#" class="hover:text-primary"><?= htmlspecialchars($category_name) ?></a></li>
            <li><span class="mx-2 text-gray-400">/</span></li>
            <li class="text-primary font-bold truncate max-w-[150px] md:max-w-none"><?= htmlspecialchars($product['name']) ?></li>
        </ul>
    </div>
</div>

<!-- Product Details Section -->
<section class="py-10 bg-white min-h-screen pb-20 md:pb-10">
    <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-10">
            
            <!-- Left: Product Image -->
            <div class="h-fit sticky top-24">
                <div class="bg-gray-100 rounded-2xl overflow-hidden border border-gray-200 shadow-sm relative group">
                    <?php if (!empty($product['image'])): ?>
                        <img src="uploads/products/<?= $product['image'] ?>" alt="<?= htmlspecialchars($product['name']) ?>" class="w-full h-auto object-cover transform group-hover:scale-105 transition duration-500">
                    <?php else: ?>
                        <!-- Image Placeholder -->
                        <div class="h-[300px] md:h-[400px] flex items-center justify-center text-gray-300 bg-gray-50">
                            <div class="text-center">
                                <i class="fa-solid fa-image text-6xl md:text-8xl mb-2"></i>
                                <p class="text-sm font-bangla">নো ইমেজ</p>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Zoom Icon -->
                    <div class="absolute bottom-4 right-4 bg-white p-2 rounded-full shadow-lg text-gray-600 cursor-pointer hover:text-primary">
                        <i class="fa-solid fa-expand"></i>
                    </div>
                </div>
            </div>

            <!-- Right: Product Info & Form -->
            <div>
                <h1 class="text-2xl md:text-3xl lg:text-4xl font-bold text-gray-800 font-bangla mb-2 leading-tight"><?= htmlspecialchars($product['name']) ?></h1>
                
                <div class="flex items-center gap-4 mb-4">
                    <span class="text-2xl font-bold text-primary en-font">৳ <?= number_format($product['base_price'], 2) ?></span>
                    <span class="text-xs md:text-sm bg-blue-50 text-blue-600 px-2 py-1 rounded font-bangla">প্রতি পিস / ইউনিট</span>
                </div>

                <p class="text-gray-600 leading-relaxed font-bangla mb-6 border-b border-gray-100 pb-6 text-sm md:text-base">
                    <?= nl2br(htmlspecialchars($product['description'] ?? '')) ?>
                </p>

                <!-- Order Form -->
                <form action="cart_action.php" method="POST" enctype="multipart/form-data" class="space-y-6">
                    <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                    <input type="hidden" name="action" value="add_to_cart">

                    <!-- Dynamic Options (Loop) -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <?php if($product_options): foreach($product_options as $option_name => $values): ?>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2 font-bangla"><?= htmlspecialchars($option_name) ?></label>
                            <div class="relative">
                                <select name="options[<?= htmlspecialchars($option_name) ?>]" class="w-full bg-gray-50 border border-gray-300 text-gray-700 py-2.5 px-4 rounded-lg focus:ring-2 focus:ring-secondary focus:border-secondary appearance-none font-bangla text-sm cursor-pointer">
                                    <?php foreach($values as $val): ?>
                                        <option value="<?= htmlspecialchars($val) ?>"><?= htmlspecialchars($val) ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-500">
                                    <i class="fa-solid fa-angle-down text-xs"></i>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; endif; ?>
                    </div>

                    <!-- File Upload -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2 font-bangla">আপনার ডিজাইন ফাইল আপলোড করুন (অপশনাল)</label>
                        <div class="flex items-center justify-center w-full">
                            <label for="dropzone-file" class="flex flex-col items-center justify-center w-full h-28 md:h-32 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100 transition relative overflow-hidden">
                                <div class="flex flex-col items-center justify-center pt-5 pb-6">
                                    <i class="fa-solid fa-cloud-arrow-up text-3xl text-gray-400 mb-2"></i>
                                    <p class="text-sm text-gray-500 font-bangla"><span class="font-semibold">ক্লিক করুন</span> অথবা ফাইল টেনে আনুন</p>
                                    <p class="text-[10px] text-gray-400 en-font mt-1">PDF, JPG, PNG (Max 10MB)</p>
                                </div>
                                <input id="dropzone-file" type="file" name="design_file" class="hidden" />
                            </label>
                        </div>
                        <div id="file-name" class="text-xs text-green-600 mt-2 font-bangla font-semibold hidden flex items-center gap-1">
                            <i class="fa-solid fa-check-circle"></i> <span></span>
                        </div>
                    </div>

                    <!-- Quantity & Total Price -->
                    <div class="bg-blue-50 p-4 rounded-xl border border-blue-100 flex flex-col sm:flex-row items-center justify-between gap-4">
                        <div class="flex items-center gap-3 w-full sm:w-auto justify-center">
                            <span class="font-semibold text-gray-700 font-bangla">পরিমাণ:</span>
                            <div class="flex items-center border border-gray-300 rounded bg-white">
                                <button type="button" onclick="updateQty(-1)" class="w-8 h-8 md:w-10 md:h-10 flex items-center justify-center bg-gray-100 hover:bg-gray-200 text-gray-600 transition">-</button>
                                <input type="number" id="qtyInput" name="quantity" value="1" min="1" class="w-12 md:w-16 text-center border-l border-r border-gray-300 py-1 en-font focus:outline-none h-8 md:h-10 text-lg" readonly>
                                <button type="button" onclick="updateQty(1)" class="w-8 h-8 md:w-10 md:h-10 flex items-center justify-center bg-gray-100 hover:bg-gray-200 text-gray-600 transition">+</button>
                            </div>
                        </div>

                        <div class="text-center sm:text-right w-full sm:w-auto">
                            <span class="text-xs text-gray-500 block font-bangla">মোট খরচ (আনুমানিক)</span>
                            <span class="text-2xl font-bold text-primary en-font">৳ <span id="totalPrice"><?= $product['base_price'] ?></span></span>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="flex gap-3 pt-2">
                        <button type="submit" name="add_to_cart" class="flex-1 bg-primary text-white py-3 md:py-3.5 rounded-full font-bold shadow-lg hover:bg-blue-800 transition transform hover:-translate-y-1 font-bangla flex items-center justify-center gap-2 text-sm md:text-base">
                            <i class="fa-solid fa-cart-shopping"></i> কার্টে যোগ করুন
                        </button>
                        <a href="tel:<?= $contact_phone ?>" class="px-5 md:px-6 py-3 md:py-3.5 border-2 border-primary text-primary rounded-full font-bold hover:bg-primary hover:text-white transition flex items-center justify-center">
                            <i class="fa-solid fa-phone text-lg"></i>
                        </a>
                    </div>
                    
                    <p class="text-[10px] md:text-xs text-gray-400 text-center font-bangla mt-2"><i class="fa-solid fa-shield-halved mr-1"></i> ১০০% সিকিউর পেমেন্ট ও ডেলিভারি</p>
                </form>
            </div>
        </div>
    </div>
</section>

<!-- JavaScript for Quantity & File Upload -->
<script>
    const basePrice = <?= $product['base_price'] ?>;
    const qtyInput = document.getElementById('qtyInput');
    const totalPriceEl = document.getElementById('totalPrice');
    const fileInput = document.getElementById('dropzone-file');
    const fileNameDisplay = document.getElementById('file-name');

    // Quantity Update Logic
    function updateQty(change) {
        let currentQty = parseInt(qtyInput.value);
        let newQty = currentQty + change;
        
        if (newQty < 1) newQty = 1;
        
        qtyInput.value = newQty;
        updatePrice();
    }

    function updatePrice() {
        let qty = parseInt(qtyInput.value);
        let total = (basePrice * qty).toFixed(2);
        totalPriceEl.innerText = total;
    }

    // File Upload Name Display
    fileInput.addEventListener('change', function(e) {
        if(e.target.files.length > 0) {
            const span = fileNameDisplay.querySelector('span');
            span.innerText = e.target.files[0].name;
            fileNameDisplay.classList.remove('hidden');
        }
    });
</script>

<?php require_once 'includes/footer.php'; ?>