<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once 'includes/db.php';

$product_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
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 (empty($product)) { header("Location: index.php"); exit; }

$stmt_cat = $pdo->prepare("SELECT name FROM categories WHERE id = ?");
$stmt_cat->execute([$product['category_id']]);
$category_name = $stmt_cat->fetchColumn();

// সেটিংস থেকে ফোন নাম্বার নিয়ে হোয়াটসঅ্যাপ লিঙ্ক তৈরি
$stmt_set = $pdo->query("SELECT contact_calls FROM settings LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$wa_phone = preg_replace('/[^0-9]/', '', $stmt_set['contact_calls'] ?? '01700000000');
if(substr($wa_phone, 0, 2) !== '88') $wa_phone = '88' . $wa_phone;

$product_options = !empty($product['options']) ? json_decode($product['options'], true) :[];
$packages = $product_options['Packages'] ?? [];
unset($product_options['Packages']); // সাধারণ অপশন থেকে প্যাকেজ বাদ দিলাম

require_once 'includes/header.php';
?>

<!-- Breadcrumb -->
<div class="bg-gray-100 py-3 border-b border-gray-200">
    <div class="container mx-auto px-4 text-sm font-bangla text-gray-600">
        <a href="index.php">হোম</a> / <a href="category.php?id=<?= $product['category_id'] ?>"><?= htmlspecialchars($category_name) ?></a> / <span class="text-blue-600 font-bold"><?= htmlspecialchars($product['name']) ?></span>
    </div>
</div>

<section class="py-10 bg-white min-h-screen pb-24">
    <div class="container mx-auto px-4 grid grid-cols-1 lg:grid-cols-2 gap-10">
        
        <!-- Left: Product Image -->
        <div class="w-full">
            <div class="bg-gray-50 rounded-2xl border flex items-center justify-center p-4 min-h-[300px]">
                <?php if ($product['image']): ?>
                    <img src="uploads/products/<?= htmlspecialchars($product['image']) ?>" class="w-full max-h-[400px] object-contain rounded-lg drop-shadow-sm">
                <?php else: ?>
                    <i class="fa-solid fa-image text-8xl text-gray-300"></i>
                <?php endif; ?>
            </div>
        </div>

        <!-- Right: Product Info & Form -->
        <div>
            <h1 class="text-2xl md:text-3xl font-bold font-bangla mb-3 text-gray-800"><?= htmlspecialchars($product['name']) ?></h1>
            
            <!-- Price -->
            <div class="flex items-center gap-3 mb-6 border-b border-gray-100 pb-6">
                <p class="text-blue-700 text-3xl font-bold en-font">৳ <span id="displayBasePrice"><?= number_format($packages ? current($packages) : $product['base_price'], 2) ?></span></p>
                <?php if(empty($packages)): ?>
                    <span class="bg-blue-50 text-blue-600 px-3 py-1 rounded-full text-xs font-bold font-bangla"><?= htmlspecialchars($product['price_unit']) ?></span>
                <?php endif; ?>
            </div>

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

                <!-- Options Grid (2 Columns for all devices) -->
                <div class="grid grid-cols-2 gap-3 md:gap-4">
                    
                    <!-- প্যাকেজ ড্রপডাউন (যদি থাকে - পুরো ২ কলাম নিবে) -->
                    <?php if(!empty($packages)): ?>
                    <div class="col-span-2">
                        <label class="block text-sm font-bold text-gray-800 mb-2 font-bangla">পরিমাণ ও প্যাকেজ মূল্য <span class="text-red-500">*</span></label>
                        <select name="selected_package" id="pkgSelect" onchange="updatePrice()" class="w-full bg-blue-50 border border-blue-200 py-3 px-4 rounded-xl font-bangla text-sm font-bold text-blue-900 outline-none cursor-pointer">
                            <?php foreach($packages as $pkg_name => $pkg_price): ?>
                                <option value="<?= htmlspecialchars($pkg_name) ?>" data-price="<?= $pkg_price ?>">
                                    <?= htmlspecialchars($pkg_name) ?> (৳ <?= $pkg_price ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>

                    <!-- অন্যান্য অপশন (Color, Size etc - ২ কলামে পাশাপাশি বসবে) -->
                    <?php foreach($product_options as $title => $values): ?>
                    <div class="col-span-1">
                        <label class="block text-xs md:text-sm font-bold text-gray-700 mb-2 font-bangla truncate" title="<?= htmlspecialchars($title) ?>">
                            <?= htmlspecialchars($title) ?>
                        </label>
                        <select name="options[<?= htmlspecialchars($title) ?>]" class="w-full border border-gray-300 py-2.5 px-2 md:px-4 rounded-xl outline-none font-bangla text-xs md:text-sm cursor-pointer bg-white">
                            <?php foreach($values as $val): ?><option value="<?= htmlspecialchars($val) ?>"><?= htmlspecialchars($val) ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <?php endforeach; ?>
                </div>

                <!-- ডিজাইন ফাইল আপলোড -->
                <div class="border-2 border-dashed border-blue-300 bg-blue-50/30 p-5 rounded-2xl text-center mt-4 transition hover:bg-blue-50">
                    <input type="file" name="design_file" id="file" class="hidden" onchange="document.getElementById('file-label').innerText = 'ফাইল: ' + this.files[0].name;">
                    <label for="file" class="cursor-pointer block">
                        <i class="fa-solid fa-cloud-arrow-up text-2xl text-blue-600 mb-1"></i>
                        <p class="text-sm font-bangla font-bold text-gray-600" id="file-label">আপনার ডিজাইন আপলোড করুন (ঐচ্ছিক)</p>
                    </label>
                </div>

                <!-- Quantity & Add to Cart -->
                <div class="flex items-center justify-between bg-slate-900 text-white p-4 rounded-2xl">
                    <div class="flex items-center gap-3 w-1/2">
                        <span class="font-bangla text-xs md:text-sm text-gray-300">সেট/পরিমাণ:</span>
                        <input type="number" name="quantity" value="1" min="1" id="qty" onchange="updatePrice()" class="w-12 md:w-16 bg-white/20 text-center rounded py-1 outline-none en-font font-bold text-white focus:bg-white/30 transition">
                    </div>
                    <div class="text-right w-1/2">
                        <p class="text-[10px] md:text-xs font-bangla opacity-80 text-gray-300">মোট খরচ</p>
                        <p class="text-lg md:text-xl font-bold text-yellow-400 en-font">৳ <span id="totalPrice"><?= number_format($packages ? current($packages) : $product['base_price'], 2) ?></span></p>
                    </div>
                </div>

                <button type="submit" class="w-full bg-blue-600 text-white py-4 rounded-xl font-bold text-lg hover:bg-blue-800 transition transform hover:-translate-y-1 font-bangla shadow-lg flex justify-center items-center gap-2">
                    <i class="fa-solid fa-cart-plus"></i> কার্টে যোগ করুন
                </button>
            </form>

            <!-- Social Order Buttons -->
            <div class="mt-6 flex flex-col sm:flex-row gap-4">
                <a href="https://wa.me/<?= $wa_phone ?>?text=<?= urlencode("হ্যালো, আমি '{$product['name']}' অর্ডার করতে চাই।") ?>" target="_blank" class="flex-1 bg-[#25D366] text-white py-3 rounded-xl font-bold text-sm text-center hover:bg-green-600 transition font-bangla flex justify-center items-center gap-2 shadow-sm hover:shadow-md">
                    <i class="fa-brands fa-whatsapp text-lg"></i> হোয়াটসঅ্যাপে অর্ডার
                </a>
                <a href="https://m.me/yourpageusername" target="_blank" class="flex-1 bg-[#0084FF] text-white py-3 rounded-xl font-bold text-sm text-center hover:bg-blue-600 transition font-bangla flex justify-center items-center gap-2 shadow-sm hover:shadow-md">
                    <i class="fa-brands fa-facebook-messenger text-lg"></i> মেসেঞ্জারে অর্ডার
                </a>
            </div>

            <!-- Product Description (Moved to Bottom) -->
            <div class="mt-10 pt-8 border-t border-gray-200">
                <h3 class="text-lg font-bold text-gray-800 font-bangla mb-4 flex items-center gap-2">
                    <i class="fa-solid fa-circle-info text-blue-600"></i> প্রোডাক্ট বিবরণ:
                </h3>
                <div class="text-gray-600 font-bangla text-sm md:text-base leading-relaxed text-justify bg-gray-50 p-5 rounded-xl border border-gray-100">
                    <?= nl2br(htmlspecialchars($product['description'])) ?>
                </div>
            </div>

        </div>
    </div>
</section>

<script>
    // লাইভ প্রাইস আপডেট লজিক
    let defaultBase = <?= $product['base_price'] ?>;
    function updatePrice() {
        const pkgSelect = document.getElementById('pkgSelect');
        let currentBase = defaultBase;
        
        if(pkgSelect) {
            currentBase = parseFloat(pkgSelect.options[pkgSelect.selectedIndex].getAttribute('data-price'));
            document.getElementById('displayBasePrice').innerText = currentBase.toLocaleString(undefined, {minimumFractionDigits: 2});
        }
        
        const qty = parseInt(document.getElementById('qty').value) || 1;
        document.getElementById('totalPrice').innerText = (currentBase * qty).toLocaleString(undefined, {minimumFractionDigits: 2});
    }
</script>

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