<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include("db/cn.php");
ob_start();

// 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']);
    $quantity = mysqli_real_escape_string($connection, $_POST['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']);
    $product_unit = mysqli_real_escape_string($connection, $_POST['product_unit']);
    $vehicle = mysqli_real_escape_string($connection, $_POST['size']);
    $category = mysqli_real_escape_string($connection, $_POST['category']);
    $wholesalePrice = mysqli_real_escape_string($connection, $_POST['wholesale_price']);
    $wh_percentage = mysqli_real_escape_string($connection, $_POST['wh_percentage']);
    $total_purchase = $trade_price * $quantity;
    $date_time = date("Y-m-d");


 $uploaded_file_path = '';
    if (isset($_FILES['img_upload']) && $_FILES['img_upload']['error'] === UPLOAD_ERR_OK) {
        $fileTmp = $_FILES['img_upload']['tmp_name'];
        $fileName = basename($_FILES['img_upload']['name']);
        $fileType = mime_content_type($fileTmp);

        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (!in_array($fileType, $allowedTypes)) {
            die("Invalid file type.");
        }

        $uploadDir = __DIR__ . '/uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $uploaded_file_path = '../uploads/' . $fileName;
        $targetFile = __DIR__ . '/' . $uploaded_file_path;

        if (!move_uploaded_file($fileTmp, $targetFile)) {
            echo "Error moving uploaded file.";
            $uploaded_file_path = '';
        }
    }
    
    // Check if the product_id already exists
    $check_query = "SELECT * FROM products WHERE product_id = '$product_id'";
    $check_result = mysqli_query($connection, $check_query);

    if (mysqli_num_rows($check_result) > 0) {
        // Product ID already exists, show an alert message
        echo "<script>alert('Product ID: $product_id and Product Name: $product_name already exists in the database.');</script>";
    } else {
        // Insert data into 'products' table
        $insert_product_query = "INSERT INTO products(product_id, product_name, expiry, category, company, quantity, wholesale_price, retail_price, percentage, wh_percentage, trade_price, total_amount, total_purchase, product_unit, supplier, date_time, img_upload, login_user, user_role, outlet_name, outlet_address) 
        VALUES ('$product_id', '$product_name', '$vehicle', '$category', '$company', '$quantity', '$wholesalePrice', '$retail_price', '$percentage', '$wh_percentage', '$trade_price', '$total_amount','$total_purchase', '$product_unit', '$supplier', '$date_time', '$uploaded_file_path', '$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, size, category, company, quantity, retail_price, percentage, trade_price, total_amount, product_unit, supplier, date_time, login_user, user_role, outlet_name, outlet_address) VALUES ('$product_id', '$product_name', '$vehicle', '$category', '$company', '$quantity', '$retail_price', '$percentage', '$trade_price', '$total_amount', '$product_unit', '$supplier', '$date_time', '$userName', '$userRole', '$outlet_name', '$outlet_address')";

        if (!mysqli_query($connection, $insert_opening_product_query)) {
            echo "Error inserting opening product: " . mysqli_error($connection);
        }
    }
}
$pr_id2 = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
$barcodeUrl = "https://barcode.tec-it.com/barcode.ashx?data={$pr_id2}&code=Code128&dpi=96";
$barcodeFilename = "barcode_$pr_id2.png";
ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Kashmir Bazar</title>

    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
   <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Custom styles for this template-->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.css" rel="stylesheet">
    
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<style>
body {
    font-family: 'Quicksand', sans-serif;
    
}
		    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
.bg-gradient-primary{
    
	background:#0A4657;
	color:#fff;	
	
	}

.btn-primary{
	background:#0A4657;
	color:#fff;
	 border:1px #0A4657 solid;
	
	}  
.btn-primary:hover{
  
  background:#fff;
  border:1px #0A4657 solid;
	color:#0A4657;
	
	}	 
    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
	
	.fa-download:hover{
		color:#953E39;
		}
		
