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

ob_start();

if (isset($_SESSION['user_name'], $_SESSION['user_role'], $_SESSION['outlet_name'], $_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}

@$id = $_GET['product_id'];



    $query = "SELECT * FROM products WHERE product_id = $id";
    $result = mysqli_query($connection, $query);
        $product = mysqli_fetch_assoc($result);

// Handle update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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']);
    $bonus_quantity = mysqli_real_escape_string($connection, $_POST['bonus_quantity']);
    $mini_quantity  = mysqli_real_escape_string($connection, $_POST['mini_quantity']);
    $noofunit       = mysqli_real_escape_string($connection, $_POST['noofunit']);
    $rpperpack      = mysqli_real_escape_string($connection, $_POST['rpperpack']);
    $tpperpack      = mysqli_real_escape_string($connection, $_POST['tpperpack']);
    $total_quantity = mysqli_real_escape_string($connection, $_POST['total_quantity']);
    $t_price        = mysqli_real_escape_string($connection, $_POST['t_price']);
    $t_perprice     = mysqli_real_escape_string($connection, $_POST['t_perprice']);
    $wholesale      = mysqli_real_escape_string($connection, $_POST['wholesale_price']);
    $total_purchase = (float)$trade_price * (float)$quantity;
    $date_time      = date("Y-m-d");

    $update_query = "UPDATE products SET
        product_id='$product_id',
        product_name='$product_name',
        size='$vehicle',
        category='$category',
        company='$company',
        quantity='$quantity',
        retail_price='$retail_price',
        percentage='$percentage',
        wholesale_price='$wholesale',
        trade_price='$trade_price',
        total_amount='$total_amount',
        bonus_quantity='$bonus_quantity',
        mini_quantity='$mini_quantity',
        noofunit='$noofunit',
        rpperpack='$rpperpack',
        tpperpack='$tpperpack',
        total_quantity='$total_quantity',
        t_price='$t_price',
        t_perprice='$t_perprice',
        total_purchase='$total_purchase',
        product_unit='$product_unit',
        supplier='$supplier',
        date_time='$date_time',
        login_user='$userName',
        user_role='$userRole',
        outlet_name='$outlet_name',
        outlet_address='$outlet_address'
    WHERE id='$id'";

    if (!mysqli_query($connection, $update_query)) {
        echo "Error updating product: " . mysqli_error($connection);
    } else {
        echo '<script type="text/javascript">window.location.href="addproduct.php";</script>';
    }
}
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>BOOK POINT</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">
    
<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;
		}
		
