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

// বাংলা সংখ্যাকে ইংরেজি করার ফাংশন
function bnToEn($number) {
    $bn =['০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯', '।'];
    $en =['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'];
    return str_replace($bn, $en, $number);
}

$message = ''; $error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $category_id = intval($_POST['category_id']);
    $base_price = floatval(bnToEn($_POST['base_price']));
    $price_unit = trim($_POST['price_unit']);
    $description = trim($_POST['description']);
    
    $final_options =[];
    
    // সাধারণ অপশন ও কালার
    $predefined = [
        'Color (কালার)' => $_POST['opt_color'],
        'Size (সাইজ)' => $_POST['opt_size'],
        'Paper Type' => $_POST['opt_paper'],
        'Lamination' => $_POST['opt_lamination'],
        'Print Side' => $_POST['opt_side'] ?? ''
    ];

    foreach ($predefined as $key => $val) {
        if (!empty(trim($val))) {
            $final_options[$key] = array_map('trim', explode(',', $val));
        }
    }

    // প্যাকেজ এবং দামের লজিক (100 Pcs: 500 | 500 Pcs: 2000)
    $opt_packages = trim($_POST['opt_packages']);
    if (!empty($opt_packages)) {
        $packages =[];
        $parts = explode('|', $opt_packages);
        foreach ($parts as $part) {
            $kv = explode(':', $part);
            if (count($kv) == 2) {
                $packages[trim($kv[0])] = floatval(bnToEn(trim($kv[1])));
            }
        }
        if (!empty($packages)) $final_options['Packages'] = $packages;
    }

    $options_json = !empty($final_options) ? json_encode($final_options, JSON_UNESCAPED_UNICODE) : null;

    // ইমেজ প্রসেসিং
    $image = $_POST['old_image'] ?? '';
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/products/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true); // Create dir if not exists
        $image = 'prod_' . time() . '.' . pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $image);
        if(!empty($_POST['old_image']) && file_exists($upload_dir . $_POST['old_image'])) @unlink($upload_dir . $_POST['old_image']);
    }

    if (isset($_POST['add_product'])) {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name))) . '-' . time();
        $stmt = $pdo->prepare("INSERT INTO products (category_id, name, slug, description, image, base_price, price_unit, options) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$category_id, $name, $slug, $description, $image, $base_price, $price_unit, $options_json]);
        $message = "আলহামদুলিল্লাহ! নতুন প্রোডাক্ট সফলভাবে যোগ করা হয়েছে।";
    } elseif (isset($_POST['edit_product'])) {
        $id = intval($_POST['product_id']);
        $stmt = $pdo->prepare("UPDATE products SET category_id=?, name=?, description=?, image=?, base_price=?, price_unit=?, options=? WHERE id=?");
        $stmt->execute([$category_id, $name, $description, $image, $base_price, $price_unit, $options_json, $id]);
        $message = "প্রোডাক্ট সফলভাবে আপডেট করা হয়েছে!";
    }
}

if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM products WHERE id = ?")->execute([intval($_GET['delete'])]);
    header("Location: manage-products.php?deleted=1"); exit;
}

$all_categories = $pdo->query("SELECT * FROM categories")->fetchAll();
$all_products = $pdo->query("SELECT p.*, c.name as cat_name FROM products p LEFT JOIN categories c ON p.category_id = c.id ORDER BY p.id DESC")->fetchAll();
?>

<!-- Success Message -->
<?php if($message): ?>
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4 font-bangla" role="alert">
    <strong class="font-bold"><i class="fa-solid fa-check-circle"></i> সফল!</strong>
    <span class="block sm:inline"><?= $message ?></span>
</div>
<?php endif; ?>
<?php if(isset($_GET['deleted'])): ?>
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4 font-bangla" role="alert">
    <strong class="font-bold"><i class="fa-solid fa-trash-can"></i> ডিলিট সম্পন্ন!</strong>
    <span class="block sm:inline">প্রোডাক্টটি মুছে ফেলা হয়েছে।</span>
