<?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'];
}
// Handle purchase addition
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["submit2"])) {
    $product_id = $_POST["product_id"]; // Use the product ID retrieved from the previous page
    $name1 = $_POST["name1"];
    $price1 = $_POST["price1"];
    $category1 = $_POST["category1"];
    $stock_qty1 = $_POST["stock_qty1"];
    $unit_pr1 = $_POST["unit_pr1"];

    // Insert purchase information into the database
    $purchaseSql = "INSERT INTO purchases (name, product_id, price, category, stock_qty, unit_pr, user_name, user_role, outlet_name, outlet_address, date_time)
	VALUES ('$name1', '$product_id', $price1, '$category1', $stock_qty1, '$unit_pr1','$userName','$userRole','$outlet_name','$outlet_address', NOW())";
    if ($connection->query($purchaseSql) === TRUE) {
        // Purchase added successfully
        // Update the stock_qty in the products table
        $updateSql = "UPDATE products SET stock_qty = stock_qty + $stock_qty1 WHERE id = '$product_id'";
        if ($connection->query($updateSql) === TRUE) {
            // Stock quantity updated successfully
            header("location:addproduct.php");
        } else {
            echo "Error updating stock quantity: " . $updateSql . "<br>" . $connection->error;
        }
    } else {
        echo "Error adding purchase: " . $purchaseSql . "<br>" . $connection->error;
    }
}
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["submit3"])) {
	$product_id1 = $_POST["product_id"];
	
	$price12 = $_POST["price1"];
	
	$updateSql2 = "UPDATE products SET price = $price12 WHERE id = '$product_id1'";

	 if ($connection->query($updateSql2) === TRUE) {
            // Stock quantity updated successfully
            header("location:addproduct.php");
        } else {
            echo "Error updating Price: " . $updateSql2 . "<br>" . $connection->error;
        }
	
	
	
	}


?>

<!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" />
     <meta http-equiv="refresh" content="25">
    <title>Stock and Manage</title>
    <!-- Latest compiled and minified 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">
<link rel="stylesheet" href="css/custom_css.css" />
    <!-- QRCode.js -->
</head>

<style>
/* Custom styles for sidebar */
    .sidebar {
    width: 100px;
    background-color: #8A1218;
    position: fixed;
    bottom: 0;
	top:60px;
    transition: transform 0.3s ease-in-out;
    transform: translateX(0);
    z-index: 1;
    height: 100%;
    border-radius: 0px;
}
    .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: #8A1218;
    }
    /* 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-color: #8A1218;
      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:#8A1218;
			 color:#fff;
			 border-radius:
                 	}
		.btn-dark:hover{
			background:#fff;
			 color:#8A1218;
			 border:1px solid #8A1218;
			}	
			.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);
            }
        }


 /* Basic styling */
    .tab {
        display: none;
        padding: 20px;
    }
    .active {
        display: block;
    }
    .tab-buttons {
        display: flex;
    }
    .tab-button {
        cursor: pointer;
        padding: 10px 20px;
        background-color: #ffff;
        border: 1px solid #881218;
        border-radius: 5px 5px 0 0;
        margin-right: 5px;
		color:#881218;
    }
    .tab-button.active {
        background-color: #881218;
		color:#fff;
    }

    /* Background colors for tab content */
    #tab1 {
        background-color: #EFEEEE;
		color:#881218;
    }
    #tab2 {
        color:#881218;
		background-color: #EFEEEE;
    }
    #tab3 {
		color:#881218;
        background-color: #EFEEEE;
    }
</style>

<body>

<?php
if(isset($msg)){
	
	echo $msg;
	}
?>
<?php include("common/hd.php"); ?>
<!-- Sidebar -->
<?php include("common/sd.php"); ?>

<?php
	  $name = $_GET["name"]; 
	  $current_date = date('Y-m-d');
      $closing = mysqli_query($connection,"select * from daily_closing where date_time ='$current_date' && name = '$name' ");
	   $close = mysqli_fetch_array($closing);
	  ?>
      
<div class="main-content">
<br />
<div class="container">
<div class="row">
<div class="col-sm-9 text-capitalize">
<h3 style="color:#881218;">Stock & Product Management (<?php echo $name;?>)</h3>
</div>
<div class="col-sm-3">

      
<a href="addproduct.php"><button type="button" class="btn btn-dark"><i class="fa fa-arrow-left"></i></button></a>

</div>
</div>

</div>

