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



// Check if session variables are set
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'];
} else {
    // Redirect to login page or handle the error
    echo "Session variables not set. Please log in.";
    exit;


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and validate input data
    $product_id = mysqli_real_escape_string($connection, $_POST['product_id']);
    $product_name = mysqli_real_escape_string($connection, $_POST['product_name']);
    $company = mysqli_real_escape_string($connection, $_POST['company']);
    $length = mysqli_real_escape_string($connection, $_POST['length']);
    $width = mysqli_real_escape_string($connection, $_POST['width']);
    $length_feet = mysqli_real_escape_string($connection, $_POST['lengthfeet']);
    $width_feet = mysqli_real_escape_string($connection, $_POST['widthfeet']);
    $square_feet = mysqli_real_escape_string($connection, $_POST['sqarea']);
    $quantity = mysqli_real_escape_string($connection, $_POST['quantity']);
    $total_quantity = mysqli_real_escape_string($connection, $_POST['total_quantity']);
    $retail_price = mysqli_real_escape_string($connection, $_POST['retail_price']);
    $percentage = mysqli_real_escape_string($connection, $_POST['percentage']);
    $trade_price = mysqli_real_escape_string($connection, $_POST['trade_price']);
    $total_amount = mysqli_real_escape_string($connection, $_POST['total_amount']);
    $supplier = mysqli_real_escape_string($connection, $_POST['supplier']);
    $rack_no = mysqli_real_escape_string($connection, $_POST['rack_no']);
    $batch_no = mysqli_real_escape_string($connection, $_POST['batch_no']);
    $product_unit = mysqli_real_escape_string($connection, $_POST['product_unit']);
    $date_time = date("Y-m-d");

    // Insert data into 'products' table
    $insert_product_query = "INSERT INTO products(product_id, product_name, company, length, width, length_feet, width_feet, square_feet, quantity, total_quantity, retail_price, percentage, trade_price, total_amount, product_unit, supplier, rack_no, batch_no, date_time, login_user, user_role, outlet_name, outlet_address) VALUES ('$product_id', '$product_name', '$company', '$length', '$width', '$length_feet', '$width_feet', '$square_feet', '$quantity', '$total_quantity', '$retail_price', '$percentage', '$trade_price', '$total_amount', '$product_unit', '$supplier', '$rack_no', '$batch_no', '$date_time', '$userName', '$userRole', '$outlet_name', '$outlet_address')";

    if (!mysqli_query($connection, $insert_product_query)) {
        echo "Error inserting product: " . mysqli_error($connection);
    }

    // Insert data into 'opening_products' table
    $insert_opening_product_query = "INSERT INTO opening_products(product_id, product_name, company, length_feet, width_feet, length_inch, width_inch, square_feet, quantity, total_quantity, retail_price, percentage, trade_price, total_amount, product_unit, supplier, rack_no, batch_no, date_time, login_user, user_role, outlet_name, outlet_address) VALUES ('$product_id', '$product_name', '$company', '$length_feet', '$width_feet', '$length', '$width', '$square_feet', '$quantity', '$total_quantity', '$retail_price', '$percentage', '$trade_price', '$total_amount', '$product_unit', '$supplier', '$rack_no', '$batch_no', '$date_time', '$userName', '$userRole', '$outlet_name', '$outlet_address')";

    if (!mysqli_query($connection, $insert_opening_product_query)) {
        echo "Error inserting opening product: " . mysqli_error($connection);
    }
}

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 */
}
/* 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 */
    }
    .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;}
		</style>
<body>

<?php include("common/hd.php"); ?>
<!-- Sidebar -->
<?php include("common/sd.php"); ?>
<div class="main-content">
    <div class="container">
        <div class="row">
            <div class="col-sm-9">
                <h3 style="color:#212529;"> Add Opening</h3>
            </div>
            <div class="col-sm-3">
                <a href="addproduct.php"><button type="button" class="btn btn-dark" style="float:left;"><i class="fa fa-arrow-left"></i></button></a>
            </div>
        </div>
    </div><br />
    <div class="container">
        <div class="row">
            <div class="col-sm-1"></div>
            <div class="col-sm-5">
                <form 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" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Product Name</label>
                        <input type="text" name="product_name" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Company</label>
                        <input type="text" name="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" placeholder="Length" />
                        </div>
                        <div class="form-group col-sm-6">
                            <label>Width in Inch</label>
                            <input type="text" name="width" class="form-control" 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" placeholder="Length" />
                        </div>
                        <div class="form-group col-sm-6">
                            <label>Width in Feets </label>
                            <input type="text" name="widthfeet" class="form-control" placeholder="Width" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Square / Feet Area</label>
                        <input type="text" name="sqarea" class="form-control" readonly />
                    </div>
                    <div class="form-group">
                        <label>Quantity</label>
                        <input type="text" name="quantity" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Total Quantity in Square Feet</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">
                        <label>Retail Price Per Sq/Feet</label>
                        <input type="text" name="retail_price" id="retail_price" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>% Apply</label>
                        <input type="text" name="percentage" id="percentage" class="form-control" readonly />
                    </div>
                    <div class="form-group">
                        <label>Trade Price Per Sq/Feet</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>Product Unit</label>
                        <select name="product_unit" class="form-control">
                        <option value="">Select Unit</option>
                        <option value="piece">Piece</option>
                        <option value="sq/ft">Sq/Ft</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Supplier</label>
                        <input type="text" name="supplier" class="form-control" />
                    </div>  
                    <div class="form-group">
                        <label>Rack No</label>
                        <input type="text" name="rack_no" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Batch No</label>
                        <input type="text" name="batch_no" class="form-control" />
                    </div>
                    <hr />
                    <button class="btn btn-dark form-control" type="submit">Save Product</button>
                </div>
                </form>
            </div>
            <div class="col-sm-1">
            </div>
        </div>
    </div>           
</div>               
</body>
<script>
    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 * 12 : lengthInch;
        let widthInInches = widthFeet > 0 ? widthFeet * 12 : widthInch;

        if (lengthFeet > 0) {
            document.querySelector('input[name="length"]').value = lengthInInches.toFixed(2);
        }
        if (widthFeet > 0) {
            document.querySelector('input[name="width"]').value = widthInInches.toFixed(2);
        }

        let areaInSquareFeet = (lengthInInches / 12) * (widthInInches / 12);

        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 calculateTradePercentage() {
        let retail_price = parseFloat(document.getElementById("retail_price").value) || 0;
        let trade_price = parseFloat(document.getElementById("trade_price").value) || 0;

        if (retail_price > 0 && trade_price > 0) {
            let percentage = ((retail_price - trade_price) * 100 / retail_price).toFixed(2);
            document.getElementById("percentage").value = percentage;
        } else {
            document.getElementById("percentage").value = '';
        }
    }

    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("retail_price").addEventListener('input', calculateTradePercentage);
        document.getElementById("trade_price").addEventListener('input', () => {
            calculateTradePercentage();
            calculateTotalAmount();
        });
    });

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

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

        function checkScreenSize() {
            if (window.innerWidth > 768) {
                sidebar.classList.remove("hide");
                overlay.classList.remove("hide");
            } else {
                sidebar.classList.add("hide");
                overlay.classList.add("hide");
            }
        }

        checkScreenSize();
        window.addEventListener("resize", checkScreenSize);
    });

    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>
<?php
}
?>