</div>
<?php endif; ?>

<div class="mb-6 flex flex-col md:flex-row md:justify-between md:items-center gap-4">
    <div>
        <h1 class="text-2xl font-bold font-bangla text-gray-800">প্রোডাক্ট ম্যানেজমেন্ট</h1>
        <p class="text-sm text-gray-500 font-bangla mt-1">আপনার দোকানের সব জিনিস এখান থেকে যোগ বা পরিবর্তন করতে পারবেন।</p>
    </div>
    <button onclick="openAddModal()" class="bg-blue-600 text-white px-6 py-2.5 rounded-lg font-bold shadow-lg hover:bg-blue-800 font-bangla transition flex items-center gap-2 transform hover:-translate-y-1">
        <i class="fa-solid fa-circle-plus text-xl"></i> নতুন জিনিস যোগ করুন
    </button>
</div>

<!-- Table Container -->
<div class="bg-white rounded-xl shadow-sm border overflow-hidden">
    <table class="w-full text-left border-collapse text-sm">
        <thead class="bg-gray-100 font-bangla text-gray-700">
            <tr>
                <th class="p-4">প্রোডাক্টের ছবি ও নাম</th>
                <th class="p-4 hidden md:table-cell">ক্যাটাগরি</th>
                <th class="p-4">দাম</th>
                <th class="p-4 text-right">অ্যাকশন (কী করবেন?)</th>
            </tr>
        </thead>
        <tbody class="divide-y divide-gray-100">
            <?php foreach($all_products as $prod): ?>
            <tr class="hover:bg-blue-50 transition group">
                <td class="p-4 flex items-center gap-4">
                    <img src="../uploads/products/<?= $prod['image'] ?: 'default.png' ?>" class="w-12 h-12 rounded-lg object-cover border border-gray-200">
                    <div>
                        <span class="font-bold font-bangla text-gray-800 text-base block"><?= htmlspecialchars($prod['name']) ?></span>
                        <span class="md:hidden text-xs text-gray-500 font-bangla"><?= htmlspecialchars($prod['cat_name']) ?></span>
                    </div>
                </td>
                <td class="p-4 font-bangla text-gray-600 hidden md:table-cell"><?= htmlspecialchars($prod['cat_name']) ?></td>
                <td class="p-4 font-bold text-blue-600 text-base">৳<?= number_format($prod['base_price'], 2) ?></td>
                <td class="p-4 text-right space-x-2">
                    <!-- Edit Button -->
                    <button onclick='openEditModal(<?= json_encode($prod) ?>)' class="bg-blue-100 text-blue-600 px-3 py-1.5 rounded hover:bg-blue-600 hover:text-white transition font-bangla text-xs font-bold" title="এডিট করুন">
                        <i class="fa-solid fa-pen-to-square mr-1"></i> পরিবর্তন
                    </button>
                    <!-- Delete Button -->
                    <a href="manage-products.php?delete=<?= $prod['id'] ?>" onclick="return confirm('আপনি কি নিশ্চিত? এই জিনিসটি ডিলিট হয়ে যাবে!')" class="bg-red-100 text-red-600 px-3 py-1.5 rounded hover:bg-red-600 hover:text-white transition font-bangla text-xs font-bold" title="মুছে ফেলুন">
                        <i class="fa-solid fa-trash mr-1"></i> মুছুন
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
            
            <?php if(empty($all_products)): ?>
            <tr>
                <td colspan="4" class="p-10 text-center text-gray-400 font-bangla">
                    <i class="fa-solid fa-box-open text-4xl mb-3"></i>
                    <p>কোনো প্রোডাক্ট পাওয়া যায়নি। নতুন জিনিস যোগ করুন।</p>
                </td>
            </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Modal -->
