<?php
include("db/cn.php");
ob_start();

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

// Handle purchase addition
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["submit2"])) {
   
    $product_id = $_POST["product_id"];
    $product_name = $_POST["product_name"];
    $company = $_POST["company"];
    $category = $_POST["category"];
    $length = $_POST["length"];
    $width = $_POST["width"];
    $lengthInch = $_POST["lengthfeet"];
    $widthInch = $_POST["widthfeet"];
    $square_feet = $_POST["sqarea"];
    $quantity = $_POST["quantity"];
    $total_quantity = $_POST["total_quantity"];
    $retail_price = $_POST["retail_price"];
    $percentage = $_POST["percentage_apply"];
    $Extrapercentage = $_POST["percentage_extra"];
    $trade_price = $_POST["trade_price"];
    $total_amount = $_POST["total_amount"];
    $supplier1 = isset($_POST["supplier1"]) ? $_POST["supplier1"] : ''; // Ensure supplier is set
    $rack_no = $_POST["rack_no"];
    $batch_no = $_POST["batch_no"];
    $date_time = date("Y-m-d");
    $login = $userName;
    $role = $userRole;
    $outlet = $outlet_name;
    $address = $outlet_address;
    $paid_by = $_POST["paid_by"];
    $product_unit = $_POST["product_unit"];

    mysqli_query($connection,"insert into purchases(
	product_id,
	product_name,
	company,
	category,
	length_feet,
	width_feet,
	length_inch,
	width_inch,
	square_feet,
	quantity,
	total_quantity,
	retail_price,
	percentage,
	extra_percentage,
	trade_price,
	total_amount,
	supplier_name,
	rack_no,
	batch_no,
	paid_by,
	product_unit,
	date_time,
	user_name,
	user_role,
	outlet_name,
	outlet_address)
	values(
	'$product_id',
	'$product_name',
	'$company',
	'$category',
	'$length',
	'$width',
	'$lengthInch',
	'$widthInch',
	'$square_feet',
	'$quantity',
	'$total_quantity',
	'$retail_price',
	'$percentage',
	'$Extrapercentage',
	'$trade_price',
	'$total_amount',
	'$supplier1',
	'$rack_no',
	'$batch_no',
	'$paid_by',
	'$product_unit',
	'$date_time',
	'$login',
	'$role',
	'$outlet',
	'$address'
	)");
   // Update the products table
    $update_query = "UPDATE products
                     SET total_quantity = total_quantity + $total_quantity,
                         trade_price = $trade_price,
                         retail_price = $retail_price
                     WHERE product_name = '$product_name'";

    mysqli_query($connection, $update_query);
 
   
}

// Fetch distinct product names for live search
$sql12 = "SELECT DISTINCT product_name FROM products";
$result12 = mysqli_query($connection, $sql12);

$categories = [];
if (mysqli_num_rows($result12) > 0) {
    while ($row12 = mysqli_fetch_assoc($result12)) {
        $categories[] = $row12['product_name'];
    }
}

// Check if a name is provided to fetch product details
if (isset($_GET['name'])) {
    $name = $connection->real_escape_string($_GET['name']);
    $sql = "SELECT * FROM products WHERE product_name = ?";
    $stmt = $connection->prepare($sql);
    $stmt->bind_param('s', $name);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $productDetails = $result->fetch_assoc();
        echo json_encode($productDetails);
    } else {
        echo json_encode(['error' => 'Product not found']);
    }
    $stmt->close();
    exit; // Ensure no further processing occurs for AJAX requests
}

ob_end_flush();
?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Purchase</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<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" />
    <!-- QRCode.js -->
    <script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>
</head>

