<?php
require_once("models/res_menu.class.php");
require_once("models/res_order.class.php");
require_once("models/order-details.class.php");
require_once("models/res_table.class.php");

$menu = ResMenu::readAll();
$msg = "";
$items = "";

if (!empty($_POST['cart']) && $_POST['cart'] !== "[]") {
    $table_id = $_POST['table'];
    $special_req = $_POST['special_request'];
    $total = $_POST['total_amount'];
    $items = json_decode($_POST['cart']);

$orderObj = new ResOrders(null, null, $table_id, $total, $special_req, 1);
$msg = $orderObj->createOrder($items);

}
?>

<div class="mb-3" style="max-width: 200px;">
    <label for="sort-list" class="form-label fw-bold text-light">Filter Menu</label>
    <select name="sort-list" id="sort-list" class="form-select form-select-sm bg-dark text-light border-light">
        <option value="all">Show All</option>
        <option value="appetizers">Appetizers</option>
        <option value="pizzas">Pizzas</option>
        <option value="main-course">Main Courses</option>
        <option value="drinks">Drinks</option>
        <option value="desserts">Desserts</option>
    </select>

    <div><?php echo $msg ?></div>
</div>

<div class="row">
    <!-- Menu -->
    <div class="col-8">
        <div class="row">
            <?php foreach ($menu as $data) { ?>
                <div class="col-6 col-sm-6 col-md-3 col-lg-3 d-flex mb-4">
                    <div class="card w-100 shadow">
                        <img src="<?php echo $data["photos"]; ?>" class="card-img-top mt-2" alt="Menu Image">
                        <div class="card-body d-flex flex-column">
                            <p class="card-title text-dark small fw-bolder mb-0"><?php echo $data["name"]; ?></p>
                            <p class="card-text text-danger small mb-0">(<?php echo $data["category"]; ?>)</p>
                            <p class="card-text text-success small fw-bolder mb-0">৳ <?php echo $data["price"]; ?></p>
                            <div class="mt-auto">
                                <button type="button" data-id="<?php echo $data['id']; ?>"
                                        data-name="<?php echo $data['name']; ?>" data-price="<?php echo $data['price']; ?>"
                                        onclick="addToCart(this)" class="btn btn-dark btn-sm w-100">
                                    <i class="fas fa-cart-plus"></i> Add
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php } ?>
        </div>
    </div>

    <!-- Checkout -->
    <div class="col-4">
        <div class="card p-3">
            <h5 class="text-danger text-center mb-1">Selected Items</h5>
            <button type="button" class="btn btn-outline-danger btn-sm mb-3" onclick="clearCart()">Clear All Items</button>

            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Price & Qty</th>
                        <th>Sub-total</th>
                        <th class="px-0"></th>
                    </tr>
                </thead>
                <tbody id="cartItems"></tbody>
                <tfoot>
                    <tr>
                        <th colspan="2">Total</th>
                        <th id="cartTotal">0</th>
                        <th class="px-0"></th>
                    </tr>
                </tfoot>
            </table>

            <form method="post" class="mb-3">
                <label for="">Select Table</label>
                <?php $table = ResTable::readAll(); ?>
                <select name="table" class="form-control mb-3">
                    <option value="all" class="fw-bold">Select a table</option>
                    <?php foreach ($table as $data) { ?>
                        <option value="<?php echo $data["id"]; ?>"><?php echo $data["name"]; ?></option>
                    <?php } ?>
                </select>

                <label for="">Special Requests</label>
                <textarea name="special_request" class="form-control mb-3"></textarea>
                <input type="hidden" name="total_amount" value="0" id="cartTotalForm">
                <input type="hidden" name="cart" id="cartForm">
                <input type="submit" class="btn btn-primary w-100" value="Confirm Order">
            </form>
        </div>
    </div>
</div>

<script src="helper/cart-helper.js"></script>
<script>
var cartHelper = new CartHelper();

<?php if ($msg == "Data saved successfully") { ?>
    clearCart();
<?php } ?>

function addToCart(btn) {
    let id = btn.dataset.id;
    let name = btn.dataset.name;
    let price = btn.dataset.price;
    cartHelper.addItem(id, name, price, 1);
    printCart();
}

function clearCart() {
    cartHelper.emptyCart();
    printCart();
}

function addQty(id) {
    cartHelper.increaseQuantity(id);
    printCart();
}

function subQty(id) {
    cartHelper.decreaseQuantity(id);
    printCart();
}

function removeItem(id) {
    cartHelper.removeItem(id);
    printCart();
}

function printCart() {
    var items = cartHelper.getCart();
    var cartForm = document.getElementById('cartForm');
    if (cartForm) cartForm.value = JSON.stringify(items);

    var cartContainer = document.getElementById('cartItems');
    cartContainer.innerHTML = '';
    var total = document.getElementById('cartTotal');
    total.innerText = 0;
    var totalForm = document.getElementById('cartTotalForm');
    totalForm.value = 0;

    items.forEach(data => {
        cartContainer.innerHTML += `
            <tr> 
                <td>${data.name}</td>
                <td>
                    <div class="mb-1">${data.price} x ${data.quantity}</div>
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-dark btn-sm" onclick="subQty(${data.id})"><i class="fas fa-minus"></i></button>
                        <button type="button" class="btn btn-outline-dark btn-sm" onclick="addQty(${data.id})"><i class="fas fa-plus"></i></button>
                    </div>
                </td>
                <td>${data.price * data.quantity}</td>
                <th class="px-0">
                    <button type="button" class="btn btn-danger btn-sm" onclick="removeItem(${data.id})"><i class="fas fa-trash"></i></button>
                </th>
            </tr>
        `;
        var newTotal = parseInt(total.innerText) + data.price * data.quantity;
        total.innerText = newTotal;
        totalForm.value = newTotal;
    });
}

printCart();
</script>