<div class="container">
 <div class="row">
   
     <div class="col-sm-12">
      <table class="table table-stripped text-center">
      <tr style="background:#881218;color:#fff;">
          <td>Date</td>
          <td style="text-transform:capitalize;">Name</td>
          <td>Opening Qty</td>
          <td>In-Store Qty</td>
          <td>Sales Qty</td>
          <td>Closing Qty</td>
      </tr>
      
      <tr class="text-capitalize">
      
      
      
      
         <td><?php  echo $close['date_time'];  ?></td>
         <td><?php  echo $close['name'];  ?></td> 
         <td><?php  echo $close['open_qty'];  ?></td> 
         <td><?php  echo $close['instore'];  ?></td>
         <td><?php  echo $close['sales'];  ?></td>
         <td><?php  echo $close['closing_qty'];  ?></td>    
     </tr>
      
      </table>
     </div>
     
      
 </div>
</div>

<br />
<br />
<div class="container">
<div class="tab-buttons">
    <div class="tab-button active" onclick="openTab(event, 'tab1')">Overview</div>
    <div class="tab-button" onclick="openTab(event, 'tab2')">IN-Store</div>
    <div class="tab-button" onclick="openTab(event, 'tab3')">Sales</div>
</div>

<div class="tab-container">
    <div id="tab1" class="tab active">
    <h2>Overview</h2>
    <div class="container">
        <div class="row">
                <div class="col-sm-7"></div>
            
            <div class="col-sm-4">
             
    
            <br />
            </div>
            <div class="col-sm-1"><button class="btn btn-dark" id="downloadButton"><i class="fa fa-download"></i></button></div>
            <br />
           
                <!--<table class="table table-striped " id="overviewTable" style="margin-top:12px;">
                    <tr style="background:#881218;text-transform:capitalize; text-align:center;">
                    
                        <td class="text-white">Date</td>
                        <td class="text-white">Opening Qty</td>
                        <td class="text-white">In-store Qty</td>
                        <td class="text-white">Sales Qty</td>
                       
                        <td class="text-white">Closing Qty</td>
                    </tr>-->
<?php 
/*  
// Start date of the month
$start_date = date('Y-m-01');
// End date of the month
$end_date = date('Y-m-t');

// Initialize opening quantity for the first day of the month
$opening_qty = 0;

// Loop through each day of the month
$current_date = $start_date;
while (strtotime($current_date) <= strtotime($end_date)) {
    // Fetch in-store quantity for this date
    $product_id = $_GET["id"]; // Assuming you're receiving product ID via GET method
    $instore_query = mysqli_query($connection, "SELECT SUM(stock_qty) AS total_instore FROM purchases WHERE DATE(date_time) = '$current_date' &&  product_id = '$product_id'");
    $instore_data = mysqli_fetch_assoc($instore_query);
    $instore_qty = $instore_data['total_instore'] ?? 0;

    // Fetch sales quantity for this date
    $sales_query = mysqli_query($connection, "SELECT SUM(product_quantity) AS total_sales FROM log_user_sales WHERE DATE(date_time) = '$current_date' &&  product_id = '$product_id'");
    $sales_data = mysqli_fetch_assoc($sales_query);
    $sales_qty = $sales_data['total_sales'] ?? 0;

    // Calculate closing quantity
    $closing_qty = $opening_qty + $instore_qty - $sales_qty;

    // Display the data in the table
    echo "<tr class='text-center'>";
    echo "<td>$current_date</td>";
    echo "<td>$opening_qty</td>";
    echo "<td>$instore_qty</td>";
    echo "<td>$sales_qty</td>";
    
    echo "<td>$closing_qty</td>";
    echo "</tr>";
// Check if data for this date already exists in the daily_closing table
    $existing_data_query = mysqli_query($connection, "SELECT * FROM daily_closing WHERE date_time = '$current_date' AND product_id = '$product_id'");
    $existing_data = mysqli_fetch_assoc($existing_data_query);

    if ($existing_data) {
    // Update existing record
    mysqli_query($connection, "UPDATE daily_closing 
                                SET closing_qty = $closing_qty,
                                    instore = $instore_qty,
                                    sales = $sales_qty,
									open_qty = $opening_qty 
                                WHERE date_time = '$current_date' 
                                AND product_id = '$product_id'");
} else {
    // Insert the closing quantity into the database for the current day
    mysqli_query($connection, "INSERT INTO daily_closing (date_time, product_id, name, open_qty, instore, sales, closing_qty,user_name,user_role,outlet_name,outlet_address)
	VALUES ('$current_date', '$product_id', '$name', $opening_qty, $instore_qty, $sales_qty, $closing_qty, $user_name, $user_role, $outlet_name, $outlet_address)");
}
    // Move to the next day
    $current_date = date('Y-m-d', strtotime($current_date . ' +1 day'));

    // Set opening quantity for the next day as the current day's closing quantity
    $opening_qty = $closing_qty;
}
*/
?>




                <!--</table>-->
                
                
                
                
             <div class="container ">
        <div class="row" style="padding:20px;background:#fff; box-shadow: 0px 0px 5px 2px #CCC; border-radius:10px;">
            <div class="col-sm-12" style="padding:20px;">
            <table class="table table-hover"  >
            <tr style="color:#8A1218;padding:20px;">
            <td style="font-weight:600;">Opening Cash</td>
            <td style="text-align:right; font-size:19px; font-weight:600;"><?php echo isset($open_cash) ? "Rs ".$open_cash.".00" : ""; ?></td>
            </tr>
            <tr>
            <td style="font-weight:600;">Cash Sales</td>
            <td style="text-align:right; font-size:19px; font-weight:600;"><?php echo isset($total_sales) ? "Rs ".$total_sales.".00" : ""; ?></td>
            </tr>
            <tr>
            <td style="font-weight:600;">Cash Out</td>
            <td style="text-align:right; font-size:19px; font-weight:600;"><?php echo isset($totalAmount) ? "Rs ".$totalAmount.".00" : ""; ?></td>
            </tr> 
            <tr>
            <td style="font-weight:600;">Closing Cash</td>
            <td style="text-align:right; font-size:19px; font-weight:600;"><?php echo isset($close_amount) ? "Rs ".$close_amount.".00" : ""; ?></td>
            </tr>
            <td style="font-weight:600;">Cash Drawer Amount</td>
            <td style="text-align:right; font-size:19px; font-weight:600;"><input type="text" name="drawer_amount" 
            placeholder="Rs" style="width:220px; height:35px; border:1px solid #999;box-shadow: 0px 0px 4px 1px #CCC; border-radius:5px;"></td>
            </tr>           
            </table>
            </div>
            
            
        </div>
        <br />
        <div class="row">
        
         <div class="col-sm-12">
         
         
         <textarea placeholder="'Remarks:'"  name="remarks"  class="form-control" style="height:150px;"></textarea>
         <br />
         <button class="btn btn-dark" type="submit" name="closedrawer"> <i class="fa fa-cash-register"></i>&nbsp;Close Cash Drawer
         </button>
        
         </div>
         
        </div>
        
    </div>
                
                
           
        </div>
    </div>
    <p></p>