label{
    font-weight:700;
    color:#000;   
}
  </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="main-content">
    <div class="container">
        <div class="row">
            <div class="col-sm-9">
                <h3 style="color:#212529;font-weight:700;"> Update Product</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" style="margin-top:20px;">
    <div class="row">
        <div class="col-sm-1"></div>
        <div class="col-sm-5">
            <form method="post" action="" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Product ID</label>
                    <input type="text" name="product_id" class="form-control" 
                        value="<?php echo htmlspecialchars($product['product_id']); ?>">
                </div>
                <div class="form-group">
                    <label>Product Name</label>
                    <input type="text" name="product_name" class="form-control"
                        value="<?php echo htmlspecialchars($product['product_name']); ?>">
                </div>
                <div class="form-group">
                    <label>Company</label>
                    <input type="text" name="company" id="company" class="form-control"
                        value="<?php echo htmlspecialchars($product['company']); ?>">
                </div>
                <div class="row">
                    <div class="form-group col-6 ">
                        <label>Category</label>
                        <select name="category" class="form-control">
                            <option value="">Select</option>
                            <?php
                            $c = mysqli_query($connection,"select * from category");
                            while($ct = mysqli_fetch_array($c)){
                                $sel = ($product['category'] == $ct['category']) ? "selected" : "";
                                echo "<option value='{$ct["category"]}' $sel>{$ct["category"]}</option>";
                            }
                            ?>
                        </select>
                    </div>
                    <div class="form-group col-6 ">
                        <label>Sub - Category</label>
                        <select name="sub_category" class="form-control">
                            <option value="">Select</option>
                            <?php
                            $cs = mysqli_query($connection,"select * from sub_category where head !=''");
                            while($cts = mysqli_fetch_array($cs)){
                                $sel = ($product['sub_category'] == $cts['sub_category']) ? "selected" : "";
                                echo "<option value='{$cts["sub_category"]}' $sel>{$cts["sub_category"]}</option>";
                            }
                            ?>
                        </select>
                    </div>
                </div>
                <div class="row">
                    <div class="form-group col-6">
                        <label>Pack Quantity</label>
                        <input type="text" name="quantity" class="form-control"
                            value="<?php echo htmlspecialchars($product['quantity']); ?>">
                    </div>
                    <div class="form-group col-6">
                        <label>Loose Qty</label>
                        <input type="text" name="bonus_quantity" class="form-control"
                            value="<?php echo htmlspecialchars($product['bonus_quantity']); ?>">
                    </div>
                </div>
                <div class="form-group">
                    <label>Min Quantity</label>
                    <input type="text" name="mini_quantity" id="mini_quantity" class="form-control"
                        value="<?php echo htmlspecialchars($product['mini_quantity']); ?>">
                </div>
                <div class="row">
                    <div class="form-group col-6">
                        <label>Wholesale </label>
                        <input type="text" name="wholesale_price" id="wholesale_price" class="form-control"
                            value="<?php echo htmlspecialchars($product['wholesale_price']); ?>">
                        <input type="hidden" name="wh_percentage" id="wh_percentage" class="form-control" />
                    </div>
                    <div class="form-group col-6">
                        <label>Sale Price(MRP)</label>
                        <input type="text" name="retail_price" id="retail_price" class="form-control"
                            value="<?php echo htmlspecialchars($product['retail_price']); ?>">
                    </div>
                </div>
                <div>
                    <input type="hidden" name="t_price" id="t_price" class="form-control"
                        value="<?php echo htmlspecialchars($product['t_price']); ?>">
                </div>
        </div>
        <div class="col-sm-5">
            <div class="form-group">
                <label>% Apply()</label>
                <input type="text" name="percentage" id="percentage" class="form-control"
                    value="<?php echo htmlspecialchars($product['percentage']); ?>">
            </div>
            <div class="">
                <input type="hidden" name="ex_percentage" id="ex_percentage" class="form-control" />
            </div>
            <div class="form-group">
                <label>Purchase Price</label>
                <input type="text" name="trade_price" id="trade_price" class="form-control"
                    value="<?php echo htmlspecialchars($product['trade_price']); ?>">
            </div>
            <div class="form-group">
                <label>No.of Unit</label>
                <input type="text" name="noofunit" id="noofunit" class="form-control"
                    value="<?php echo htmlspecialchars($product['noofunit']); ?>">
            </div>
            <div class="row">
                <div class="form-group col-6">
                    <label>Sale Price Per Unit</label>
                    <input type="text" name="rpperpack" id="rpperpack" class="form-control"
                        value="<?php echo htmlspecialchars($product['rpperpack']); ?>">
                </div>
                <div class="">
                    <input type="hidden" name="t_perprice" id="t_perprice" class="form-control"
                        value="<?php echo htmlspecialchars($product['t_perprice']); ?>">
                </div>
                <div class="form-group col-6">
                    <label>Purchase Price Per Unit</label>
                    <input type="text" name="tpperpack" id="tpperpack" class="form-control"
                        value="<?php echo htmlspecialchars($product['tpperpack']); ?>">
                </div>
            </div>
            <div class="row">
                <div class="form-group col-6">
                    <label>Total Quantity</label>
                    <input type="text" name="total_quantity" id="total_quantity" class="form-control"
                        value="<?php echo htmlspecialchars($product['total_quantity']); ?>">
                </div>
                <div class="form-group col-6">
                    <label>Total Amount</label>
                    <input type="text" name="total_amount" id="total_amount" class="form-control"
                        value="<?php echo htmlspecialchars($product['total_amount']); ?>">
                </div>
            </div>
            <div class="row">
                <div class="form-group col-6">
                    <label>Supplier</label>
                    <input type="text" name="supplier" class="form-control"
                        value="<?php echo htmlspecialchars($product['supplier']); ?>">
                </div>
                <div class="">
                    <input type="hidden" value="0" name="size" class="form-control" />
                </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" <?php echo ($product['product_unit']=='Pcs')?'selected':''; ?>>Pcs</option>
                    </select>
                </div> 
            </div>
            <div class="">
                <input type="hidden" value="0" name="batch_no" class="form-control" />
                <input type="hidden" value="0" name="size"  class="form-control" />
                <input type="hidden" name="expiry_d" value="0" class="form-control">
            </div>
            <hr />
            <button class="btn btn-dark form-control" type="submit" style="color:#fff;">Update Product</button>
        </div>
        </form>
        <div class="col-sm-1"></div>
    </div>
