<?php session_start();
include_once('includes/config.php');
include_once('includes/settings.php');
if (strlen($_SESSION['id']) == 0) {
    header('location:logout.php');
} else {
    if ($_SESSION['address'] == 0):
        echo "<script type='text/javascript'> document.location ='checkout.php'; </script>";
    endif;



    //Order details
    if (isset($_POST['submit'])) {
        $userid = $_SESSION['id'];

        // 1. Stock Validation
        $cartCheck = mysqli_query($con, "SELECT c.productId, c.productQty, p.stock_quantity, p.productName, p.vendor_id 
                                         FROM cart c 
                                         JOIN products p ON c.productId = p.id 
                                         WHERE c.userID='$userid'");
        $cartItems = [];
        while ($row = mysqli_fetch_assoc($cartCheck)) {
            if ($row['productQty'] > $row['stock_quantity']) {
                echo "<script>alert('Insufficient stock for " . addslashes($row['productName']) . " (Available: " . $row['stock_quantity'] . ")'); window.location='my-cart.php';</script>";
                exit();
            }
            $cartItems[] = $row;
        }

        $orderno = mt_rand(100000000, 999999999);
        $address = $_SESSION['address'];
        $totalamount = $_SESSION['gtotal'];
        $txntype = $_POST['paymenttype'];
        $txnno = $_POST['txnnumber'];

        $query = mysqli_query($con, "insert into orders(orderNumber,userId,addressId,totalAmount,txnType,txnNumber) values('$orderno','$userid','$address','$totalamount','$txntype','$txnno')");

        if ($query) {
            // 2. Decrement Stock & Log Inventory
            foreach ($cartItems as $item) {
                $pid = $item['productId'];
                $qty = $item['productQty'];
                $vid = $item['vendor_id'];
                $newStock = $item['stock_quantity'] - $qty;

                // Update Product Stock
                mysqli_query($con, "UPDATE products SET stock_quantity='$newStock' WHERE id='$pid'");

                // Log Inventory Change
                mysqli_query($con, "INSERT INTO inventory_logs (product_id, vendor_id, adjustment, previous_stock, current_stock, reason, reference_id, created_by) 
                                    VALUES ('$pid', '$vid', '-$qty', '{$item['stock_quantity']}', '$newStock', 'Order Placed', '$orderno', '$userid')");
            }

            $sql = "insert into ordersdetails (userId,productId,quantity) select userID,productId,productQty from cart where userID='$userid';";
            $sql .= "update ordersdetails set orderNumber='$orderno' where userId='$userid' and orderNumber is null;";
            $sql .= "delete from  cart where userID='$userid'";
            $result = mysqli_multi_query($con, $sql);

            if ($result) {
                unset($_SESSION['address']);
                unset($_SESSION['gtotal']);
                echo '<script>alert("Your order successfully placed. Order number is "+"' . $orderno . '")</script>';
                echo "<script type='text/javascript'> document.location ='my-orders.php'; </script>";
            }
        } else {
            echo "<script>alert('Something went wrong. Please try again');</script>";
            echo "<script type='text/javascript'> document.location ='payment.php'; </script>";
        }
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <?php include('includes/head.php'); ?>
    <style type="text/css"></style>

    <body class="cnt-home">
        <header class="header-style-1">
            <?php include('includes/top-header.php'); ?>
            <?php include('includes/main-header.php'); ?>
            <?php include('includes/menu-bar.php'); ?>
        </header>

        <!-- Breadcrumb -->
        <div class="breadcrumb mt-2">
            <div class="container">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item"><a href="checkout.php">Checkout</a></li>
                        <li class="breadcrumb-item active">Payment</li>
                    </ol>
                </nav>
            </div>
        </div>

        <!-- Main Content -->
        <div class="body-content outer-top-xs">
            <div class="container">
                <!-- Section-->
                <section class="py-5">
                    <div class="container px-4  mt-5">


                        <form method="post" name="signup">
                            <div class="row">
                                <div class="col-2">Total Payment</div>
                                <div class="col-6"><input type="text" name="totalamount"
                                        value="<?php echo $_SESSION['gtotal']; ?>" class="form-control" readonly></div>
                            </div>
                            <div class="row mt-3">
                                <div class="col-2">Payment Type</div>
                                <div class="col-6">

                                    <select class="form-control" name="paymenttype" id="paymenttype" required>
                                        <option value="">Select</option>
                                        <option value="e-Wallet">E-Wallet</option>
                                        <option value="Internet Banking">Internet Banking</option>
                                        <option value="Debit/Credit Card">Debit/Credit Card</option>
                                        <option value="Cash on Delivery">Cash on Delivery (COD)</option>
                                    </select>
                                </div>

                            </div>

                            <div class="row mt-3" id="txnno">
                                <div class="col-2">Transaction Number</div>
                                <div class="col-6"><input type="text" name="txnnumber" id="txnnumber" class="form-control"
                                        maxlength="50"></div>
                            </div>


                            <div class="row mt-3">
                                <div class="col-4">&nbsp;</div>
                                <div class="col-6"><input type="submit" name="submit" id="submit" class="btn btn-primary"
                                        required></div>
                            </div>
                        </form>

                    </div>


            </div>
        </div><!-- /.container -->
        </div><!-- /.body-content -->

        <!-- Footer -->
        <?php include('includes/footer.php'); ?>
        <?php include('includes/foot.php'); ?>
    </body>

    </html>
    <script type="text/javascript">

        //For report file
        $('#txnno').hide();
        $(document).ready(function () {
            $('#paymenttype').change(function () {
                if ($('#paymenttype').val() == 'Cash on Delivery') {
                    $('#txnno').hide();
                } else if ($('#paymenttype').val() == '') {
                    $('#txnno').hide();
                } else {
                    $('#txnno').show();
                    jQuery("#txnnumber").prop('required', true);
                }
            })
        }) 
    </script>
<?php } ?>
