<?php
require_once '../../includes/auth_middleware.php';
require_once '../../config/database.php';
require_once '../../includes/header.php';
checkRole(['admin']);

// Ambil semua produk
$products = $pdo->query("SELECT * FROM products")->fetchAll();

// Ambil semua bahan baku untuk dropdown
$ingredients = $pdo->query("SELECT * FROM ingredients")->fetchAll();
?>

<div class="container" style="max-width: 900px; padding-bottom: 50px;">
    
    <?php if (isset($_GET['status']) && $_GET['status'] == 'updated'): ?>
        <div style="background: #ecfdf5; border-left: 5px solid #10b981; color: #065f46; padding: 15px; margin-bottom: 20px; border-radius: 8px;">
            ✅ Takaran resep berhasil diperbarui!
        </div>
    <?php endif; ?>

    <header style="margin-bottom: 2rem;">
        <h2 style="margin:0;">MANAJEMEN RESEP</h2>
        <p style="color: #6b7280; margin:0;">Tentukan komposisi bahan untuk setiap menu</p>
    </header>

    <?php foreach ($products as $p): ?>
        <div class="card" style="margin-bottom: 2rem; border-top: 4px solid var(--primary);">
            <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid #eee; padding-bottom: 10px; margin-bottom: 15px;">
                <h3 style="margin:0; color: #1f2937;"><?= strtoupper($p['product_name']) ?></h3>
                <span style="font-size: 0.8rem; font-weight: bold; background: #e5e7eb; color: #374151; padding: 5px 12px; border-radius: 20px;">
                    Harga Jual: Rp <?= number_format($p['selling_price'], 0, ',', '.') ?>
                </span>
            </div>

            <table style="width: 100%; border-collapse: collapse; margin-bottom: 15px;">
                <thead>
                    <tr style="text-align: left; font-size: 0.85rem; color: #6b7280; background: #f9fafb;">
                        <th style="padding: 10px;">Bahan Baku</th>
                        <th style="padding: 10px;">Takaran Penggunaan</th>
                        <th style="padding: 10px; text-align: right;">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $stmt = $pdo->prepare("SELECT r.*, i.name, i.unit FROM recipes r JOIN ingredients i ON r.ingredient_id = i.id WHERE r.product_id = ?");
                    $stmt->execute([$p['id']]);
                    $recipe_items = $stmt->fetchAll();
                    
                    if(count($recipe_items) == 0): ?>
                        <tr><td colspan="3" style="text-align: center; padding: 15px; color: #9ca3af; font-size: 0.85rem;">Belum ada bahan untuk menu ini.</td></tr>
                    <?php endif;

                    foreach ($recipe_items as $item):
                    ?>
                    <tr style="border-bottom: 1px solid #eee;">
                        <td style="padding: 10px; font-weight: bold; color: #374151;"><?= $item['name'] ?></td>
                        <td style="padding: 10px; color: #10b981; font-weight: bold; font-size: 1.1rem;">
                            <?= rtrim(rtrim(number_format($item['usage_qty'], 2, '.', ''), '0'), '.') ?> 
                            <span style="font-size: 0.8rem; color: #6b7280; font-weight: normal;"><?= $item['unit'] ?></span>
                        </td>
                        <td style="padding: 10px; text-align: right;">
                            <button onclick='openEditModal(<?= json_encode($item) ?>, "<?= htmlspecialchars($p['product_name']) ?>")' style="background: #fbbf24; color: #92400e; border: none; padding: 5px 10px; border-radius: 5px; cursor: pointer; font-size: 0.75rem; font-weight: bold; margin-right: 5px;">
                                ✏️ Edit
                            </button>
                            <a href="../../api/delete_recipe.php?id=<?= $item['id'] ?>" onclick="return confirm('Hapus bahan ini dari resep?')" style="background: #fee2e2; color: #dc2626; padding: 5px 10px; border-radius: 5px; text-decoration: none; font-size: 0.75rem; font-weight: bold;">
                                🗑️ Hapus
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <form action="../../api/add_recipe.php" method="POST" style="display: flex; flex-wrap: wrap; gap: 10px; background: #f3f4f6; padding: 15px; border-radius: 8px;">
                <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
                <div style="flex: 2; min-width: 200px;">
                    <select name="ingredient_id" required style="width: 100%; padding: 10px; border-radius: 6px; border: 1px solid #d1d5db; outline: none;">
                        <option value="">+ Tambah Bahan Baru...</option>
                        <?php foreach ($ingredients as $ing): ?>
                            <option value="<?= $ing['id'] ?>"><?= $ing['name'] ?> (<?= $ing['unit'] ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div style="flex: 1; min-width: 100px;">
                    <input type="number" step="0.01" name="usage_qty" placeholder="Takaran (Qty)" required style="width: 100%; padding: 10px; border-radius: 6px; border: 1px solid #d1d5db; outline: none; box-sizing: border-box;">
                </div>
                <button type="submit" class="btn-primary" style="flex: 1; min-width: 100px; padding: 10px; font-size: 0.9rem; border-radius: 6px;">Simpan</button>
            </form>
        </div>
    <?php endforeach; ?>
</div>

<div id="editModal" style="display:none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); align-items: center; justify-content: center; backdrop-filter: blur(2px);">
    <div class="card" style="width: 100%; max-width: 400px; margin: 20px; position: relative;">
        <span onclick="closeModal()" style="position: absolute; right: 15px; top: 15px; font-size: 1.5rem; cursor: pointer; color: #9ca3af;">&times;</span>
        
        <h3 style="margin-top: 0; color: #1f2937; border-bottom: 2px solid #f3f4f6; padding-bottom: 10px;">Update Takaran Bahan</h3>
        
        <form action="../../api/update_recipe.php" method="POST">
            <input type="hidden" name="recipe_id" id="edit_id">
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; font-size: 0.8rem; font-weight: bold; margin-bottom: 5px; color: #6b7280;">Menu Produk</label>
                <input type="text" id="edit_product_name" style="width: 100%; padding: 10px; border: none; background: transparent; font-weight: bold; color: var(--accent);" readonly>
            </div>

            <div style="margin-bottom: 15px;">
                <label style="display: block; font-size: 0.8rem; font-weight: bold; margin-bottom: 5px; color: #6b7280;">Nama Bahan</label>
                <input type="text" id="edit_ingredient_name" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px; background: #f9fafb; color: #374151; font-weight: bold;" readonly>
            </div>

            <div style="margin-bottom: 25px;">
                <label style="display: block; font-size: 0.8rem; font-weight: bold; margin-bottom: 5px; color: #10b981;">Takaran Penggunaan (Qty)</label>
                <div style="display: flex; align-items: center; gap: 10px;">
                    <input type="number" step="0.01" name="usage_qty" id="edit_qty" style="flex: 1; padding: 12px; border: 2px solid #10b981; border-radius: 8px; font-size: 1.2rem; font-weight: bold; color: #065f46; outline: none;" required>
                    <span id="edit_unit" style="font-weight: bold; color: #6b7280; width: 50px;"></span>
                </div>
            </div>

            <button type="submit" class="btn-primary" style="width: 100%; padding: 15px; font-size: 1.1rem; border-radius: 8px;">💾 Simpan Perubahan</button>
        </form>
    </div>
</div>

<script>
function openEditModal(item, productName) {
    // Isi data ke dalam form modal
    document.getElementById('edit_id').value = item.id;
    document.getElementById('edit_product_name').value = productName;
    document.getElementById('edit_ingredient_name').value = item.name;
    document.getElementById('edit_qty').value = item.usage_qty;
    document.getElementById('edit_unit').innerText = item.unit;
    
    // Tampilkan modal
    document.getElementById('editModal').style.display = 'flex';
}

function closeModal() {
    document.getElementById('editModal').style.display = 'none';
}

// Tutup modal jika klik di luar kotak
window.onclick = function(event) {
    const modal = document.getElementById('editModal');
    if (event.target == modal) {
        closeModal();
    }
}
</script>