</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 calculateValues() {
    const packQuantity = parseFloat(document.querySelector('input[name="quantity"]').value) || 0;
    const bonusQuantity = parseFloat(document.querySelector('input[name="bonus_quantity"]').value) || 0;
    let noOfUnit = parseFloat(document.getElementById("noofunit").value) || 1;

    const baseSalePrice = parseFloat(document.getElementById("retail_price").value) || 0;
    const whPercentage = parseFloat(document.getElementById("wh_percentage").value) || 0;
    const percentage = parseFloat(document.getElementById("percentage").value) || 0;
    const exPercentage = parseFloat(document.getElementById("ex_percentage").value) || 0;

    noOfUnit = noOfUnit > 0 ? noOfUnit : 1;

    const totalQuantity = (packQuantity * noOfUnit) + bonusQuantity;
    document.getElementById("total_quantity").value = totalQuantity;

    // Step 1: Subtract percentage from baseSalePrice
    let afterPercentage = baseSalePrice - (baseSalePrice * percentage / 100);

    // Step 2: Add whPercentage on BASE retail_price (not discounted)
    let afterWh = afterPercentage + (baseSalePrice * whPercentage / 100);

    // Step 3: Subtract exPercentage from afterWh
    let finalPrice = afterWh - (afterWh * exPercentage / 100);

    const tradePrice = finalPrice;

    const salePricePerUnit = (baseSalePrice / noOfUnit).toFixed(2);
    document.getElementById("rpperpack").value = salePricePerUnit;

    const purchasePricePerUnit = (tradePrice / noOfUnit).toFixed(2);
    document.getElementById("tpperpack").value = purchasePricePerUnit;

    const totalAmount = (totalQuantity * (tradePrice / noOfUnit)).toFixed(2);
    document.getElementById("total_amount").value = totalAmount;

    document.getElementById("trade_price").value = tradePrice.toFixed(2);
}

function calculateTradePriceFromPercentage() {
    const baseSalePrice = parseFloat(document.getElementById("retail_price").value) || 0;
    const whPercentage = parseFloat(document.getElementById("wh_percentage").value) || 0;
    const percentage = parseFloat(document.getElementById("percentage").value) || 0;
    const exPercentage = parseFloat(document.getElementById("ex_percentage").value) || 0;

    let afterPercentage = baseSalePrice - (baseSalePrice * percentage / 100);
    let afterWh = afterPercentage + (baseSalePrice * whPercentage / 100);
    let finalPrice = afterWh - (afterWh * exPercentage / 100);

    document.getElementById("trade_price").value = finalPrice.toFixed(2);
    calculateValues();
}

let percentageTimer;
document.getElementById("percentage").addEventListener("input", () => {
    clearTimeout(percentageTimer);
    percentageTimer = setTimeout(() => {
        calculateTradePriceFromPercentage();
    }, 500);
});

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('input').forEach(input => {
        input.addEventListener('input', calculateValues);
    });
});
</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>