<?php
// আউটপুট বাফারিং (যাতে কোনো হেডার এরর না আসে)
ob_start();
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'] ?? 0);
    $base_price = floatval(bnToEn($_POST['base_price'] ?? '0'));
    $price_unit = trim($_POST['price_unit'] ?? '');
    $description = trim($_POST['description'] ?? '');
    
    $final_options =[];
    
    // সাধারণ অপশন ও কালার (?? '' দেওয়া হয়েছে যাতে null error না আসে)
    $predefined = [
        'Color (কালার)' => $_POST['opt_color'] ?? '',
        'Size (সাইজ)'   => $_POST['opt_size'] ?? '',
        'Paper Type'    => $_POST['opt_paper'] ?? '',
        'Lamination'    => $_POST['opt_lamination'] ?? '',
        'Print Side'    => $_POST['opt_side'] ?? '',
        'Finishing'     => $_POST['opt_finishing'] ?? ''
    ];

    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);
        $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'])) {
    $id = intval($_GET['delete']);
    // ইমেজ মুছে ফেলা
    $stmt = $pdo->prepare("SELECT image FROM products WHERE id=?");
    $stmt->execute([$id]);
    $img = $stmt->fetchColumn();
    if($img && file_exists('../uploads/products/'.$img)) @unlink('../uploads/products/'.$img);
    
    // ডাটাবেস থেকে ডিলিট
    $pdo->prepare("DELETE FROM products WHERE id = ?")->execute([$id]);
    echo "<script>window.location.href='manage-products.php?deleted=1';</script>"; 
    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();
?>

<div class="mb-6 flex justify-between items-center">
    <h1 class="text-2xl font-bold font-bangla text-gray-800">প্রোডাক্ট ম্যানেজমেন্ট</h1>
    <button onclick="openAddModal()" class="bg-blue-600 text-white px-5 py-2.5 rounded-lg font-bold shadow hover:bg-blue-700 transition font-bangla">
        <i class="fa-solid fa-plus mr-1"></i> নতুন প্রোডাক্ট
    </button>
</div>

<?php if ($message || isset($_GET['deleted'])): ?>
    <div class="bg-green-100 text-green-700 p-4 rounded-lg mb-6 font-bangla border border-green-200 flex items-center gap-2">
        <i class="fa-solid fa-circle-check"></i> <?= $message ?: "প্রোডাক্ট মুছে ফেলা হয়েছে!" ?>
    </div>
<?php endif; ?>