</div>






    <div id="tab2" class="tab">
        <h2>IN-Store</h2>
        <div class="container">
           <div class="row">
            
      <div class="col-sm-7"></div>
            
            <div class="col-sm-4">
             
    
            <br />
            </div>
            <div class="col-sm-1"><button class="btn btn-dark" id="downloadButton2"><i class="fa fa-download"></i></button></div>
            </div>
           
           <br />
             <div class="col-sm-12">
               <table class="table table-stripped text-center" id="instoreviewTable">
                <tr style="background:#881218; color:#fff;">
                <td>Date</td>
                <td>ID</td>
                <th>Name</th>
                <td>Unit</td>
                <td>Qty`</td>
                <td>Amount</td>
                </tr>
               
               
               <?php
			   $name = $_GET["name"];
               $rec = mysqli_query($connection,"select * from purchases where name = '".$name."'");
			   
			   while($row = mysqli_fetch_array($rec)){
			   ?>
               
               <tr>
               <td><?php echo $row["date_time"];  ?></td>
               <td><?php echo $row["product_id"];  ?></td>
               <td class="text-capitalize"><?php echo $row["name"];  ?></td>
               <td><?php echo $row["unit_pr"];  ?></td>
               <td><?php echo $row["stock_qty"];  ?></td>
               <td><?php echo $row["price"];  ?></td>
               </tr>
               <?php 
			   }
			   ?>
               
               </table>
             </div>
           </div>
          </div>
    </div>
    <div id="tab3" class="tab">
        <h2>Sales</h2>
        <div class="container">
           <div class="row">
            
            <div class="col-sm-7"></div>
            
            <div class="col-sm-4">
             
    
            <br />
            </div>
            <div class="col-sm-1"><button class="btn btn-dark" id="downloadButton3"><i class="fa fa-download"></i></button></div>
           </div>
           <br />
             <div class="col-sm-12">
               <table class="table table-stripped text-center" id="salesviewTable">
                <tr style="background:#881218; color:#fff;">
                <td>Order ID</td>
                <td>Date</td>
                <td>ID</td>
                <td>Name</td>
                <td>Price</td>
                <td>Qty`</td>
                <td>Amount</td>
                <td>Tax</td>
                <td>Total Amount</td>
                </tr>
               
              <?php
			  $id = $_GET["id"];
               $rec2 = mysqli_query($connection,"select * from sales  where product_id = '".$id."'");
			   
			   while($row2 = mysqli_fetch_array($rec2)){
			   ?>
               <tr>
               <td><?php echo $row2["order_id"];  ?></td>
               <td><?php echo $row2["date_time"];  ?></td>
               <td><?php echo $row2["product_id"];  ?></td>
               <td><?php echo $row2["product_name"];  ?></td>
               <td><?php echo $row2["product_price"];  ?></td>
               <td><?php echo $row2["product_quantity"];  ?></td>
               <td><?php echo $row2["product_total"];  ?></td>
               <td><?php echo $row2["tax_amount"];  ?></td>
               <td><?php echo $row2["total_amount"];  ?></td>
               </tr>
               <?php } ?>
               </table>
             </div>
           </div>
          </div>
    </div>
    
    </div>
    
    
    
