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

// 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 pay_hold WHERE order_id = '$order_id'");
$row = mysqli_fetch_array($rec);

// Initialize variables to prevent undefined index warnings
$customer_name = "";
$phone_number = "";
$sale_by = "";
$paid_by = "";

// Check if customer details are available
if ($row) {
    $customer_name = isset($row["customer_name"]) ? $row["customer_name"] : "";
    $phone_number = isset($row["phone_number"]) ? $row["phone_number"] : "";
    $sale_by = isset($row["sale_by"]) ? $row["sale_by"] : "";
    $paid_by = isset($row["paid_by"]) ? $row["paid_by"] : "";
}

// Function to check if a product already exists in the table
function productExists($connection, $order_id, $product_id) {
    $query = "SELECT COUNT(*) as count FROM pay_hold WHERE order_id = '$order_id' AND product_id = '$product_id'";
    $result = mysqli_query($connection, $query);
    $data = mysqli_fetch_assoc($result);
    return $data['count'] > 0;
}

// Function to get product ID by name
function getProductIdByName($connection, $product_name) {
    $query = "SELECT id FROM products WHERE name = '$product_name'";
    $result = mysqli_query($connection, $query);
    $data = mysqli_fetch_assoc($result);
    return $data['id'];
}

function addOrUpdateProduct($connection, $order_id, $product_id, $product_name, $product_price, $product_quantity, $product_total) {
    // Escape all parameters to prevent SQL injection
    $order_id = mysqli_real_escape_string($connection, $order_id);
    $product_id = mysqli_real_escape_string($connection, $product_id);
    $product_name = mysqli_real_escape_string($connection, $product_name);
    $product_quantity = mysqli_real_escape_string($connection, $product_quantity);
    $product_total = mysqli_real_escape_string($connection, $product_total);

    // Check if product price is empty, if so, set it to NULL
    if ($product_price === '') {
        // Handle null product price
        $product_price = null;
    } else {
        // Handle non-null product price
        $product_price = "'" . mysqli_real_escape_string($connection, $product_price) . "'";
    }

    if (!empty($product_name) && is_numeric($product_price) && is_numeric($product_quantity)) {
        if (productExists($connection, $order_id, $product_id)) {
            // If product already exists, update quantity and price
            $query = "UPDATE pay_hold SET product_quantity = product_quantity + $product_quantity, product_price = $product_price, product_total = '$product_total' WHERE order_id = '$order_id' AND product_id = '$product_id'";
        } else {
            // If product doesn't exist, insert new record
            $query = "INSERT INTO pay_hold (order_id, product_id, product_name, product_price, product_quantity, product_total) VALUES ('$order_id', '$product_id', '$product_name', $product_price, '$product_quantity', '$product_total')";
        }
        mysqli_query($connection, $query);
    }
}

// Function to delete product from the table
function deleteProduct($connection, $order_id, $product_id) {
    mysqli_query($connection, "DELETE FROM pay_hold WHERE order_id = '$order_id' AND product_id = '$product_id'");
}

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    // Check if delete button is clicked
    if (isset($_POST["action"]) && $_POST["action"] == "delete_product") {
        $product_id = mysqli_real_escape_string($connection, $_POST["product_id"]);
        deleteProduct($connection, $order_id, $product_id);
    } else {
        // Get product details from the form
        $product_name = mysqli_real_escape_string($connection, $_POST["product_name"]);
        $product_price = mysqli_real_escape_string($connection, $_POST["product_price"]);
        $product_quantity = mysqli_real_escape_string($connection, $_POST["product_quantity"]);
        $product_total = floatval($product_price) * intval($product_quantity); // Calculate total price

        // Get product ID by name
        $product_id = getProductIdByName($connection, $product_name);

        // Add or update product
        addOrUpdateProduct($connection, $order_id, $product_id, $product_name, $product_price, $product_quantity, $product_total);
    }

    // Fetch customer details from the form if available
    $customer_name = isset($_POST["customer_name"]) ? mysqli_real_escape_string($connection, $_POST["customer_name"]) : "";
    $phone_number = isset($_POST["phone_number"]) ? mysqli_real_escape_string($connection, $_POST["phone_number"]) : "";
    $sale_by = isset($_POST["sale_by"]) ? mysqli_real_escape_string($connection, $_POST["sale_by"]) : "";
    $paid_by = isset($_POST["paid_by"]) ? mysqli_real_escape_string($connection, $_POST["paid_by"]) : "";

    // Calculate subtotal, tax, discount, and grand total
    $subtotal = calculateSubtotal($connection, $order_id);
    $tax = $subtotal * 0.1; // Assuming 10% tax
    $discount = isset($_POST["discount"]) ? floatval($_POST["discount"]) : 0; // Assuming discount is provided in the form
    $grandTotal = calculateGrandTotal($subtotal, $discount); // Calculate grand total after tax and discount

    // Insert customer details into cdetail table
    $customer_query = "INSERT INTO cdetail (order_id, customer_name, phone_number, sale_by, paid_by) VALUES ('$order_id', '$customer_name', '$phone_number', '$sale_by', '$paid_by')";
    mysqli_query($connection, $customer_query);

    // Insert product details and calculations into sales table
    $sales_query = "INSERT INTO sales (product_id,product_name, product_price, product_quantity, product_total, tax_amount, total_amount, order_id, date_time)
	 VALUES ('$product_id','$product_name','$product_price','$product_quantity', $subtotal, $tax, $grandTotal,'$order_id','NOW()')";
    mysqli_query($connection, $sales_query);
}

