<?php
include "db.php";
include "header.php";

$success = '';
$error = '';

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $product_name = trim($_POST['name'] ?? '');
    $product_code = trim($_POST['product_code'] ?? '');
    $ingredient_ids = $_POST['ingredient_id'] ?? [];
    $quantities = $_POST['quantity'] ?? [];

    if (empty($product_name)) {
        $error = "Παρακαλώ δώστε όνομα προϊόντος.";
    } else {
        if (empty($product_code)) {
            $res = $db->query("SELECT MAX(id) AS max_id FROM products");
            $row = $res->fetch_assoc();
            $next_id = ($row['max_id'] ?? 0) + 1;
            $product_code = 'PRD-' . str_pad($next_id, 5, '0', STR_PAD_LEFT);
        }

        $stmt = $db->prepare("INSERT INTO products (name, product_code) VALUES (?, ?)");
        $stmt->bind_param("ss", $product_name, $product_code);
        $stmt->execute();
        $product_id = $stmt->insert_id;

        for ($i = 0; $i < count($ingredient_ids); $i++) {
            $ingredient_id = (int)$ingredient_ids[$i];
            $quantity = (float)$quantities[$i];

            if ($ingredient_id > 0 && $quantity > 0) {
                $resUnit = $db->query("SELECT unit_id FROM ingredients WHERE id = $ingredient_id LIMIT 1");
                $rowUnit = $resUnit->fetch_assoc();
                $unit_id = $rowUnit['unit_id'];

                $stmt2 = $db->prepare("INSERT INTO product_ingredients (product_id, ingredient_id, quantity, unit_id) VALUES (?, ?, ?, ?)");
                $stmt2->bind_param("iidi", $product_id, $ingredient_id, $quantity, $unit_id);
                $stmt2->execute();
            }
        }

        $success = "✅ Το προϊόν καταχωρήθηκε επιτυχώς!";
    }
}

$ingredients = $db->query("
    SELECT i.id, i.name, u.name AS unit_name
    FROM ingredients i
    JOIN units u ON i.unit_id = u.id
    ORDER BY i.name
");
?>

<style>
/* Αφαιρούμε default margin/padding */
html, body {
    margin: 0;
    padding: 0;
    height: 100%;
}

/* Grid Layout με Sidebar */
body {
    display: grid;
    grid-template-columns: 250px 1fr; /* sidebar 250px */
    height: 100vh; /* ολόκληρο viewport ύψος */
}


/* Content */
#content {
    grid-column: 2;
    display: flex;
    justify-content: center; /* οριζόντια center */
    align-items: center;     /* κάθετα center */
    height: 100%;            /* γεμίζει grid cell */
    padding: 20px;
    margin-top: -150px;
    box-sizing: border-box;
}

/* Card */
.card {
    width: 100%;
    max-width: 500px;
    padding: 25px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

/* Υλικά */
.ingredient-row {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
}
.ingredient-row select,
.ingredient-row input {
    flex: 1;
    padding: 5px;
}
.remove-row {
    background: #e74c3c;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}
</style>

<div id="content">
    <div class="card">
        <h3 class="text-center mb-4"><i class="bi bi-plus-circle"></i> Προσθήκη Προϊόντος</h3>

        <?php if ($success): ?>
            <div class="alert alert-success text-center"><?= $success ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-danger text-center"><?= $error ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="mb-3">
                <label class="form-label">Κωδικός Προϊόντος:</label>
                <input type="text" name="product_code" class="form-control" placeholder="Αφήστε κενό για αυτόματο">
            </div>

            <div class="mb-3">
                <label class="form-label">Όνομα Προϊόντος:</label>
                <input type="text" name="name" class="form-control" required>
            </div>

            <h5>Υλικά</h5>
            <div id="ingredients-list">
                <div class="ingredient-row">
                    <select name="ingredient_id[]" class="form-select" required>
                        <option value="">-- Επιλογή Υλικού --</option>
                        <?php
                        $ingredients->data_seek(0);
                        while ($row = $ingredients->fetch_assoc()):
                        ?>
                            <option value="<?= $row['id'] ?>">
                                <?= htmlspecialchars($row['name']) ?> (<?= htmlspecialchars($row['unit_name']) ?>)
                            </option>
                        <?php endwhile; ?>
                    </select>
                    <input type="number" step="0.0001" name="quantity[]" class="form-control" placeholder="Ποσότητα" style="max-width:120px;" required>
                    <button type="button" class="remove-row">X</button>
                </div>
            </div>

            <div class="mb-3">
                <button type="button" id="add-ingredient" class="btn btn-warning btn-sm"><i class="bi bi-plus-circle"></i> Προσθήκη Υλικού</button>
            </div>

            <button type="submit" class="btn btn-success w-100"><i class="bi bi-check-circle"></i> Καταχώρηση Προϊόντος</button>
            <a href="recipes_list.php" class="btn btn-secondary w-100 mt-3"><i class="bi bi-arrow-left"></i> Επιστροφή στη λίστα</a>
        </form>
    </div>
</div>

<script>
document.getElementById('add-ingredient').addEventListener('click', function(){
    let container = document.getElementById('ingredients-list');
    let row = container.querySelector('.ingredient-row').cloneNode(true);
    row.querySelectorAll('input, select').forEach(input => input.value = '');
    container.appendChild(row);
});

document.addEventListener('click', function(e){
    if(e.target && e.target.classList.contains('remove-row')){
        let rows = document.querySelectorAll('.ingredient-row');
        if(rows.length > 1){
            e.target.closest('.ingredient-row').remove();
        }
    }
});
</script>

<?php include "footer.php"; ?>
