<?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'];
       

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Initialize variables
    $saleBy = isset($_POST["sale_by"]) ? $_POST["sale_by"] : ""; // Sale by information
    $paidBy = isset($_POST["paid_by"]) ? $_POST["paid_by"] : ""; // Paid by information
    $customer = isset($_POST['customer']) ? $_POST['customer'] : ""; // Customer name
    $phone = isset($_POST['phone']) ? $_POST['phone'] : "";
	
    // Check if the necessary POST variables are set
    if (isset($_POST['product_id']) && isset($_POST['product_name']) && isset($_POST['product_price']) && isset($_POST['product_quantity']) && isset($_POST['total_amount']) && isset($_POST['total_tax']) && isset($_POST['discount_amount']) && isset($_POST['supplier']) && isset($_POST['company']) && isset($_POST['company_category'])) {
        // Retrieve data from POST request
        $productIds = $_POST['product_id']; // Array of product IDs
        $productNames = $_POST['product_name']; // Array of product names
        $productPrices = $_POST['product_price']; // Array of product prices
        $productQuantities = $_POST['product_quantity']; // Array of product quantities
        $totalAmountString = $_POST['total_amount']; // Total amount string
        $totalTaxString = $_POST['total_tax']; // Total tax string
        $discountAmount = $_POST['discount_amount']; // Discount amount
          $suppliers = $_POST['supplier']; // Array of suppliers
            $companies = $_POST['company']; // Array of companies
            $companyCategories = $_POST['company_category']; // Array of company categories
	  
	  
	  
	  
	  
  $userName1 = $_SESSION['user_name'];
    $userRole1 = $_SESSION['user_role'];
	$outlet_address1 = $_SESSION['outlet_address'];
	$outlet_name1 = $_SESSION['outlet_name'];
        // Check if arrays are not empty before proceeding
        if (!empty($productIds) && !empty($productNames) && !empty($productPrices) && !empty($productQuantities)) {
            // Extract numeric values using regular expressions
            preg_match('/Rs (\d+\.\d+)/', $totalAmountString, $totalAmountMatches); // Extract total amount
            preg_match('/Rs (\d+\.\d+)/', $totalTaxString, $totalTaxMatches); // Extract total tax

            // Extracted numeric values
            $totalAmount = isset($totalAmountMatches[1]) ? (float)$totalAmountMatches[1] : 0; // Convert total amount to float
            $totalTax = isset($totalTaxMatches[1]) ? (float)$totalTaxMatches[1] : 0; // Convert total tax to float

             // Calculate tax rate
        $taxRate = 0.00; // 10% tax rate

        // Calculate total tax amount
        $totalTaxAmount = $totalAmount * $taxRate;

        $taxNewAmount = $totalTaxAmount + $totalAmount - $discountAmount;

        // Generate unique order number
        $orderNumber = uniqid('ORDER');

        $date_time = date("Y-m-d");
		//$day_time = date('l');
        // Start a transaction
        $connection->begin_transaction();
        
      // Retrieve cash amount and change amount from the form data
// Retrieve cash amount and change amount from the form data
        $cashAmount = isset($_POST["cash_amount"]) ? $_POST["cash_amount"] : ""; // Cash amount
        $changeAmount = isset($_POST["change_amount"]) ? $_POST["change_amount"] : ""; // Change amount

 // Construct the SQL query for sales table
                $sql = "INSERT INTO log_user_sales (product_id, supplier_name, company, company_category, product_name, product_price, product_quantity, 
                    product_total, tax_amount, total_amount, paid_by, customer_name, customer_phone, discount_amount, cash_amount, change_amount, order_id, outlet_name,
                    login_user, user_role, outlet_address, date_time) VALUES ";

                // Iterate over the product data and append values to the query
                for ($i = 0; $i < count($productIds); $i++) {
                    $productId = $productIds[$i];
                    $productName = $productNames[$i];
                    $productPrice = $productPrices[$i];
                    $productQuantity = $productQuantities[$i];
                    $supplier = $suppliers[$i];
                    $company = $companies[$i];
                    $companyCategory = $companyCategories[$i];
                    $productTotal = $productPrice * $productQuantity; // Calculate product_total

                    // Append values to the query
                    $sql .= "('$productId', '$supplier', '$company', '$companyCategory', '$productName', '$productPrice', '$productQuantity', '$productTotal', 
                        '$totalTaxAmount', '$taxNewAmount', '$paidBy', '$customer', '$phone', '$discountAmount', '', '', '$orderNumber',
                        '$outlet_name', '$userName', '$userRole', '$outlet_address', '$date_time')";


    // Append a comma if it's not the last iteration
    if ($i < count($productIds) - 1) {
        $sql .= ", ";
    }

    // Update the quantity of the product in the database
    $updateQuantitySql = "UPDATE products SET total_quantity = total_quantity - $productQuantity WHERE name = '$productName'";
    if (!$connection->query($updateQuantitySql)) {
        // If an error occurs, rollback the transaction
        $connection->rollback();
        echo "Error updating product quantity: " . $updateQuantitySql . "<br>" . $connection->error;
        exit();
    }
}

            // Execute the constructed SQL query for sales table
            if ($connection->query($sql) === TRUE) {
                // Insert data into cdetail table
                $cdetailSql = "INSERT INTO cdetail (customer_name, phone_number, sale_by, outlet_name, outlet_address, paid_by, order_id) VALUES ('$customer', '$phone', '$userName1', '$outlet_name1', '$outlet_address1', '$paidBy', '$orderNumber')";
                if ($connection->query($cdetailSql) === TRUE) {
                    // Commit the transaction if everything is successful
                    $connection->commit();
                    echo "Transaction successful.";
                } else {
                    // Rollback the transaction if an error occurs
                    $connection->rollback();
                    echo "Error inserting into cdetail table: " . $cdetailSql . "<br>" . $connection->error;
                }
            } else {
                // Rollback the transaction if an error occurs
                $connection->rollback();
                echo "Error inserting into sales table: " . $sql . "<br>" . $connection->error;
            }
        } else {
            // Send JSON response indicating missing product details
            echo json_encode(array("error" => "Product details are missing."));
            exit();
        }
    } else {
        // Send JSON response indicating missing required fields
        header("location: print_bill.php");
        exit();
    }
}

