<main class="main-wrapper">
    <div class="main-content">
        <div class="row align-items-center">
            <div class="col-md-8 my-2">
                <!-- <h3 class="fmon mb-0">Order Details - #<?= $order['id'] ?></h3> -->
                <?php
                $orderShortId = explode('-', $order['id'])[0];
                ?>
                <h3 class="fmon mb-0">Order Details - #<?= $orderShortId ?></h3>

                <a href="<?= base_url('product/size/' . $order['id']) ?>" class="btn setBtn px-4">
                    <img src="./assets/images/size.png" alt="">view size
                </a>

                <p class="mb-0 text-muted">Order Date: <?= $order['orderDate'] ?> |
                    Status:
                    <select class="form-select status-select d-inline w-auto"
                        data-orderid="<?= $order['id'] ?>"
                        data-currentstatus="<?= $order['status'] ?>">
                        <option value="process" <?= $order['status'] == 'process' ? 'selected' : '' ?>>Processing</option>
                        <option value="processed" <?= $order['status'] == 'processed' ? 'selected' : '' ?> <?= empty($order['deliveryDate']) ? 'disabled' : '' ?>>Ready to deliver</option>
                        <option value="deliver" <?= $order['status'] == 'deliver' ? 'selected' : '' ?> <?= empty($order['deliveryDate']) ? 'disabled' : '' ?>>Delivered</option>
                    </select>
                </p>
            </div>

            <div class="col-md-4 my-2 d-flex justify-content-end gap-2">
                <p class="mb-0 align-self-center">Total: <?= $order['total'] ?></p>
                <button class="btn setBtn px-4" data-bs-toggle="modal" data-bs-target="#deliveryModal"
                    <?= in_array($order['status'], ['processed', 'deliver']) ? 'disabled' : '' ?>>
                    <?= empty($order['deliveryDate']) ? 'Set Delivery Date' : 'Update Delivery Date' ?>
                </button>

            </div>
        </div>

        <!-- Delivery Date Modal -->
        <div class="modal fade" id="deliveryModal" tabindex="-1" aria-labelledby="deliveryModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body">
                        <form id="deliveryDateForm" data-orderid="<?= $order['id'] ?>">
                            <p class="text-center fw-bold mb-3">
                                <?= empty($order['deliveryDate']) ? 'Set Delivery Date' : 'Update Delivery Date' ?>
                            </p>
                            <input type="date"
                                class="form-control fcn1"
                                name="delivery_date"
                                value="<?= !empty($order['deliveryDate']) ? date('Y-m-d', strtotime($order['deliveryDate'])) : '' ?>"
                                min="<?= date('Y-m-d') ?>"
                                required>
                            <button type="submit" class="btn setBtn px-5 d-block mx-auto my-2">
                                <?= empty($order['deliveryDate']) ? 'Set Date' : 'Update Date' ?>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="row my-2">
            <div class="col-md-12">
                <div class="orderCard table-responsive p-2">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Name</th>
                                <th>Quantity</th>
                                <!-- <th>Date</th> -->
                                <th>Price</th>
                                <th>Total Price</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $num = 1; ?>
                            <?php foreach ($order['products'] as $product): ?>
                                <?php print_r($product['date']);?>
                                <tr>
                                    <td><?= $num++; ?></td>
                                    <td>
                                        <img class="tableImag" src="<?= $product['image'] ?>" alt="<?= $product['name'] ?>"
                                            style="width: 40px; height: 40px; object-fit: cover">
                                        <?= $product['name'] ?>
                                    </td>
                                    <td><?= $product['quantity'] ?></td>
                                    <!-- <td><?= date('Y-m-d', strtotime($product['date'])) ?></td> -->
                           

                                    <!-- <td><?= $product['date'] ?></td> -->

                                    <td>AED <?= $product['price'] ?></td>
                                    <td><strong>AED <?= number_format($product['quantity'] * $product['price'], 2) ?></strong></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="row mt-4">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h5>Shipping Address</h5>
                                <p class="mb-0"><?= $order['address'] ?></p>
                                <?php if (!empty($order['deliveryDate'])): ?>
                                    <p class="mt-2 mb-0">Delivery Date: <?= $order['deliveryDate'] ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h5>Order Timeline</h5>
                                <ul class="list-unstyled">
                                    <?php foreach ($order['timeline'] as $event): ?>
                                        <li class="mb-2">
                                            <small class="text-muted"><?= $event['date'] ?></small><br>
                                            <?= $event['event'] ?>
                                        </li>
                                    <?php endforeach; ?>
                                    <!-- <?php if (!empty($order['deliveryDate'])): ?>
                                        <li class="mb-2">
                                        <small class="text-muted"><?= $order['deliveryDate'] ?></small><br>
                                        <br>
                                            Delivery Date Set
                                        </li>
                                    <?php endif; ?> -->
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>
<!--end main wrapper-->