.btn, .form-control, option{
	font-weight:700;  	
		}
  </style>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <?php
        include("common/sd.php");
		?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

                    <!-- Sidebar Toggle (Topbar) -->
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>

                    <!-- Topbar Search -->
                    
  <?php include('common/log.php');  ?>

                    <!-- Topbar Navbar -->
                    
                </nav>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
                
 <div class="container">
        <div class="row">
            <div class="col-sm-9">
                <h3 style="color:#212529; font-weight:700;"> Add New Product</h3></div>
            <div class="col-sm-3"></div>
        </div>
    </div><br />
    <br />
    <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"  required> 
                    </div>
                    <div class="form-group">
                        <label>Product Name</label>
                        <input type="text" name="product_name" class="form-control" required/>
                    </div>
                    <div class="">
               <?php 
                 $c = mysqli_query($connection,"select * from category");
               ?> 
                <div class="form-group ">
                    <label>Category</label>
                    <select name="category"   class="form-control" required>
                        <option value="">Select</option>
                        <?php
                          while($r = mysqli_fetch_array($c)){
                        ?>
                        <option class="text-capitalize" value="<?php echo $r["category"]; ?>"><?php echo $r["category"]; ?></option>
                        <?php 
                          }
                         ?>
                    </select>    
                </div>
                <div class="form-group ">
                    <label>Brand Name</label>
                    <input type="text" name="company"  id="company" class="form-control" required/>
                </div>
                </div>
                    
                    <div class="">
                      
                        <input type="hidden" name="quantity" class="form-control" required/>
                    </div>
                      <div class="form-group">
                        <label>WholeSale Price</label>
                        <input type="text" name="wholesale_price" class="form-control" required/>
                    </div>
                    <div class="form-group">
                        <label>Sale Price</label>
                        <input type="text" name="retail_price" id="retail_price" class="form-control" required/>
                    </div>
                    
                </div>
                <div class="col-sm-5">
                    
                    <div class="row">
                    <div class="form-group col-6">
                        <label>% Apply</label>
                        <input type="text" name="percentage" id="percentage" class="form-control" readonly />
                    </div>
                    <div class="form-group col-6">
                        <label>Mwst% </label>
                        <input type="text" name="wh_percentage"  class="form-control"  required/>
                    </div>
                    </div>
                    <div class="form-group">
                        <label>Purchase Price</label>
                        <input type="text" name="trade_price" id="trade_price" class="form-control" required/>
                    </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="supplier" class="form-control" required/>
                    </div> 
                    
                    <div class="row">
                    <div class=" col-6 form-group">
                        <label>Expiry</label>
                        <input type="date" name="size"  class="form-control" required/>
                    </div>
                    <div class="col-6 form-group">
                        <label>Product Unit</label>
                        <select name="product_unit" class="form-control">
                        <option value="">Select Unit</option>
                        <option value="Pcs">Pcs</option>
                        <option value="ltr">Litre</option>
                        <option value="kg">KG</option>
                        <option value="gram">Gram</option>
                        <option value="packs">Packs</option>
                        </select>
                    </div> 
                    </div>
                    <div class="form-group">
                        <label>Product Image</label>
                        <input type="file" name="img_upload" class="form-control btn btn-primary" required >
                    </div>
                    <hr />
                    <button class="btn btn-dark form-control" type="submit">Save Product</button>
                </div>
                </form>
            </div>
            <div class="col-sm-1">
            </div>
        </div>
           
    
            
                <!-- /.container-fluid -->

            </div>
            <br><br>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php");  ?>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="">Logout</a>
                </div>
            </div>
        </div>
    </div>
<script>
    function calculateTotalAmount() {
        let quantity = parseFloat(document.querySelector('input[name="quantity"]').value) || 0;
        let trade_price = parseFloat(document.getElementById("trade_price").value) || 0;

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

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

    document.addEventListener('DOMContentLoaded', (event) => {
        document.querySelector('input[name="quantity"]').addEventListener('input', calculateTotalAmount);
        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>
   <script>
document.addEventListener("DOMContentLoaded", function () {
    const productIdInput = document.querySelector('input[name="product_id"]');
    productIdInput.addEventListener('keydown', function (event) {
        if (event.key === 'Enter') {
            event.preventDefault(); // prevent form submission
            // optionally, move focus to next input field
            document.querySelector('input[name="product_name"]').focus();
        }
    });
});
</script> 
   <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>

</body>

</html>