?>
<!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;
			text-align:right;
			font-size:36px;
			font-weight:700;
        }

        .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="print_bill.php" method="post" enctype="multipart/form-data">
 <!-- Other form fields -->
    <input type="hidden" name="orderid" value="<?php echo $orderNumber; ?>">
    <input type="hidden" name="customer" value="<?php echo $customer; ?>">
    <input type="hidden" name="phone" value="<?php echo $phone; ?>">
    <input type="hidden" name="sale_by" value="<?php echo $saleBy; ?>">
    <input type="hidden" name="paid_by" value="<?php echo $paidBy; ?>">
    <!-- Hidden input fields for product information -->
    <?php for ($i = 0; $i < count($productIds); $i++) : ?>
        <input type="hidden" name="product_id[]" value="<?php echo $productIds[$i]; ?>">
        <input type="hidden" name="product_name[]" value="<?php echo $productNames[$i]; ?>">
        <input type="hidden" name="product_price[]" value="<?php echo $productPrices[$i]; ?>">
        <input type="hidden" name="product_quantity[]" value="<?php echo $productQuantities[$i]; ?>">
        <!-- Calculate total amount for each product -->
        <?php $productTotal = $productPrices[$i] * $productQuantities[$i]; ?>
        <input type="hidden" name="product_totals[]" value="<?php echo $productTotal; ?>">
    <?php endfor; ?>
    <!-- Hidden input fields for total, tax, and discount -->
    <input type="hidden" name="total_amount" value="<?php echo $totalincartSum; ?>">
    <input type="hidden" name="tax_amount" value="<?php echo $totalTaxAmount; ?>">
    <input type="hidden" name="discount_amount" value="<?php echo $discountAmount; ?>">
       
<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>
            </tr>
        </thead>
        <tbody>
            <?php for ($i = 0; $i < count($productNames); $i++) : ?>
                <tr class="text-center text-capitalize">
                    
                    <td><?php echo $productNames[$i]; ?></td>
                    <td><?php echo $productPrices[$i]; ?></td>
                    <td><?php echo $productQuantities[$i]; ?></td>
                    <td>
                        <?php 
                            $totalincart = $productPrices[$i] * $productQuantities[$i]; 
                            echo $totalincart.'';
                        ?>
                    </td>
                </tr>
            <?php endfor; ?>
        </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 style="margin-left:20px;"> 
               <?php
				$totalincartSum = 0; // Initialize the sum variable
				
				// Loop through the arrays
				for ($i = 0; $i < count($productNames); $i++) {
					// Calculate totalincart for each row
					$totalincart = $productPrices[$i] * $productQuantities[$i]; 
					$totalincartSum += $totalincart; // Add to the sum
				}
				?>
                <td style="font-size:14px;"><p><strong>Sub Total:</strong></p></td>
                <td  >Rs&nbsp;<?php echo $totalincartSum; ?>&nbsp; /-</td>
                </tr>
                <tr>
                <td style="font-size:14px;"><p><strong>Tax :</strong></p></td>
                <td  > Rs&nbsp;<?php echo $totalTaxAmount; ?>&nbsp; /-</td>
                </tr>
                <tr>
                <td style="font-size:14px;">
                <p><strong>Discount:</strong></p></td>
                <td  > Rs&nbsp;<?php echo $discountAmount; ?>&nbsp; /-</td></tr>
                <tr><td style="font-size:14px;">
                <p><strong>Total Amount:</strong></p></td>
                <td  >Rs&nbsp;<?php echo $taxNewAmount; ?>&nbsp;/-</td></tr>
                <tr><td>
                </td></tr>
               <input type="hidden" name="total_amount" value="<?php echo $taxNewAmount; ?>">
               
               </table>
      
           
          

               <br>
               <center><!--<button type="button" class="btn btn-dark form-control" style="width:75%;" 
               onclick="submitForm()">Generate Invoice</button>-->
</center>
               
               </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> Total Amount Payable:</strong></p></div>
                <div class="col-sm-6" style="font-size:21px; font-weight:700;"> <?php echo'Rs&nbsp;'.$taxNewAmount.' /-'; ?></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()">Generate</button>
                            
                            
                        </div>
                    </div>
                </div>
             <input type="hidden" id="cash_amount" name="cash_amount" value="">
<input type="hidden" id="change_amount" name="change_amount" value="">
</div>
</div>
</div>




    <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>
      
	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);
});
 

    // 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 calculate() {
    var enteredAmount = parseFloat(document.getElementById('output').innerText);
    var finalAmount = <?php echo $taxNewAmount; ?>;

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

function submitForm() {
    document.getElementById('myForm').submit();
}
    // 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);
    }
	 // Function to toggle sidebar visibility
   
   // 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  } ?>