<?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 the form is submitted for deletion
if(isset($_POST["delete_id"])) {
    $delete_id = mysqli_real_escape_string($connection, $_POST["delete_id"]);
    
    // Delete the row from the pay_hold table
    $delete_query = "DELETE FROM pay_hold WHERE id = '$delete_id'";
    if(mysqli_query($connection, $delete_query)) {
        echo '<script>alert("Row deleted successfully.");</script>';
    } else {
        echo '<script>alert("Failed to delete row.");</script>';
    }
}

$order_id = mysqli_real_escape_string($connection, $_GET["order_id"]); // Assuming you're passing order_id through GET method

// Fetching product_id from pay_hold table
$rec = mysqli_query($connection,"SELECT * FROM pay_hold WHERE order_id = '$order_id'");
$row12 = mysqli_fetch_array($rec);
$product_id = $row12["product_id"];

// Query to fetch data
$query1 = "SELECT * FROM pay_hold WHERE order_id = '$order_id'";
$result1 = mysqli_query($connection, $query1);

// Calculate total cash amount
$sumQuery = "SELECT SUM(product_total) AS total_cash_amount FROM pay_hold WHERE order_id = '$order_id'";
$result2 = $connection->query($sumQuery);

// Initialize variables for tax, total amount, discount, change amount, and cash amount
$tax = 0;
$finalAmount = 0;
$discount = 0;
$changeAmount = 0;
$cashAmount = 0;

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

    // Extract the sum of cash_amount and change_amount
    $totalCashAmount = $row4['total_cash_amount'];
    // Calculate tax amount (assuming tax is 10%)
    $tax = $totalCashAmount * 0.00;
    // Calculate final amount
    $finalAmount = $totalCashAmount + $tax;
}

// Check if the form is submitted for generating invoice
if(isset($_POST["generate_invoice"])) {
    // Begin a transaction
    mysqli_begin_transaction($connection);

    // Variable to track insertion status
    $success = true;

    // Iterate through each product
    while ($row = mysqli_fetch_assoc($result1)) {
        // Gather necessary data including cash amount and change amount for each product
        $salesData = array(
            'product_id' => $row['product_id'],
            'product_name' => $row['product_name'],
            'product_price' => $row['product_price'],
            'product_quantity' => $row['product_quantity'],
            'product_total' => $row['product_total'],
            'tax_amount' => $tax,
            'total_amount' => $finalAmount,
			'paid_by' => $row['paid_by'],
			'customer_name' => $row12['customer_name'],
			'customer_phone' => $row12['phone_number'],
            'discount_amount' => isset($row12['discount_amount']) ? $row12['discount_amount'] : 0,
            'change_amount' => isset($_POST['change_amount']) ? $_POST['change_amount'] : 0,
            'cash_amount' => isset($_POST['cash_amount']) ? $_POST['cash_amount'] : 0,
            'order_id' => $order_id,
			'outlet_name' => $outlet_name,
			'login_user' => $userName,
			'user_role' => $userRole,
			'outlet_address' => $outlet_address,
            'date_time' => date("Y-m-d")
        );

        // Prepare and execute INSERT query for each product
        $salesColumns = implode(", ", array_keys($salesData));
        $salesValues = "'" . implode("', '", $salesData) . "'";
        $insertQuery = "INSERT INTO log_user_sales ($salesColumns) VALUES ($salesValues)";

        if(!mysqli_query($connection, $insertQuery)) {
            $success = false; // If any insertion fails, set success to false
            break; // Exit the loop
        }
    }

    if ($success) {
        // If all insertions are successful, commit the transaction
        mysqli_commit($connection);

        // Delete product data from pay_hold table
        $delete_product_query = "DELETE FROM pay_hold WHERE order_id = '$order_id'";
        if(mysqli_query($connection, $delete_product_query)) {
            echo '<script>alert("Invoice generated successfully and product data deleted from pay_hold.");</script>';
            echo '<script>window.location.href = "orders_detail_v.php";</script>'; // Redirect to orders_detail_v.php
            exit; // Stop further execution
        } else {
            echo '<script>alert("Failed to delete product data from pay_hold.");</script>';
        }
    } else {
        // If any insertion fails, roll back the transaction
        mysqli_rollback($connection);
        echo '<script>alert("Failed to generate invoice.");</script>';
    }
}
?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POS Data</title>
    <!-- Bootstrap CSS -->
    <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">
    
   <style>
    #table-container-wrapper {
    max-height: 300px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
