<?php
include('db/cn.php');

if(isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name'])
 && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
	$outlet_address = $_SESSION['outlet_address'];
	$outlet_name = $_SESSION['outlet_name'];

        // Display the user's name and role

// Check if order_id is provided via GET request
if (!isset($_GET["order_id"])) {
    // Redirect or handle error
    exit("Order ID is missing.");
}

$order_id = mysqli_real_escape_string($connection, $_GET["order_id"]);

// Fetch data from sales table
$rec = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id = '$order_id'");
$row = mysqli_fetch_array($rec);

// Fetch data from cdetail table
$rec2 = mysqli_query($connection, "SELECT * FROM cdetail WHERE order_id = '$order_id'");
$row2 = mysqli_fetch_array($rec2);

$sumQuery = "SELECT SUM(product_total) AS total_cash_amount FROM log_user_sales WHERE order_id = '$order_id'";

// Execute the query
$result = $connection->query($sumQuery);

// Check if the query was successful
if ($result) {
    // Fetch the result as an associative array
    $row4 = $result->fetch_assoc();

    // Extract the sum of cash_amount and change_amount
    $totalCashAmount = $row4['total_cash_amount'];
}
// Handle form submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    foreach ($_POST as $key => $value) {
        // Check if the key starts with "refund_qty_"
        if (strpos($key, 'refund_qty_') === 0) {
            $product_id = substr($key, strlen('refund_qty_')); // Extract product ID
            $refund_quantity = mysqli_real_escape_string($connection, $value); // Escape input for SQL

            if ($refund_quantity > 0) {
                // Fetch the details of the product being refunded
                $product_query = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id = '$order_id' ");
                $product_row = mysqli_fetch_array($product_query);

                // Check if the customer name is null and provide a default value if it is
                $customer_name = isset($row2["customer_name"]) ? $row2["customer_name"] : "Unknown";

                // Calculate updated values
                $updated_product_total = $product_row["product_price"] * $refund_quantity;
                $updated_tax_amount = $updated_product_total * 0.10; // Assuming tax_amount is 10% of the product total
                $updated_total_amount = $updated_product_total + $updated_tax_amount;

                $insert_query = "INSERT INTO order_detail(order_id, customer_name, phone_number, sale_by, paid_by, product_id, product_name, product_price, product_quantity, product_total, tax_amount, total_amount, date_time, order_status, outlet_name, user_role, outlet_address)
                                 VALUES ('$order_id', '$customer_name', '".$row2["phone_number"]."', '".$row2["sale_by"]."', '".$row2["paid_by"]."', '$product_id', '".$product_row["product_name"]."', '".$product_row["product_price"]."', '$refund_quantity', '$updated_product_total', '$updated_tax_amount', '$updated_total_amount', '".$product_row["date_time"]."', 'Refund', '$outlet_name', '$userRole', '$outlet_address')";
                if (!mysqli_query($connection, $insert_query)) {
                    // Handle error if insertion fails
                    exit("Error inserting data into order_detail table: " . mysqli_error($connection));
                }

                // Update product quantity in products table
                if (!mysqli_query($connection, "UPDATE products SET stock_qty = stock_qty + '$refund_quantity' WHERE id = '$product_id'")) {
                    // Handle error if update fails
                    exit("Error updating product quantity: " . mysqli_error($connection));
                }
            }
        }
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Detail</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="css/custom_css.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<style>
@media (max-width: 880px) {
    .col-4 {
        width: 33.33% !important;
    }
    .fa-wifi {
        display: none !important;
    }
    .col-6 {
        width: 50% !important;
    }
}

 #table-container-refund {
    max-height: 580px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
/* Custom styles for sidebar */    /* Custom styles for sidebar */
    .sidebar {
        width: 100px;
        background: linear-gradient(360deg, #060606, #0A5064);
        position: fixed;
        bottom: 0;
        top: 60px;
        transition: transform 0.3s ease-in-out;
        transform: translateX(0);
        z-index: 1;
        height: 100%;
        border-radius: 0px;
		   transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;
    }.sidebar.hide {
      transform: translateX(-100px); /* Move sidebar out of the viewport when it is hidden */
    }
      .sidebar .nav-item {
    padding: 10px 0 ;
    text-align: center;
    position: relative;
	font-size:12px;
}
    .sidebar .nav-link {
      color: #fff;
      position: relative; /* Ensure icon and text are positioned relative to the nav link */
      z-index: 2; /* Ensure the text and icon are above the hover background */
    }
    .sidebar .nav-link i {
      margin-bottom: 5px; /* Adjust the margin of the icon */
    }
    /* Custom styles for hover effect */
    .sidebar .nav-item:hover:after {
      background-color: #fff;
      content: '';
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 100%;
      z-index: 1; /* Ensure the hover background is below the text and icon */
    }
    .sidebar .nav-item:hover .nav-link {
      color: #0A5064;
    }
    /* Custom styles for divider */
    .sidebar .nav-item:after {
      content: "";
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 1px;
      background-color: #fff;
      transition: height 0.3s ease-in-out; /* Transition effect for smooth animation */
    }
    /* Custom styles for header */    .header {
        background: linear-gradient(270deg, #060606, #0A5064);
        color: #fff;
        padding: 10px;
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 2;
        height: 69px;
        box-shadow: #FFF 2px 0px 0px 0px;
        /* Ensure header appears above sidebar */
    }
    .header .navbar-toggler {
      color: #fff;
    }
    .header .navbar-toggler-icon {
      color: #fff; /* Set the color of the toggle button to white */
    }
    .header .navbar-toggler.white {
      color: #fff !important; /* Ensure the toggle button is white */
    }
    .header .navbar-brand {
      color: #fff; /* Set navbar brand text color to white */
    }
    .header .nav-item .nav-link {
      color: #fff; /* Set nav link text color to white */
    }
    .main-content {
      margin-top: 50px; /* Height of fixed header + padding */
      margin-left: 100px; /* Width of sidebar */
      padding-top: 30px; /* Height of fixed header */
    }
	/* Custom styles for search bar */
    .search-container {
      display: flex;
      align-items: center;
      width: 300px;
      margin: 2px auto;
    }
    .search-input {
      width: 100%;
      padding: 10px 30px 10px 10px; /* Adjust padding to accommodate the icon */
      border: 1px solid #ccc;
      border-radius: 20px;
      font-size: 16px;
    }
    .search-icon {
      position: relative;
      left: -25px; /* Adjust the position of the icon */
      color: #aaa;
    }
    .search-icon i {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
.btn-dark
         {
			 background:#0A5064;
			 color:#fff;
			 border: 1px solid #0A5064;
                 	}
		.btn-dark:hover{
			background:#fff;
			 color:#0A5064;
			 border:1px solid #0A5064;
			}	
			.bg-dark2{
			background:#8A1218;
			color:#fff;	
				}	
	
	 .modal-content {
            animation: modal-animation 0.5s;
        }

        @keyframes modal-animation {
            from {
                opacity: 0;
                transform: scale(0.8);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }
		
</style>
<body>

<?php include("common/hd.php");?>

<?php include("common/sd.php"); ?>

<div class="main-content">
    <form method="post" action="">
        <br />
        <div class="container">
            <div class="row">
                <br>
                <div class="col-sm-7" >
                    <label class=" text-dark" style="width:200px;text-align:center;padding:10px; border-radius:8px; border:1px solid #000; font-size:22px;">
                        Sale ID =&nbsp;&nbsp;<?php echo isset($row["id"]) ? $row["id"] : ""; ?>
                    </label>
                    <br><br>
                    <div id="table-container-refund">
                        <center>
                            <table class="table table-stripped text-center table-hover">
                                <tr style="font-weight:700;">
                                    
                                    <td>Name</td>
                                    <td>Price</td>
                                    <td>Qty</td>
                                    <td>Refund Qty</td>
                                    <td>Action</td>
                                </tr>
                                <?php
                                // Fetch sales details based on order ID
                                $rec3 = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id = '$order_id'");
                                while ($row3 = mysqli_fetch_array($rec3)) { ?>
                                    <tr>
                                        
                                        <td class="text-capitalize"><?php echo $row3["product_name"]; ?></td>
                                        <td><?php echo $row3["product_price"]; ?></td>
                                        <td><span style="width:50px; height:10px; background:#8A1218;color:#fff;padding:5px; border-radius:20px;">
                                                <?php echo $row3["product_quantity"]; ?></span></td>
                                        <td>
                                            <input type="number" class="" name="refund_qty_<?php echo $row3['product_id']; ?>" min="0"
                                                   max="<?php echo $row3['product_quantity']; ?>" value="0" style="width:50px;">
                                        </td>
                                        <td>
                                            <button type="submit" name="refund_<?php echo $row3['product_id']; ?>" class="btn btn-dark btn-sm"><i class="fa fa-cash-register"></i></button>
                                        </td>
                                    </tr>
                                <?php } ?>
                            </table>
                        </center>
                    </div>
                </div>
                <div class="col-sm-1"></div>
                <div class="col-sm-4 text-center" >
                    <span style="font-size:22px;">Order ID#</span>
                    <span class="text-dark" style="font-size:22px; text-align:center;border:1px solid #353535;padding:10px; border-radius:8px;">
                        <?php echo isset($order_id) ? $order_id : ""; ?>
                    </span> <?php 
                                $rec4 = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id = '$order_id'");
                                $row4 = mysqli_fetch_array($rec4); ?>
                    <br><br>
                    <i class=" fa fa-calendar-check " style="color:#8A1218;font-size:20px;margin-top:10px;"></i>
                    &nbsp; <span class="" style="text-align:center; margin-top:10px;"><?php echo $row["date_time"]; ?></span>
                    <div>
                        <div style="padding:20px; margin-top:10px;">
                            <h4>Customer Detail</h4>
                            <table class="table table-striped text-center" >
                                <tr>
                                    <td style="text-align:left;">Name:</td>
                                    <td><?php echo isset($row4["customer_name"]) ? $row4["customer_name"] : ""; ?></td>
                                </tr>
                                <tr>
                                    <td style="text-align:left;" >Cell#:</td>
                                    <td><?php echo isset($row4["customer_phone"]) ? $row4["customer_phone"] : ""; ?></td>
                                </tr>
                                <tr>
                                    <td style="text-align:left;" >Cashier:</td>
                                    <td>Hassan</td>
                                </tr>
                                <tr>
                                    <td  style="text-align:left;" >Payment Method:</td>
                                    <td class="text-capitalize"><?php echo isset($row4["paid_by"]) ? $row4["paid_by"] : ""; ?></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    <center>
                        <div class="" style="width:350px;border-radius:10px;border:1px solid #ccc;box-shadow:0px 2px 0px 1px #F6EEEE; padding:10px;margin-top:20px; ">
                            <table class="table text-dark" style="width:300px; padding:30px; font-weight:700; ">
                                <tr>
                                    <td>Sub - </td>
                                    <td><?php echo "Rs ".$totalCashAmount.".00"; ?></td>
                                </tr>
                                <tr>
                                    <td>Tax  - </td>
                                    <td> <?php echo  "Rs ".$row["tax_amount"].".00"; ?></td>
                                </tr>
                                <tr>
                                    <td>Total  - </td>
                                    <td><?php echo  "Rs ".$row["total_amount"].".00"; ?></td>
                                </tr>
                            </table>
                        </div>
                    </center>
                    <a href="orders_detail_v.php">
                        <button type="button" class="btn btn-dark form-control" style="border-radius:20px;margin-top:20px;">Submit</button>
                    </a>
                </div>
            </div>
        </div>
    </form>
</div>

<!-- Include necessary scripts -->
<script>
document.addEventListener("DOMContentLoaded", function () {
    var sidebar = document.getElementById("sidebar");
    var overlay = document.createElement("div");
    overlay.classList.add("overlay");
    document.body.appendChild(overlay);

    function toggleSidebar() {
        sidebar.classList.toggle("hide");
        overlay.classList.toggle("hide");

        var mainContent = document.querySelector(".main-content");
        if (sidebar.classList.contains("hide")) {
            mainContent.style.marginLeft = "0";
        } else {
            mainContent.style.marginLeft = "100px"; // Width of the sidebar
        }
    }

    overlay.addEventListener("click", function () {
        toggleSidebar();
    });

    // Add toggle functionality to navbar toggler
    var navbarToggler = document.querySelector(".navbar-toggler");
    navbarToggler.addEventListener("click", function () {
        toggleSidebar();
    });

    // Automatically hide sidebar on all screen sizes
    // sidebar.classList.add("hide");
    // overlay.classList.add("hide");
    
    // Add class to body to prevent scrolling when sidebar is open
    // document.body.classList.add("noscroll");

    // Check if screen size is larger than a certain threshold (e.g., 768px for desktop screens)
    function checkScreenSize() {
        if (window.innerWidth > 768) {
            sidebar.classList.remove("hide");
            overlay.classList.remove("hide");
        } else {
            sidebar.classList.add("hide");
            overlay.classList.add("hide");
        }
    }

    // Check screen size on initial load and whenever the window is resized
    checkScreenSize();
    window.addEventListener("resize", checkScreenSize);
});
 
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</body>
</html>
<?php  } ?>