</div>
  
  
  
  
 
    
    
</div>    
</body>
<!-- JavaScript libraries -->
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<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>
<!-- FileSaver.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>
<!-- TableExport.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/TableExport/5.2.0/js/tableexport.min.js"></script>

<script>
        function toggleSidebar() {
      document.getElementById("sidebar").classList.toggle("hide");
    }
	
document.getElementById("downloadButton").addEventListener("click", function () {
        exportTableToCSV();
    });
	
	document.getElementById("downloadButton2").addEventListener("click", function () {
        exportTableToCSV2();
    });
	
	document.getElementById("downloadButton3").addEventListener("click", function () {
        exportTableToCSV3();
    });

    function exportTableToCSV() {
        var csv = [];
        var rows = document.querySelectorAll("#overviewTable tr");

        for (var i = 0; i < rows.length; i++) {
            var row = [], cols = rows[i].querySelectorAll("td, th");

            for (var j = 0; j < cols.length; j++) 
                row.push(cols[j].innerText);

            csv.push(row.join(","));
        }

        var csvContent = "data:text/csv;charset=utf-8," + csv.join("\n");
        var encodedUri = encodeURI(csvContent);
        var link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "table_data.csv");
        document.body.appendChild(link);
        link.click();
    }
	    function exportTableToCSV2() {
        var csv = [];
        var rows = document.querySelectorAll("#instoreviewTable tr");

        for (var i = 0; i < rows.length; i++) {
            var row = [], cols = rows[i].querySelectorAll("td, th");

            for (var j = 0; j < cols.length; j++) 
                row.push(cols[j].innerText);

            csv.push(row.join(","));
        }

        var csvContent = "data:text/csv;charset=utf-8," + csv.join("\n");
        var encodedUri = encodeURI(csvContent);
        var link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "table_data.csv");
        document.body.appendChild(link);
        link.click();
    }
	    function exportTableToCSV3() {
        var csv = [];
        var rows = document.querySelectorAll("#salesviewTable tr");

        for (var i = 0; i < rows.length; i++) {
            var row = [], cols = rows[i].querySelectorAll("td, th");

            for (var j = 0; j < cols.length; j++) 
                row.push(cols[j].innerText);

            csv.push(row.join(","));
        }

        var csvContent = "data:text/csv;charset=utf-8," + csv.join("\n");
        var encodedUri = encodeURI(csvContent);
        var link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "table_data.csv");
        document.body.appendChild(link);
        link.click();
    }

// Live search functionality
document.getElementById('searchInput').addEventListener('input', function() {
    var filter, table, tr, td, i, txtValue;
    filter = this.value.toUpperCase();
    table = document.getElementById("overviewTable");
    tr = table.getElementsByTagName("tr");
    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0]; // Change index based on column position
        if (td) {
            txtValue = td.textContent || td.innerText;
            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
});
    // Function to switch between tabs
    function openTab(evt, tabName) {
        // Get all elements with class="tab" and hide them
        var tabs = document.getElementsByClassName("tab");
        for (var i = 0; i < tabs.length; i++) {
            tabs[i].style.display = "none";
        }

        // Get all elements with class="tab-button" and remove the class "active"
        var tabButtons = document.getElementsByClassName("tab-button");
        for (var i = 0; i < tabButtons.length; i++) {
            tabButtons[i].classList.remove("active");
        }

        // Show the current tab, and add an "active" class to the button that opened the tab
        document.getElementById(tabName).style.display = "block";
        evt.currentTarget.classList.add("active");
    }
</script>


</html>