@media (max-width: 880px) {
    .col-4 {
        width: 33.33% !important;
    }
    .fa-wifi {
        display: none !important;
    }
    .col-6 {
        width: 50% !important;
    }
}
/* 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:#212529;
			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);
            }
        }
        .calculator-box {
            background-color: #f0f0f0;
            padding: 20px;
            border-radius: 5px;
			width:100%;
			
        }

        .calculator {
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 10px;
        }

        .output {
            background-color: #eee;
            padding: 26px;
            margin-bottom: 10px;
			font-size:44px;
			font-weight:700;
			text-align:right;
		     
        }

        .buttons {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            grid-gap: 5px;
        }

        .buttons button {
            padding: 32px;
            font-size: 20px;
            border: none;
            cursor: pointer;
            background-color: #0A5064;
			color:#353535;
        }
		

        .buttons button:hover {
            background-color: #353535;
			color:#fff;
        }
		
		
			
			
    </style>
</head>
<body>
<?php include("common/hd.php"); ?>
<?php include("common/sd.php"); ?>
<br><br>
<form id="myForm" action="submit_hold.php?order_id=<?php echo $order_id; ?>" method="post" enctype="multipart/form-data">
<div class="main-content">


<div class="container">
<div class="row">

<div class="col-sm-6">

            <br>
<!--<h4>Customer Detail</h4>
<table class="table table-bordered text-center">
<tr>
<td class=" text-white" style="background:#8A1218;">Customer Name</td>
<td><?php  echo $customer;?><td>
</tr>

<tr>
<td class=" text-white" style="background:#8A1218;">Customer Phone</td>
<td><?php  echo $phone;?></td>
</tr>

<tr>
<td class=" text-white" style="background:#8A1218;"> Sale By :</td>
<td><?php  echo $saleBy;?></td>
</tr>

<tr>
<td class=" text-white" style="background:#8A1218;">Paid Method By </td>
<td><?php  echo $paidBy;?></td>
</tr>





</tr>
</table>-->
<div id="table-container-wrapper">
<table  class="table table-striped" style="margin-top:20px;border:1px solid #F2E6E6;box-shadow:0px 2px 0px 1px #F6EEEE; border-radius:8px;">
        <thead>
            <tr class="bg-dark2 text-white text-center text-capitalize" style="border-radius:8px;" >
               
                <th>Product </th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Amount</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
           <?php
            // Loop through each row of the result set
            while ($row = mysqli_fetch_assoc($result1)) {
                // Display product details in table rows and cells
                echo "<tr class='text-center text-capitalize' >";
                echo "<td>" . $row['product_name'] . "</td>"; // Assuming product_name is the column name
                echo "<td>" . $row['product_price'] . "</td>"; // Assuming price is the column name
                echo "<td>" . $row['product_quantity'] . "</td>"; // Assuming quantity is the column name
                echo "<td>" . $row['product_total'] . "</td>"; // Assuming amount is the column name
				echo "<td ><button type='submit' class='btn btn-dark btn-sm fa fa-trash' style='border-radius:20px; font-size:12px;' name='delete_id' value='" . $row['id'] . "'></button></td>";
                echo "</tr>";
				
            }
            ?>
        </tbody>
    </table>
</div>

<br><br>
<div class="">
            
                <table class="table table-borderless text-left text-small"
                 style="margin-top:20px;border:1px solid #F2E6E6;box-shadow:0px 2px 0px 1px #F6EEEE; border-radius:8px; padding:20px;">
               <tr> 
             
                <td style="font-size:14px;"><p><strong>Sub Total:</strong></p></td>
                <td  >Rs&nbsp;<?php echo $totalCashAmount;?>.00</td>
                </tr>
                <tr>
                <td style="font-size:14px;"><p><strong>Tax:</strong></p></td>
                <td  > Rs&nbsp;<?php echo $tax ;  ?>.00</td>
                </tr>
                <tr>
                <td style="font-size:14px;">
                <p><strong>Discount:</strong></p></td>
                <td  > Rs&nbsp;<?php echo $row12["discount_amount"]; ?></td></tr>
                <tr><td style="font-size:14px;">
                <p><strong>Total Amount:</strong></p></td>
                <td  >Rs&nbsp;<?php echo $finalAmount; ?>.00</td></tr>
                <tr><td>
                </td></tr>
               
               
               </table>
      
           
               <br>
               <button type="submit" class="btn btn-dark"  name="generate_invoice">Conform Payment / Generate-invoice</button>
               
               </div>
</div>
<div class="col-sm-6">

<div >

    <div class="row text-center" 
    style="margin-top:20px;border:1px solid #F2E6E6;box-shadow:0px 2px 0px 1px #F6EEEE; border-radius:8px; padding:20px;">
                <div class="col-sm-6">
                <p><strong>Payable(incl. TAX):</strong></p></div>
                <div class="col-sm-6" style="font-size:21px; font-weight:700;"> <?php echo'Rs&nbsp;'.$finalAmount.'.00'; ?></div>
                <div class="col-sm-12 bg-dark2" style="border-radius:12px;">
                <p class="text-center" id="remaining-change"  style="font-weight:700; font-size:22px; margin-bottom:5px;"></p>
                </div>
    </div>

</div>

<br><br><br><br>
<div class="calculator-box " >
                    <h2></h2>
                    <div class="calculator">
                        <div class="output">
                            <span id="output"></span>
                        </div>
                        <div class="buttons">
                            <button type="button" onclick="appendNumber('7')">7</button>
                            <button type="button" onclick="appendNumber('8')">8</button>
                            <button type="button" onclick="appendNumber('9')">9</button>
                            <button type="button" onclick="appendNumber('4')">4</button>
                            <button type="button" onclick="appendNumber('5')">5</button>
                            <button type="button" onclick="appendNumber('6')">6</button>
                            <button type="button" onclick="appendNumber('1')">1</button>
                            <button type="button" onclick="appendNumber('2')">2</button>
                            <button type="button" onclick="appendNumber('3')">3</button>
                            <button type="button" onclick="appendNumber('0')">0</button>
                            <button type="button" onclick="clearOutput()">C</button>
                            <button type="button" onclick="calculate()">Calculate</button>
                            
                            
                        </div>
                    </div>
                </div>
              
</div>
</div>
</div>

    <input type="hidden" id="cash_amount" name="cash_amount" value="">
<input type="hidden" id="change_amount" name="change_amount" value="">


    <div class="container">
        <div class="row">
        
            
            <div class="col-sm-6">
            
           
            
                

                
            </div>
        </div>
    </div>
    

 </div>   
	    </form>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  <script>
    // Function to append numbers to the calculator output
    function appendNumber(number) {
        document.getElementById('output').innerText += number;
    }

    // Function to clear the calculator output
    function clearOutput() {
        document.getElementById('output').innerText = '';
    }

    // Function to calculate change amount and submit the form
    function calculate() {
        var enteredAmount = parseFloat(document.getElementById('output').innerText);
        var finalAmount = <?php echo $finalAmount; ?>;

        if (!isNaN(enteredAmount)) {
            if (enteredAmount >= finalAmount) {
                var remainingChange = enteredAmount - finalAmount;
                document.getElementById('remaining-change').innerText = 'Remaining Change: Rs ' + remainingChange.toFixed(2);
                // Set cash_amount and change_amount directly in the form
                document.getElementById('cash_amount').value = enteredAmount.toFixed(2);
                document.getElementById('change_amount').value = remainingChange.toFixed(2);
                // Submit the form
                
            } else {
                alert('Entered amount is less than the final amount.');
            }
        } else {
            alert('Please enter a valid amount.');
        }
    }

    // Function to toggle sidebar visibility
    function toggleSidebar() {
        document.getElementById("sidebar").classList.toggle("hide");
    }

    // Function to capture cash amount from the calculator
    function captureCashAmount() {
        var cashAmount = parseFloat(document.getElementById('output').innerText);
        document.getElementById('cash_amount').value = cashAmount.toFixed(2);
    }

    // Call captureCashAmount when the page loads to initialize cash_amount
    window.onload = captureCashAmount;
	
	
	
	   
   // Function to handle keyboard input
    document.addEventListener('keydown', function(event) {
        // Get the key pressed
        var key = event.key;

        // If the key is a number, append it to the output
        if (!isNaN(key)) {
            appendNumber(key);
        } else if (key === 'Backspace') {
            // If the key is Backspace, clear the output
            clearOutput();
        } else if (key === 'Enter') {
            // If the key is Enter, calculate the total
            calculate();
        }
    });

</script>


</body>
</html>
<?php } ?>