<style>
 #product-container-wrapper {
    max-height: 700px; /* 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:#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);
            }
        }
		label{font-size:12px; font-weight:600;}
		
		    #searchResults {
        position: absolute;
        background-color: #f9f9f9;
        border: 1px solid #ddd;
        max-height: 200px;
        overflow-y: auto;
        width: 92%;
        display: none;
    }
    #searchResults div {
        padding: 10px;
        cursor: pointer;
    }
    #searchResults div:hover {
        background-color: #f1f1f1;
    }
	.autocomplete-active {
    background-color: #353535;
	color:#fff;
}
		</style>
<body>
<?php 



?>
<?php include("common/hd.php"); ?>
<!-- Sidebar -->
<?php include("common/sd.php"); ?>
<div class="main-content">


<?php
// Fetch supplier data
$rec1236 = mysqli_query($connection, "SELECT * FROM supplier 
                                    WHERE user_name = '$userName' 
                                    AND user_role = '$userRole' 
                                    AND outlet_name = '$outlet_name' 
                                    AND outlet_address = '$outlet_address'");
?>
<div class="container">
    <div class="row">
        <div class="col-sm-3">
            <h3 style="color:#212529;">Add Purchase</h3>
        </div>
        <div class="col-sm-1"></div>
        <div class="col-sm-4">
         <input type="text" id="searchInput" autocomplete="off" class="form-control" placeholder="Search Product">
<div id="searchResults"></div>

                    
        </div>
        <div class="col-sm-1">
        
        </div>
        <div class="col-sm-3">
         <a href="addproduct.php"><button type="button" class="btn btn-dark" style="float:right;"><i class="fa fa-arrow-left"></i></button></a>
        </div>
    </div>

<div class="container">
    <div class="row">
        <div class="col-sm-1"></div>
        <div class="col-sm-5">
            <form id="productForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Product ID</label>
                    <input type="text" name="product_id" id="product_id" class="form-control" />
                </div>
                <div class="form-group">
                    <label>Product Name</label>
                    <input type="text" name="product_name" id="product_name" class="form-control" />
                </div>
                <div class="form-group">
                        <label>Category</label>
                        <input type="text" name="category" id="category" class="form-control" />
                    </div>
                <div class="form-group">
                    <label>Company</label>
                    <input type="text" name="company"  id="company" class="form-control" />
                </div>
                
                <div class="row">
                    <div class="col-sm-6 form-group">
                        <label>Length in Inch</label>
                        <input type="text" name="length"  class="form-control in_height" placeholder="Length" />
                    </div>
                    <div class="form-group col-sm-6">
                        <label>Width in Inch</label>
                        <input type="text" name="width"  class="form-control in_height" placeholder="Width" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-6 form-group">
                        <label>Length in Feets</label>
                        <input type="text" name="lengthfeet"  class="form-control in_height" placeholder="Length" />
                    </div>
                    <div class="form-group col-sm-6">
                        <label>Width in Feets </label>
                        <input type="text" name="widthfeet"  class="form-control in_height" placeholder="Width" />
                    </div>
                </div>
                <div class="form-group">
                    <label> Area</label>
                    <input type="text" name="sqarea" id="sqarea" class="form-control"  />
                </div>
                <div class="form-group">
                    <label>Quantity</label>
                    <input type="text" name="quantity" id="quantity" class="form-control" />
                </div>
                <div class="form-group">
                    <label>Total Quantity</label>
                    <input type="text" name="total_quantity" id="total_quantity" class="form-control" readonly />
                </div>
                 
                
            </div>
            <div class="col-sm-5">
               
                <div class="form-group">
                    
                    <input type="hidden" name="percentage_apply" id="percentage_apply" class="form-control" value="0" />
                </div>
                <div class="form-group">
                    
                    <input type="hidden" name="percentage_extra" id="percentage_extra" class="form-control" value="0" />
                </div>
                <div class="form-group">
                    <label>Sale Price</label>
                    <input type="text" name="retail_price" id="retail_price" class="form-control" />
                </div>
                <div class="form-group">
                    <label>Purchase Price</label>
                    <input type="text" name="trade_price" id="trade_price" class="form-control"  />
                </div>
                <div class="form-group">
                    <label>Total Amount</label>
                    <input type="text" name="total_amount" id="total_amount" class="form-control" readonly />
                </div>
                <div class="form-group">
                    <label>Supplier</label>
                    <input type="text" name="supplier1" id="supplier" class="form-control" />
                </div>  
                <div class="form-group">
                    <label>Rack No</label>
                    <input type="text" name="rack_no" id="rack_no" class="form-control" />
                </div>
                <div class="form-group">
                    <label>Batch No</label>
                    <input type="text" name="batch_no" id="batch_no" class="form-control" />
                </div>
                <hr />
                <div class="row">
                <div class=" col-sm-6 form-group">
                    <label>Method</label>
                    <select class="form-control" name="paid_by">
                     <option value="">Select</option>
                     <option value="cash">Cash</option>
                     <option value="credit">Credit</option>
                     <option value="other">Other</option>
                     </select>
                </div>
                    <div class="form-group col-sm-6">
                    <label>Unit</label>
                    <select class=" form-control" name="product_unit">
                     <option value="">Select</option>
                  <option value="kg">KG</option>
                        <option value="gram">Gram</option>
                        <option value="piece">Piece</option>
                        <option value="sq/ft">Sq/Ft</option>
                     </select>
                </div>
                </div>
                <button class="btn btn-dark form-control" type="submit" name="submit2">Save Product</button>
            </div>
            </form>
        </div>
        <div class="col-sm-1">
        </div>
    </div>

</form>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", function () {
    const categories = <?php echo json_encode($categories); ?>;
    const searchInput = document.getElementById('searchInput');
    const searchResults = document.getElementById('searchResults');
    let currentFocus = -1; // To keep track of the currently focused item

    // Function to set z-index of searchResults
    function setSearchResultsZIndex(zIndex) {
        searchResults.style.zIndex = zIndex;
    }

    // Event listeners for input focus and blur
    searchInput.addEventListener('focus', function () {
        setSearchResultsZIndex(2); // Set higher z-index when input is focused
        if (searchResults.innerHTML !== '') {
            searchResults.style.display = 'block';
        }
    });

    searchInput.addEventListener('blur', function () {
        setSearchResultsZIndex(0); // Set lower z-index when input loses focus
        setTimeout(() => {
            searchResults.style.display = 'none';
        }, 200); // Delay hiding dropdown to allow click event on dropdown items
    });

    searchInput.addEventListener('input', function () {
        const query = this.value.trim().toLowerCase();
        if (query === '') {
            searchResults.style.display = 'none';
            return;
        }
        const filteredCategories = categories.filter(category => category.toLowerCase().includes(query));
        renderResults(filteredCategories);
    });

    searchResults.addEventListener('mousedown', function (e) {
        if (e.target.tagName === 'DIV') {
            searchInput.value = e.target.textContent;
            fetchProductDetails(e.target.textContent);
            searchResults.style.display = 'none';
        }
    });

    searchInput.addEventListener('keydown', function (e) {
        const items = searchResults.getElementsByTagName('div');
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            currentFocus++;
            addActive(items);
            ensureVisible(items[currentFocus]);
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            currentFocus--;
            addActive(items);
            ensureVisible(items[currentFocus]);
        } else if (e.key === 'Enter') {
            e.preventDefault();
            if (currentFocus > -1) {
                console.log("Enter pressed on item:", items[currentFocus].textContent);
                searchInput.value = items[currentFocus].textContent;
                fetchProductDetails(items[currentFocus].textContent);
                searchResults.style.display = 'none';
            }
        }
    });

    function addActive(items) {
        if (!items) return false;
        removeActive(items);
        if (currentFocus >= items.length) currentFocus = 0;
        if (currentFocus < 0) currentFocus = items.length - 1;
        items[currentFocus].classList.add('autocomplete-active');
    }

    function removeActive(items) {
        for (let i = 0; i < items.length; i++) {
            items[i].classList.remove('autocomplete-active');
        }
    }

    function ensureVisible(item) {
        const dropdownRect = searchResults.getBoundingClientRect();
        const itemRect = item.getBoundingClientRect();

        if (itemRect.bottom > dropdownRect.bottom) {
            searchResults.scrollTop = item.offsetTop + item.offsetHeight - searchResults.clientHeight;
        } else if (itemRect.top < dropdownRect.top) {
            searchResults.scrollTop = item.offsetTop;
        }
    }

    function renderResults(results) {
        let html = '';
        results.forEach(result => {
            html += `<div>${result}</div>`;
        });
        searchResults.innerHTML = html;
        searchResults.style.display = 'block';
        currentFocus = -1; // Reset focus index when new results are rendered
    }

    function fetchProductDetails(name) {
        fetch(`<?php echo $_SERVER['PHP_SELF']; ?>?name=${encodeURIComponent(name)}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert(data.error);
                } else {
                    populateForm(data);
                }
            })
            .catch(error => {
                console.error('Error fetching product details:', error);
            });
    }

    function populateForm(data) {
        document.getElementById('product_id').value = data.product_id || '';
        document.getElementById('product_name').value = data.product_name || '';
        document.getElementById('company').value = data.company || '';
        document.getElementById('category').value = data.category || '';
        document.getElementById('length').value = data.length || '';
        document.getElementById('width').value = data.width || '';
        document.getElementById('square_feet').value = data.square_feet || '';
		document.getElementById('quantity').value = data.quantity || '';
		document.getElementById('total_quantity').value = data.total_quantity || '';
		document.getElementById('retail_price').value = data.retail_price || '';
		document.getElementById('percentage').value = data.percentage || '';
		document.getElementById('trade_price').value = data.trade_price || '';
        document.getElementById('total_amount').value = data.total_amount || '';
		document.getElementById('supplier').value = data.supplier || '';
		document.getElementById('rack_no').value = data.rack_no || '';
		document.getElementById('batch_no').value = data.batch_no || '';

    }
});

function calculateSquareFeet() {
        let lengthFeet = parseFloat(document.querySelector('input[name="lengthfeet"]').value) || 0;
        let widthFeet = parseFloat(document.querySelector('input[name="widthfeet"]').value) || 0;
        let lengthInch = parseFloat(document.querySelector('input[name="length"]').value) || 0;
        let widthInch = parseFloat(document.querySelector('input[name="width"]').value) || 0;

        let lengthInInches = lengthFeet > 0 ? lengthFeet : lengthInch;
        let widthInInches = widthFeet > 0 ? widthFeet  : widthInch;

        let areaInSquareFeet = (lengthInInches) * (widthInInches) || (lengthFeet) * (widthFeet) ;
        

        document.querySelector('input[name="sqarea"]').value = areaInSquareFeet.toFixed(2);

        calculateTotalQuantity();
    }

function calculateTotalQuantity() {
    let area = parseFloat(document.querySelector('input[name="sqarea"]').value) || 0;
    let quantity = parseFloat(document.querySelector('input[name="quantity"]').value) || 0;

    let totalQuantity = area * quantity;

    document.querySelector('input[name="total_quantity"]').value = totalQuantity.toFixed(2);

    calculateTotalAmount();
}

function calculateTradePrice() {
    let trade_price = parseFloat(document.getElementById("trade_price").value) || 0;
    calculateTotalAmount();
}

function calculateTotalAmount() {
    let total_quantity = parseFloat(document.getElementById("total_quantity").value) || 0;
    let trade_price = parseFloat(document.getElementById("trade_price").value) || 0;

    if (total_quantity > 0 && trade_price > 0) {
        let total_amount = (total_quantity * trade_price).toFixed(2);
        document.getElementById("total_amount").value = total_amount;
    } else {
        document.getElementById("total_amount").value = '';
    }
}

document.addEventListener('DOMContentLoaded', (event) => {
    document.querySelector('input[name="length"]').addEventListener('input', calculateSquareFeet);
    document.querySelector('input[name="width"]').addEventListener('input', calculateSquareFeet);
    document.querySelector('input[name="lengthfeet"]').addEventListener('input', calculateSquareFeet);
    document.querySelector('input[name="widthfeet"]').addEventListener('input', calculateSquareFeet);
    document.querySelector('input[name="quantity"]').addEventListener('input', calculateTotalQuantity);
    document.getElementById("trade_price").addEventListener('input', calculateTradePrice);
});

  
	
	

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 toggle submenu
    function toggleSubMenu(element) {
        $(element).next('.sub-menu').slideToggle();
    }
</script>
<!-- jQuery library -->
<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>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</html>