<!-- 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-50 font-bangla text-gray-500 border-b">
            <tr>
                <th class="p-4 font-semibold">প্রোডাক্ট</th>
                <th class="p-4 font-semibold">ক্যাটাগরি</th>
                <th class="p-4 font-semibold">দাম</th>
                <th class="p-4 text-right font-semibold">অ্যাকশন</th>
            </tr>
        </thead>
        <tbody class="divide-y divide-gray-50">
            <?php foreach($all_products as $prod): ?>
            <tr class="hover:bg-gray-50 transition">
                <td class="p-4 flex items-center gap-3">
                    <img src="../uploads/products/<?= $prod['image'] ?: 'default.png' ?>" class="w-10 h-10 rounded-lg object-cover border bg-white">
                    <span class="font-bold font-bangla text-gray-800"><?= htmlspecialchars($prod['name']) ?></span>
                </td>
                <td class="p-4 font-bangla text-gray-500"><?= htmlspecialchars($prod['cat_name']) ?></td>
                <td class="p-4">
                    <span class="font-bold text-blue-600 en-font block">৳<?= $prod['base_price'] ?></span>
                    <span class="text-[10px] text-gray-400 font-bangla"><?= htmlspecialchars($prod['price_unit']) ?></span>
                </td>
                <td class="p-4 text-right">
                    <button onclick='openEditModal(<?= json_encode($prod) ?>)' class="w-8 h-8 inline-flex items-center justify-center bg-blue-50 text-blue-600 rounded hover:bg-blue-600 hover:text-white transition mr-2">
                        <i class="fa-solid fa-pen-to-square"></i>
                    </button>
                    <a href="manage-products.php?delete=<?= $prod['id'] ?>" onclick="return confirm('নিশ্চিতভাবে ডিলিট করতে চান?')" class="w-8 h-8 inline-flex items-center justify-center bg-red-50 text-red-500 rounded hover:bg-red-500 hover:text-white transition">
                        <i class="fa-solid fa-trash-can"></i>
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Modal -->
<div id="productModal" class="fixed inset-0 bg-slate-900/60 z-50 hidden flex items-center justify-center p-4 backdrop-blur-sm">
    <div class="bg-white rounded-2xl w-full max-w-4xl max-h-[90vh] overflow-y-auto shadow-2xl">
        <div class="p-6 border-b flex justify-between items-center sticky top-0 bg-white z-20">
            <h3 id="modalTitle" class="text-xl font-bold font-bangla text-gray-800">প্রোডাক্ট যোগ করুন</h3>
            <button onclick="closeModal()" class="text-gray-400 hover:text-red-500 transition"><i class="fa-solid fa-times text-xl"></i></button>
        </div>
        
        <form id="productForm" action="manage-products.php" method="POST" enctype="multipart/form-data" class="p-6">
            <input type="hidden" name="product_id" id="edit_id">
            <input type="hidden" name="old_image" id="edit_old_image">

            <div class="grid grid-cols-1 md:grid-cols-3 gap-5 mb-5">
                <div class="md:col-span-2">
                    <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">নাম *</label>
                    <input type="text" name="name" id="edit_name" required class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-lg outline-none focus:border-blue-500 font-bangla">
                </div>
                <div>
                    <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">ক্যাটাগরি *</label>
                    <select name="category_id" id="edit_category" required class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-lg font-bangla outline-none focus:border-blue-500">
                        <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-5 mb-6">
                <div>
                    <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">ডিফল্ট দাম (৳)</label>
                    <input type="text" name="base_price" id="edit_price" placeholder="যেমন: ৫০০ বা 500" class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-lg outline-none focus:border-blue-500 en-font">
                </div>
                <div>
                    <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">একক (যেমন: পিস)</label>
                    <input type="text" name="price_unit" id="edit_unit" placeholder="প্রতি পিস / বক্স" class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-lg font-bangla outline-none focus:border-blue-500">
                </div>
                <div>
                    <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">ছবি (নতুন দিলে আগেরটি মুছবে)</label>
                    <input type="file" name="image" class="w-full text-xs pt-2">
                </div>
            </div>

            <!-- Printing Options -->
            <div class="bg-blue-50/50 p-5 rounded-xl border border-blue-100 mb-6">
                <h4 class="font-bold mb-4 font-bangla text-blue-800 border-b border-blue-200 pb-2"><i class="fa-solid fa-gears mr-1"></i> অতিরিক্ত অপশন ও প্যাকেজ প্রাইস</h4>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
                    <div class="md:col-span-3">
                        <label class="block text-xs font-bold text-gray-600 font-bangla mb-1">প্যাকেজ ও দাম (100 Pcs: 500 | 500 Pcs: 1500)</label>
                        <input type="text" name="opt_packages" id="val_Packages" placeholder="যেমন: 100 পিস: 500 | 500 পিস: 1500" class="w-full px-3 py-2.5 bg-white border border-blue-200 rounded-lg text-sm font-bangla outline-none focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-gray-600 font-bangla mb-1">কালার (Color)</label>
                        <input type="text" name="opt_color" id="val_Color" placeholder="সিঙ্গেল কালার, মাল্টিকালার" class="w-full px-3 py-2.5 bg-white border border-blue-200 rounded-lg text-sm font-bangla outline-none focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-gray-600 font-bangla mb-1">সাইজ (Size)</label>
                        <input type="text" name="opt_size" id="val_Size" placeholder="A4, A5, Custom" class="w-full px-3 py-2.5 bg-white border border-blue-200 rounded-lg text-sm font-bangla outline-none focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-gray-600 font-bangla mb-1">কাগজের ধরন</label>
                        <input type="text" name="opt_paper" id="val_Paper_Type" placeholder="80gsm, Art Paper, PVC" class="w-full px-3 py-2.5 bg-white border border-blue-200 rounded-lg text-sm font-bangla outline-none focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-gray-600 font-bangla mb-1">ল্যামিনেশন</label>
                        <input type="text" name="opt_lamination" id="val_Lamination" placeholder="None, Matte, Glossy" class="w-full px-3 py-2.5 bg-white border border-blue-200 rounded-lg text-sm font-bangla outline-none focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-gray-600 font-bangla mb-1">প্রিন্ট সাইড (Print Side)</label>
                        <input type="text" name="opt_side" id="val_Print_Side" placeholder="Single Side, Both Side" class="w-full px-3 py-2.5 bg-white border border-blue-200 rounded-lg text-sm font-bangla outline-none focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-gray-600 font-bangla mb-1">ফিনিশিং (Finishing)</label>
                        <input type="text" name="opt_finishing" id="val_Finishing" placeholder="Pad Binding, Spiral" class="w-full px-3 py-2.5 bg-white border border-blue-200 rounded-lg text-sm font-bangla outline-none focus:border-blue-500">
                    </div>
                </div>
            </div>

            <div class="mb-6">
                <label class="block text-sm font-bold mb-1 font-bangla text-gray-700">প্রোডাক্টের বিবরণ</label>
                <textarea name="description" id="edit_desc" rows="3" class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-lg outline-none focus:border-blue-500 font-bangla text-sm"></textarea>
            </div>

            <button type="submit" name="add_product" id="submitBtn" class="w-full bg-slate-800 text-white py-3.5 rounded-xl font-bold font-bangla shadow-lg hover:bg-black transition">সংরক্ষণ করুন</button>
        </form>
    </div>
</div>

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

    function openAddModal() {
        form.reset(); 
        document.getElementById('modalTitle').innerText = "নতুন প্রোডাক্ট যোগ করুন";
        document.getElementById('submitBtn').name = "add_product"; 
        document.getElementById('edit_id').value = "";
        modal.classList.remove('hidden');
    }

    function openEditModal(data) {
        form.reset(); 
        document.getElementById('modalTitle').innerText = "প্রোডাক্ট আপডেট করুন";
        document.getElementById('submitBtn').name = "edit_product"; 
        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.includes('Side') ? 'Print_Side' : 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'; 
ob_end_flush(); 
?>