// Function to calculate grand total after discount
function calculateGrandTotal($subtotal, $discount) {
    // Calculate grand total after discount
    $grandTotal = $subtotal * 1.1; // Adding 10% tax
    $discountedTotal = $grandTotal - $discount; // Applying discount
    return $discountedTotal;
}

// Function to calculate subtotal based on product totals in the table
function calculateSubtotal($connection, $order_id) {
    $subtotal = 0;
    $rec3 = mysqli_query($connection, "SELECT * FROM pay_hold WHERE order_id = '$order_id'");
    while ($row3 = mysqli_fetch_array($rec3)) {
        $subtotal += $row3["product_total"];
    }
    return $subtotal;
}

// Calculate tax and grand total
$subTotal = calculateSubtotal($connection, $order_id);
$tax = $subTotal * 0.1;
$grandTotal = $subTotal + $tax;
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hold 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">
    
 
</head>
<style>
.bg-dark2{
    background:#8A1218;
	color:#fff;	
	}
/* Custom styles for sidebar */
    .sidebar {
    width: 100px;
    background-color: #8A1218;
    position: fixed;
    bottom: 0;
	top:60px;
    transition: transform 0.3s ease-in-out;
    transform: translateX(0);
    z-index: 1;
    height: 100%;
    border-radius: 0px;
}
    .sidebar.hide {
      transform: translateX(-100px); /* Move sidebar out of the viewport when it is hidden */
    }
    .sidebar .nav-item {
      padding: 21px 0;
      text-align: center;
      position: relative; /* Make the nav item container relative */
    }
    .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: #8A1218;
    }
    /* 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-color: #8A1218;
      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%);
    }
</style>
<body>

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

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

<div class="main-content">
    <form method="post" enctype="multipart/form-data">
        <br />
        <div class="container">
            <div class="row">
                <div class="col-sm-3">
                    <label class="btn-dark" style="padding:20px; border-radius:8px;">Order Hold ID =&nbsp;&nbsp;<?php echo isset($row["id"]) ? $row["id"] : ""; ?></label>
                </div>
                <div class="col-sm-5"></div>
                <div class="col-sm-4">
                    <label class="btn-dark" style="padding:20px; border-radius:8px;">Order-ID = <?php echo isset($order_id) ? $order_id : ""; ?></label>
                </div>
                <div class="col-sm-5">
                    <br />
                    <h4>Customer Detail</h4>
                    <table class="table table-bordered text-center">
                        <tr>
                            <td style="background:#8A1218; color:#fff;">Customer Name</td>
                            <td><?php echo isset($row["customer_name"]) ? $row["customer_name"] : ""; ?></td>
                        </tr>
                        <tr>
                            <td style="background:#8A1218; color:#fff;">Phone Number</td>
                            <td><?php echo isset($row["phone_number"]) ? $row["phone_number"] : ""; ?></td>
                        </tr>
                        <tr>
                            <td style="background:#8A1218; color:#fff;">Sale Close By</td>
                            <td><?php echo isset($row["sale_by"]) ? $row["sale_by"] : ""; ?></td>
                        </tr>
                        <tr>
                            <td style="background:#8A1218; color:#fff;">Paid Method</td>
                            <td><?php echo isset($row["paid_by"]) ? $row["paid_by"] : ""; ?></td>
                        </tr>
                    </table>
                </div>
                
               <div class="col-sm-7">
                    <br /><br /><br />
                    <h4>Add Product Manually</h4>
                    <div class="row">
                        <div class="form-group col-md-4">
                            <input type="text" class="form-control" id="product_name" name="product_name" placeholder="Product Name">
                        </div>
                        <div class="form-group col-md-4">
                            <input type="number" class="form-control" id="product_price" name="product_price" placeholder="Product Price">
                        </div>
                        <div class="form-group col-md-3">
                            <input type="number" class="form-control" id="product_quantity" name="product_quantity" placeholder="Qty">
                        </div>
                        <div class="form-group col-md-1">
                           <button type="submit" class="btn btn-dark">+</button>
                        </div>
                    </div>
                </div>



                <div class="col-sm-12">
                    <!-- Table to display sales details -->
                    <table id="product_table" class="table table-bordered text-center">
                        <tr style="background:#8A1218; color:#fff;">
                            <td>Pr.Name</td>
                            <td>Pr.Price</td>
                            <td>Pr.QTY</td>
                            <td>Pr.Total</td>
                            <td>Action</td>
                        </tr>
						 <?php
                        // Fetch sales details based on order ID
                        $rec3 = mysqli_query($connection, "SELECT * FROM pay_hold 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><?php echo $row3["product_quantity"]; ?></td>
                                <td class="product_total"><?php echo $row3["product_total"]; ?></td>
                                <td><button type="button" onclick="deleteProduct(this)" class="btn btn-dark" data-product-id="<?php echo $row3['product_id']; ?>"><i class="fa fa-trash"></i></button></td>
                            </tr>
                        <?php } ?>
                         
                    </table>
                    <div class="row">
                    <div class="col-sm-6">
                    <br><br><br><br>
                    <button type="submit" class="btn btn-dark" name="submit">Proceed to Sale</button></div>
                    <div class="col-sm-6">
                    <table class="table table-bordered">
                    <tr>
                    
                        <tr id="subtotal_row" >
                            <td colspan="1" class="bg-dark text-white" style="text-align:right;">Subtotal:</td>
                            <td style="background:#8A1218; color:#fff;" id="subtotal" colspan="1" >Rs: <?php echo $subTotal; ?></td>
                        </tr>
                        <tr id="tax_row">
                            <td colspan="1" class="bg-dark text-white" style="text-align:right;">Tax Amount (10%):</td>
                            <td style="background:#8A1218; color:#fff;"  id="tax" colspan="1">Rs: <?php echo $tax; ?></td>
                        </tr>
                        <td colspan="1" class="bg-dark text-white" style="text-align:right;">Discount:</td>
                     <td  style="background:#8A1218; color:#fff;" colspan="1" ><input type="number" class="" id="discount" name="discount" placeholder=" ADD Discount" oninput="calculateTotal()"></td></tr>
                        <tr id="grand_total_row">
                            <td colspan="1" class="bg-dark text-white" style="text-align:right;">Grand Total:</td>
                            <td style="background:#8A1218; color:#fff;"  id="grand_total" colspan="1">Rs: <?php echo $grandTotal; ?></td>
                        </tr>
                    </table>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
</body>
  <script>
    // Initialize an empty array to store the added products
    var addedProducts = [];

    function addProductManually() {
        var productName = document.getElementById("product_name").value;
        var productPrice = parseFloat(document.getElementById("product_price").value);
        var productQuantity = parseInt(document.getElementById("product_quantity").value);
        var productTotal = productPrice * productQuantity;

        // Create an object to represent the product
        var newProduct = {
            name: productName,
            price: productPrice,
            quantity: productQuantity,
            total: productTotal
        };

        // Add the product to the array
        addedProducts.push(newProduct);

        // Update the table and subtotal
        updateTableAndSubtotal();
    }

    function deleteProduct(row) {
        var rowIndex = row.parentNode.parentNode.rowIndex;
        // Remove the product from the array
        addedProducts.splice(rowIndex - 1, 1);
        // Update the table and subtotal
        updateTableAndSubtotal();
    }

function updateTableAndSubtotal() {
    var table = document.getElementById("product_table");
    var subtotal = 0;

    // Iterate over existing rows and calculate subtotal
    addedProducts.forEach(function(product) {
        var newRow = table.insertRow(-1);
        newRow.innerHTML = "<td class='text-capitalize'>" + product.name + "</td><td>" + product.price + "</td><td>" + product.quantity + "</td><td class='product_total'>" + product.total.toFixed(2) + "</td><td><button type='button' onclick='deleteProduct(this)' class='btn btn-dark'><i class='fa fa-trash'></i></button></td>";
        subtotal += product.total;
    });

    // Calculate tax (10%)
    var tax = subtotal * 0.1;
    var grandTotal = subtotal + tax; // Calculate grand total

    // Update the subtotal, tax, and grand total
    document.getElementById("subtotal").innerHTML = "Rs: " + subtotal.toFixed(2);
    document.getElementById("tax").innerHTML = "Rs: " + tax.toFixed(2);
    document.getElementById("grand_total").innerHTML = "Rs: " + grandTotal.toFixed(2);
}

function calculateTotal() {
    var subtotal = parseFloat(document.getElementById("subtotal").innerText.replace("Rs: ", ""));
    var tax = subtotal * 0.1;
    var discount = parseFloat(document.getElementById("discount").value);
    if (isNaN(discount)) {
        discount = 0;
    }
    var grandTotal = subtotal + tax - discount;

    document.getElementById("grand_total").innerText = "Rs: " + grandTotal.toFixed(2);
}
</script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></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>
</html>
