<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include "db.php";
include "header.php";

$show_success = false;

// ---------------- SAVE ----------------
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["save_all"])) {
    foreach ($_POST['product_id'] as $i => $id) {
        $id = (int)$id;
        $markup = (float)$_POST['markup'][$i];
        $margin = (float)$_POST['margin'][$i];
        $vat = (float)$_POST['vat'][$i];
        $catalog = isset($_POST['catalog'][$i]) ? 1 : 0;

        $stmt = $db->prepare("
            UPDATE products 
            SET markup=?, margin=?, vat=?, catalog=? 
            WHERE id=?
        ");
        $stmt->bind_param("dddii", $markup, $margin, $vat, $catalog, $id);
        $stmt->execute();
        $stmt->close();
    }

    $show_success = true;
}

// --------------- LOAD PRODUCTS ---------------
$result = $db->query("SELECT * FROM products ORDER BY name ASC");
?>

<!-- DataTables + Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">

<style>
.product-link {
    text-decoration: none;
    font-weight: bold;
    color: #0d6efd;
}
.product-link:hover {
    text-decoration: underline;
    color: #084298;
}

 body {
        min-height: 100vh;
        display: flex;
        margin: 0;
        background: #f9f9f9;
    }
    
</style>

<div class="container-fluid mt-5" style="padding-left: 220px; padding-right: 30px;">
    <h2><i class="bi bi-clipboard"></i> Τιμοκατάλογος Προϊόντων</h2>

    <form method="POST" action="">
    <table id="productsTable" class="table table-striped table-bordered mt-3 shadow-sm">
        <thead class="table-dark">
            <tr>
                <th>ID</th>
                <th>Κωδικός</th>
                <th>Όνομα</th>
                <th>Κόστος (€)</th>
                <th>Markup %</th>
                <th>Τιμή Markup</th>
                <th>Τιμή Markup + ΦΠΑ</th>
                <th>Margin %</th>
                <th>Τιμή Margin</th>
                <th>Τιμή Margin + ΦΠΑ</th>
                <th>ΦΠΑ %</th>
                <th>Κατάλογος</th>
            </tr>
        </thead>
        <tbody>
        <?php while ($row = $result->fetch_assoc()):

            // Υπολογισμός κόστους προϊόντος
            $stmt = $db->prepare("
                SELECT pi.quantity, COALESCE(ip.price,0) AS price
                FROM product_ingredients pi
                LEFT JOIN ingredient_prices ip ON ip.id = (
                    SELECT id FROM ingredient_prices 
                    WHERE ingredient_id = pi.ingredient_id 
                    ORDER BY date DESC LIMIT 1
                )
                WHERE pi.product_id = ?
            ");
            $stmt->bind_param("i", $row['id']);
            $stmt->execute();
            $res_cost = $stmt->get_result();

            $cost = 0;
            while($r = $res_cost->fetch_assoc()){
                $cost += $r['quantity'] * $r['price'];
            }
            $stmt->close();
        ?>
            <tr class="product-row">

                <td><?= $row['id'] ?></td>
                <td><?= htmlspecialchars($row['product_code']) ?></td>

                <td>
                    <a href="product_edit.php?id=<?= $row['id'] ?>" class="text-danger fw-bold">
                        <?= htmlspecialchars($row['name']) ?>
                    </a>
                </td>

                <td class="price-box cost"><?= number_format($cost, 2) ?></td>

                <td><input type="number" step="0.01" class="form-control markup" name="markup[]" value="<?= $row['markup'] ?>"></td>
                <td class="price-box markup_price_no_vat">0</td>
                <td class="price-box markup_price_vat">0</td>

                <td><input type="number" step="0.01" class="form-control margin" name="margin[]" value="<?= $row['margin'] ?>"></td>
                <td class="price-box margin_price_no_vat">0</td>
                <td class="price-box margin_price_vat">0</td>

                <td><input type="number" step="1" class="form-control vat" name="vat[]" value="<?= $row['vat'] ?>"></td>

                <td class="text-center">
                    <input type="checkbox" name="catalog[]" value="1" <?= $row['catalog'] ? 'checked' : '' ?>>
                </td>

                <input type="hidden" name="product_id[]" value="<?= $row['id'] ?>">
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>

    <div class="mt-3 d-flex gap-2">
        <button type="submit" name="save_all" class="btn btn-success"><i class="bi bi-check-circle"></i> Αποθήκευση</button>
        <a href="products_export.php" class="btn btn-warning"><i class="bi bi-arrow-down-circle"></i> Εξαγωγή σε Excel (μόνο προϊόντα Καταλόγου)</a>
    </div>

    <?php if($show_success): ?>
        <div id="saveAlert" class="alert alert-success mt-3 text-center">✔ Οι αλλαγές αποθηκεύτηκαν!</div>
        <script>
            setTimeout(function() {
                $("#saveAlert").fadeOut("slow");
            }, 3000);
        </script>
    <?php endif; ?>

    </form>
</div>

<!-- jQuery + DataTables JS + Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
$(document).ready(function() {
    $('#productsTable').DataTable({
        "paging": true,
        "searching": true,
        "ordering": true,
        "order": [[2, "asc"]],
        "language": { "url": "//cdn.datatables.net/plug-ins/1.13.6/i18n/el.json" }
    });

    function updateRow(row) {
        let cost = parseFloat(row.find(".cost").text().replace(',', '.')) || 0;
        let markup = parseFloat(row.find(".markup").val()) || 0;
        let margin = parseFloat(row.find(".margin").val()) || 0;
        let vat = parseFloat(row.find(".vat").val()) || 0;

        let markupPriceNoVAT = cost * (1 + markup/100);
        let markupPriceVAT = markupPriceNoVAT * (1 + vat/100);
        let marginPriceNoVAT = cost / (1 - margin/100);
        let marginPriceVAT = marginPriceNoVAT * (1 + vat/100);

        row.find(".markup_price_no_vat").text(markupPriceNoVAT.toFixed(2));
        row.find(".markup_price_vat").text(markupPriceVAT.toFixed(2));
        row.find(".margin_price_no_vat").text(marginPriceNoVAT.toFixed(2));
        row.find(".margin_price_vat").text(marginPriceVAT.toFixed(2));
    }

    $(".product-row").each(function() {
        let row = $(this);
        row.find("input[type='number']").on("input", function() {
            updateRow(row);
        });
        updateRow(row);
    });
});
</script>

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