<div id="productModal" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center p-4 overflow-y-auto">
    <div class="bg-white rounded-2xl w-full max-w-4xl max-h-[95vh] flex flex-col shadow-2xl mt-10 mb-10">
        
        <!-- Modal Header -->
        <div class="p-5 border-b flex justify-between items-center bg-gray-50 rounded-t-2xl shrink-0">
            <h3 id="modalTitle" class="text-xl font-bold font-bangla text-blue-900 flex items-center gap-2">
                <i class="fa-solid fa-cart-plus"></i> নতুন জিনিস যোগ করুন
            </h3>
            <button onclick="closeModal()" class="w-8 h-8 flex items-center justify-center bg-red-100 text-red-500 rounded-full hover:bg-red-500 hover:text-white transition">
                <i class="fa-solid fa-times text-lg"></i>
            </button>
        </div>
        
        <!-- Modal Body (Scrollable) -->
        <form id="productForm" action="manage-products.php" method="POST" enctype="multipart/form-data" class="p-6 overflow-y-auto grow">
            <input type="hidden" name="product_id" id="edit_id">
            <input type="hidden" name="old_image" id="edit_old_image">

            <!-- Information Box -->
            <div class="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6 rounded-r-lg text-sm text-blue-800 font-bangla">
                <i class="fa-solid fa-circle-info text-blue-600 mr-1"></i> 
                <strong>সহজ নিয়ম:</strong> যেসব নামের পাশে <span class="text-red-500 font-bold">*</span> আছে, সেগুলো অবশ্যই পূরণ করতে হবে। দামের জায়গায় ইংরেজি বা বাংলা যে কোনো সংখ্যা লিখতে পারবেন।
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6 border-b pb-6">
                <!-- Name -->
                <div>
                    <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">
                        <i class="fa-solid fa-tag text-blue-500 w-4"></i> জিনিসের নাম <span class="text-red-500">*</span>
                    </label>
                    <p class="text-[11px] text-gray-500 mb-2 font-bangla">গ্রাহক যে নাম দেখবে (যেমন: প্রফেশনাল ভিজিটিং কার্ড)</p>
                    <input type="text" name="name" id="edit_name" required placeholder="নাম লিখুন..." class="w-full px-4 py-2.5 border border-gray-300 rounded-lg outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 font-bangla bg-gray-50 focus:bg-white transition">
                </div>
                <!-- Category -->
                <div>
                    <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">
                        <i class="fa-solid fa-folder-open text-blue-500 w-4"></i> কোন ক্যাটাগরি? <span class="text-red-500">*</span>
                    </label>
                    <p class="text-[11px] text-gray-500 mb-2 font-bangla">এই জিনিসটি কোন ক্যাটাগরির ভেতরে থাকবে?</p>
                    <select name="category_id" id="edit_category" required class="w-full px-4 py-2.5 border border-gray-300 rounded-lg outline-none focus:border-blue-500 font-bangla bg-gray-50 focus:bg-white transition cursor-pointer">
                        <option value="">-- ক্যাটাগরি সিলেক্ট করুন --</option>
                        <?php foreach($all_categories as $cat): ?><option value="<?= $cat['id'] ?>"><?= $cat['name'] ?></option><?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6 border-b pb-6">
                <!-- Price -->
                <div>
                    <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">
                        <i class="fa-solid fa-money-bill-wave text-green-500 w-4"></i> বেসিক দাম (৳) <span class="text-red-500">*</span>
                    </label>
                    <p class="text-[11px] text-gray-500 mb-2 font-bangla">শুধু সংখ্যা লিখুন (যেমন: ৫০০)</p>
                    <input type="text" name="base_price" id="edit_price" required placeholder="500" class="w-full px-4 py-2.5 border border-gray-300 rounded-lg outline-none focus:border-blue-500 font-bangla bg-gray-50 focus:bg-white">
                </div>
                <!-- Unit -->
                <div>
                    <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">
                        <i class="fa-solid fa-box text-orange-500 w-4"></i> বিক্রির হিসাব
                    </label>
                    <p class="text-[11px] text-gray-500 mb-2 font-bangla">যেমন: প্রতি পিস, প্যাকেট, হাজার</p>
                    <input type="text" name="price_unit" id="edit_unit" placeholder="যেমন: প্রতি প্যাকেট" class="w-full px-4 py-2.5 border border-gray-300 rounded-lg outline-none focus:border-blue-500 font-bangla bg-gray-50 focus:bg-white">
                </div>
                <!-- Image -->
                <div>
                    <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">
                        <i class="fa-solid fa-image text-purple-500 w-4"></i> সুন্দর একটি ছবি দিন
                    </label>
                    <p class="text-[11px] text-gray-500 mb-2 font-bangla">মোবাইল বা কম্পিউটার থেকে সিলেক্ট করুন</p>
                    <input type="file" name="image" class="w-full text-sm font-bangla file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 cursor-pointer">
                </div>
            </div>

            <!-- Printing Options (Made VERY clear) -->
            <div class="bg-gray-50 p-5 rounded-xl border border-gray-200 mb-6">
                <h4 class="font-bold mb-4 font-bangla text-gray-800 text-lg flex items-center gap-2">
                    <i class="fa-solid fa-list-check text-blue-600"></i> সাইজ, কালার এবং প্যাকেজ (ঐচ্ছিক)
                </h4>
                
                <!-- Package Option (Specially designed for easy understanding) -->
                <div class="bg-white p-4 rounded-lg border border-blue-100 shadow-sm mb-5">
                    <label class="block text-sm font-bold text-gray-800 mb-1 font-bangla">
                        <i class="fa-solid fa-layer-group text-blue-500"></i> কয় পিস নিলে কত দাম? (প্যাকেজ)
                    </label>
                    <p class="text-xs text-gray-500 mb-3 font-bangla leading-relaxed">
                        যদি পরিমাণের উপর দাম আলাদা হয়, তবে এখানে লিখবেন। লেখার নিয়ম হলো: <br>
                        <strong class="bg-blue-50 text-blue-700 px-2 py-1 rounded inline-block mt-1">১০০ পিস: ৫০০ | ৫০০ পিস: ১৫০০ | ১০০০ পিস: ২৫০০</strong> <br>
                        (মাঝে অবশ্যই এই খাড়া দাগটি <strong class="text-red-500 text-lg">|</strong> ব্যবহার করবেন)
                    </p>
                    <input type="text" name="opt_packages" id="val_Packages" placeholder="উদাহরণ: 100 Pcs: 500 | 500 Pcs: 1500" class="w-full px-4 py-3 border border-gray-300 rounded-lg outline-none focus:border-blue-500 font-bangla">
                </div>

                <!-- Color, Size, etc -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-1 font-bangla">কালার (রঙ)</label>
                        <p class="text-[10px] text-gray-400 mb-1 font-bangla">কমা (,) দিয়ে লিখুন (যেমন: লাল, নীল, সিঙ্গেল কালার)</p>
                        <input type="text" name="opt_color" id="val_Color" class="w-full px-3 py-2 border border-gray-300 rounded outline-none font-bangla">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-1 font-bangla">সাইজ</label>
                        <p class="text-[10px] text-gray-400 mb-1 font-bangla">কমা (,) দিয়ে লিখুন (যেমন: 2x3 ইঞ্চি, A4, A5)</p>
                        <input type="text" name="opt_size" id="val_Size" class="w-full px-3 py-2 border border-gray-300 rounded outline-none font-bangla">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-1 font-bangla">কাগজের ধরন</label>
                        <p class="text-[10px] text-gray-400 mb-1 font-bangla">যেমন: 300 GSM Art Card, 100 GSM</p>
                        <input type="text" name="opt_paper" id="val_Paper_Type" class="w-full px-3 py-2 border border-gray-300 rounded outline-none font-bangla">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-1 font-bangla">ল্যামিনেশন</label>
                        <p class="text-[10px] text-gray-400 mb-1 font-bangla">যেমন: ম্যাট, গ্লসি, ল্যামিনেশন ছাড়া</p>
                        <input type="text" name="opt_lamination" id="val_Lamination" class="w-full px-3 py-2 border border-gray-300 rounded outline-none font-bangla">
                    </div>
                </div>
            </div>

            <!-- Description -->
            <div class="mb-6">
                <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">
                    <i class="fa-solid fa-align-left text-blue-500 w-4"></i> জিনিসের বিস্তারিত বিবরণ
                </label>
                <p class="text-[11px] text-gray-500 mb-2 font-bangla">গ্রাহক যেন পড়ে বুঝতে পারে জিনিসটা কেমন।</p>
                <textarea name="description" id="edit_desc" rows="4" placeholder="এখানে বিস্তারিত লিখুন..." class="w-full px-4 py-3 border border-gray-300 rounded-lg outline-none focus:border-blue-500 font-bangla bg-gray-50 focus:bg-white"></textarea>
            </div>

            <!-- Submit Button (Sticky at bottom of form scroll) -->
            <div class="sticky bottom-0 bg-white pt-4 pb-2 border-t">
                <button type="submit" name="add_product" id="submitBtn" class="w-full bg-green-600 text-white py-4 rounded-xl font-bold font-bangla text-lg shadow-lg hover:bg-green-700 hover:shadow-xl transition transform hover:-translate-y-1 flex justify-center items-center gap-2">
                    <i class="fa-solid fa-check-circle text-xl"></i> <span>সব ঠিক আছে, সেভ করুন</span>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    const modal = document.getElementById('productModal');
    const form = document.getElementById('productForm');

    function openAddModal() {
        form.reset(); 
        document.getElementById('modalTitle').innerHTML = '<i class="fa-solid fa-cart-plus"></i> নতুন জিনিস যোগ করুন';
        document.getElementById('submitBtn').name = "add_product"; 
        document.getElementById('submitBtn').querySelector('span').innerText = "সব ঠিক আছে, সেভ করুন";
        document.getElementById('submitBtn').className = "w-full bg-green-600 text-white py-4 rounded-xl font-bold font-bangla text-lg shadow-lg hover:bg-green-700 hover:shadow-xl transition transform hover:-translate-y-1 flex justify-center items-center gap-2";
        document.getElementById('edit_id').value = "";
        modal.classList.remove('hidden');
    }

    function openEditModal(data) {
        form.reset(); 
        document.getElementById('modalTitle').innerHTML = '<i class="fa-solid fa-pen-to-square"></i> প্রোডাক্ট পরিবর্তন করুন';
        document.getElementById('submitBtn').name = "edit_product"; 
        document.getElementById('submitBtn').querySelector('span').innerText = "পরিবর্তন সেভ করুন";
        document.getElementById('submitBtn').className = "w-full bg-blue-600 text-white py-4 rounded-xl font-bold font-bangla text-lg shadow-lg hover:bg-blue-700 hover:shadow-xl transition transform hover:-translate-y-1 flex justify-center items-center gap-2";
        
        document.getElementById('edit_id').value = data.id;
        document.getElementById('edit_name').value = data.name; 
        document.getElementById('edit_category').value = data.category_id;
        document.getElementById('edit_price').value = data.base_price; 
        document.getElementById('edit_unit').value = data.price_unit;
        document.getElementById('edit_desc').value = data.description; 
        document.getElementById('edit_old_image').value = data.image;

        if(data.options) {
            const opts = JSON.parse(data.options);
            for (const key in opts) {
                let idName = key.includes('Color') ? 'Color' : (key.includes('Size') ? 'Size' : key.replace(/[^a-zA-Z]/g, '_'));
                if(key === 'Packages') {
                    let pkgArr = []; for(let p in opts[key]) pkgArr.push(p + ": " + opts[key][p]);
                    document.getElementById('val_Packages').value = pkgArr.join(" | ");
                } else {
                    let input = document.getElementById("val_" + idName);
                    if(input) input.value = opts[key].join(", ");
                }
            }
        }
        modal.classList.remove('hidden');
    }
    
    function closeModal() { 
        modal.classList.add('hidden'); 
    }
</script>
<?php require_once 'includes/footer.php'; ?>