<script>
    document.addEventListener('submit', function(e) {
        if (e.target && e.target.id === 'deliveryDateForm') {
            e.preventDefault();

            const formData = new FormData(e.target);
            const orderId = e.target.dataset.orderid;

            document.querySelector('.loader-overlay').style.display = 'block';

            fetch(`<?= base_url('product/setDeliveryDate/') ?>${orderId}`, {
                    method: 'POST',
                    body: formData
                })
                .then(async response => {
                    const data = await response.json();
                    document.querySelector('.loader-overlay').style.display = 'none';

                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: 'Delivery date updated successfully',
                            confirmButtonColor: '#FFD700'
                        }).then(() => location.reload());
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error!',
                            text: data.message || 'Failed to update delivery date',
                            confirmButtonColor: '#FFD700'
                        });
                    }
                })
                .catch(error => {
                    document.querySelector('.loader-overlay').style.display = 'none';
                    console.error('Error:', error);
                });
        }
    });

    document.addEventListener("DOMContentLoaded", function() {
        document.querySelectorAll(".status-select").forEach(select => {
            const currentStatus = select.getAttribute("data-currentstatus");

            select.querySelectorAll("option").forEach(option => {
                if (currentStatus === "process" && option.value === "process") {
                    option.style.display = "none";
                } else if (currentStatus === "processed") {
                    if (option.value === "process" || option.value === "processed") {
                        option.style.display = "none";
                    }
                } else if (currentStatus === "deliver") {
                    if (option.value === "process" || option.value === "processed") {
                        option.style.display = "none";
                    }
                }
            });

            // Alert on attempt to select a hidden option
            select.addEventListener("mousedown", function(e) {
                const hiddenOption = Array.from(select.options).find(opt =>
                    opt.style.display === "none" && opt === e.target
                );
                if (hiddenOption) {
                    Swal.fire({
                        icon: "error",
                        title: "Invalid Selection",
                        text: "You cannot select a previous status",
                        confirmButtonColor: "#FFD700"
                    });
                    e.preventDefault();
                }
            });
        });
    });

    document.addEventListener("change", function(e) {
        if (e.target && e.target.classList.contains("status-select")) {
            const newStatus = e.target.value;
            const orderId = e.target.dataset.orderid;
            const currentStatus = e.target.getAttribute("data-currentstatus");
            const deliveryDate = "<?= $order['deliveryDate'] ?>";

            if ((newStatus === "processed" || newStatus === "deliver") && !deliveryDate) {
                Swal.fire({
                    icon: "warning",
                    title: "Enter Delivery Date!",
                    text: "Please enter a delivery date before proceeding.",
                    confirmButtonColor: "#FFD700"
                }).then(() => {
                    document.querySelector("#deliveryModal").classList.add("show");
                    document.querySelector("#deliveryModal").style.display = "block";
                });
                e.target.value = currentStatus;
                return;
            }

            Swal.fire({
                title: "Confirm Status Change",
                html: `You are changing order status from <b>${currentStatus}</b> to <b>${newStatus}</b>`,
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#FFD700",
                cancelButtonColor: "#d33",
                confirmButtonText: "Confirm Change"
            }).then((result) => {
                if (result.isConfirmed) {
                    document.querySelector(".loader-overlay").style.display = "block";
                    e.target.disabled = true;

                    fetch(`<?= base_url('product/updateOrderStatus/') ?>${orderId}`, {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/json"
                            },
                            body: JSON.stringify({
                                status: newStatus
                            })
                        })
                        .then(async (response) => {
                            const data = await response.json();
                            document.querySelector(".loader-overlay").style.display = "none";
                            e.target.disabled = false;

                            if (data.success) {
                                Swal.fire({
                                    icon: "success",
                                    title: "Status Updated!",
                                    html: `Order status changed to <b>${newStatus}</b>`,
                                    confirmButtonColor: "#FFD700"
                                }).then(() => location.reload());
                            } else {
                                e.target.value = currentStatus;
                                Swal.fire({
                                    icon: "error",
                                    title: "Update Failed",
                                    text: data.message || "Could not update status",
                                    confirmButtonColor: "#FFD700"
                                });
                            }
                        })
                        .catch((error) => {
                            console.error("Fetch Error:", error);
                            Swal.fire({
                                icon: "error",
                                title: "Network Error",
                                text: "Please check your internet connection",
                                confirmButtonColor: "#FFD700"
                            });
                        });
                } else {
                    e.target.value = currentStatus;
                }
            });
        }
    });
</script>