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

// Έλεγχος ID
if (!isset($_GET['id'])) die("<p style='color:red;'>Missing product ID.</p>");
$product_id = (int)$_GET['id'];

// Φέρε το προϊόν
$stmt = $db->prepare("SELECT * FROM products WHERE id=?");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$product = $stmt->get_result()->fetch_assoc();
if (!$product) die("<p style='color:red;'>Το προϊόν δεν βρέθηκε.</p>");

// Φέρε όλα τα υλικά
$ingredients_query = "SELECT i.*, u.name AS unit_name 
                      FROM ingredients i 
                      LEFT JOIN units u ON i.unit_id = u.id
                      ORDER BY i.name";
$ingredients_all = $db->query($ingredients_query);

// Αν υποβλήθηκε η φόρμα
$success = false;
$error = '';

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

    if (empty($name)) {
        $error = "Παρακαλώ συμπληρώστε το όνομα του προϊόντος.";
    } else {
        $stmt2 = $db->prepare("UPDATE products SET name=?, product_code=? WHERE id=?");
        $stmt2->bind_param("ssi", $name, $product_code, $product_id);
        $stmt2->execute();

        $stmt3 = $db->prepare("DELETE FROM product_ingredients WHERE product_id=?");
        $stmt3->bind_param("i", $product_id);
        $stmt3->execute();

        for ($i = 0; $i < count($ingredient_ids); $i++) {
            if ($ingredient_ids[$i] && $quantities[$i] > 0) {
                $stmt4 = $db->prepare("INSERT INTO product_ingredients (product_id, ingredient_id, quantity, unit_id) 
                                       VALUES (?, ?, ?, ?)");
                $stmt4->bind_param("iidi", $product_id, $ingredient_ids[$i], $quantities[$i], $units[$i]);
                $stmt4->execute();
            }
        }

        $success = true;
        $stmt = $db->prepare("SELECT * FROM products WHERE id=?");
        $stmt->bind_param("i", $product_id);
        $stmt->execute();
        $product = $stmt->get_result()->fetch_assoc();
    }
}

// Φέρε υλικά προϊόντος
$stmt5 = $db->prepare("SELECT * FROM product_ingredients WHERE product_id=?");
$stmt5->bind_param("i", $product_id);
$stmt5->execute();
$product_ingredients = $stmt5->get_result()->fetch_all(MYSQLI_ASSOC);
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">

<style>
/* Wrapper page */
.edit-product-page {
    width: calc(100vw - 250px - 30px);
    margin-left: 250px;
    margin-right: 30px;
    min-height: 100vh;

    display: flex;
    align-items: center;      /* κάθετα στο κέντρο */
    justify-content: center;  /* οριζόντια στο κέντρο */

    padding: 20px;
    box-sizing: border-box;
}

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

/* Ingredient row */
.ingredient-row {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
}
.ingredient-row select,
.ingredient-row input {
    flex: 1;
    padding: 5px;
}
.delete-row {
    background: #e74c3c;
    color: #fff;
    border: none;
    padding: 5px 10px;
    border-radius: 6px;
    cursor: pointer;
}

/* Alerts */
.alert-success,
.alert-danger {
    text-align: center;
    margin-top: 10px;
}
</style>

<div class="edit-product-page">
    <div class="edit-product-card">
        <h3 class="text-center mb-4"><i class="bi bi-pencil-square"></i> Επεξεργασία Προϊόντος</h3>

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

        <form method="POST">
            <div class="mb-3">
                <label>Κωδικός Προϊόντος:</label>
                <input type="text" name="product_code" class="form-control" value="<?= htmlspecialchars($product['product_code']) ?>" required>
            </div>

            <div class="mb-3">
                <label>Όνομα Προϊόντος:</label>
                <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($product['name']) ?>" required>
            </div>

            <h5>Υλικά</h5>
            <div id="ingredients-container">
                <?php if ($product_ingredients): ?>
                    <?php foreach ($product_ingredients as $pi): ?>
                        <?php
                        $unitQ = $db->query("SELECT name FROM units WHERE id=" . (int)$pi['unit_id']);
                        $unitName = $unitQ->fetch_assoc()['name'] ?? "";
                        ?>
                        <div class="ingredient-row">
                            <select name="ingredient_id[]" class="ingredient-select form-select">
                                <option value="">-- Επιλογή Υλικού --</option>
                                <?php 
                                $ingredients_all->data_seek(0);
                                while ($ing = $ingredients_all->fetch_assoc()): ?>
                                    <option value="<?= $ing['id'] ?>" data-unit-id="<?= $ing['unit_id'] ?>" data-unit-name="<?= $ing['unit_name'] ?>" <?= ($ing['id']==$pi['ingredient_id'])?'selected':'' ?>>
                                        <?= htmlspecialchars($ing['name']) ?> (<?= $ing['unit_name'] ?>)
                                    </option>
                                <?php endwhile; ?>
                            </select>
                            <input type="number" step="0.0001" name="quantity[]" value="<?= $pi['quantity'] ?>" class="form-control">
                            <input type="text" class="unit-field form-control" name="unit_name[]" value="<?= $unitName ?>" readonly>
                            <input type="hidden" name="unit_id[]" value="<?= $pi['unit_id'] ?>">
                            <button type="button" class="delete-row">X</button>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="ingredient-row">
                        <select name="ingredient_id[]" class="ingredient-select form-select">
                            <option value="">-- Επιλογή Υλικού --</option>
                            <?php 
                            $ingredients_all->data_seek(0);
                            while ($ing = $ingredients_all->fetch_assoc()): ?>
                                <option value="<?= $ing['id'] ?>" data-unit-id="<?= $ing['unit_id'] ?>" data-unit-name="<?= $ing['unit_name'] ?>">
                                    <?= htmlspecialchars($ing['name']) ?> (<?= $ing['unit_name'] ?>)
                                </option>
                            <?php endwhile; ?>
                        </select>
                        <input type="number" step="0.0001" name="quantity[]" placeholder="Ποσότητα" class="form-control">
                        <input type="text" class="unit-field form-control" name="unit_name[]" readonly>
                        <input type="hidden" name="unit_id[]">
                        <button type="button" class="delete-row">X</button>
                    </div>
                <?php endif; ?>
            </div>

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

            <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-2"><i class="bi bi-arrow-left"></i> Επιστροφή στη λίστα</a>

            <?php if ($success): ?>
                <div class="alert alert-success mt-3 text-center">✔ Οι αλλαγές αποθηκεύτηκαν!</div>
            <?php endif; ?>
        </form>
    </div>
</div>

<script>
// Αυτόματη συμπλήρωση μονάδας
document.addEventListener("change", function(e){
    if(e.target.classList.contains("ingredient-select")){
        let row = e.target.closest(".ingredient-row");
        let opt = e.target.selectedOptions[0];
        row.querySelector(".unit-field").value = opt.getAttribute("data-unit-name") || "";
        row.querySelector("input[name='unit_id[]']").value = opt.getAttribute("data-unit-id") || "";
    }
});

// Προσθήκη νέας γραμμής
document.getElementById("add-ingredient").addEventListener("click", function(){
    let container = document.getElementById("ingredients-container");
    let first = container.querySelector(".ingredient-row");
    let clone = first.cloneNode(true);
    clone.querySelectorAll("input").forEach(i=>i.value="");
    clone.querySelectorAll("select").forEach(s=>s.selectedIndex=0);
    container.appendChild(clone);
});

// Διαγραφή γραμμής
document.addEventListener("click", function(e){
    if(e.target.classList.contains("delete-row")){
        e.target.closest(".ingredient-row").remove();
    }
});
</script>

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