<?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'];
}
@$supplier_name = $_GET["emp_name"];



//-------------------------------------
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["emp_adv"])){
$date_time32 = date("Y-m-d");
$empName = $_POST["empName"];
$emp_adv = $_POST["emp_adv1"];	
$paid_by = $_POST["paid_by"];	
$emp_desc = $_POST["emp_desc"];
$date = date("Y-m-d");
 mysqli_query($connection,"insert into adv_salari(emp_name,emp_adv,emp_desc,paid_by,date_time)
 values('".$empName."','".$emp_adv."','".$emp_desc."','".$paid_by."','".$date_time32."')");
 
  mysqli_query($connection,"insert into incash(name_detail,amount,cr_id,paid_by,login_user,user_role,outlet_name,outlet_address,date_time)
 values('".$empName."','".$emp_adv."','','$paid_by','".$userName."','".$userRole."','".$outlet_name."','".$outlet_address."','".$date."')");
}
//--------------------------------------

//-------------------------------------
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["paid_emp"])){
$dateTime= date("Y-m-d");
$emp_name = $_POST["emp_name"];
$emp_paid = $_POST["emp_paid"];
$emp_des = $_POST["emp_des"];

	

 mysqli_query($connection,"insert into salari_paid(emp_name,emp_paid,emp_des,date_time)
 values('".$emp_name."','".$emp_paid."','".$emp_des."','".$dateTime."')");
 

}
//--------------------------------------

//-------------------------------------
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["open_emp"])){
$dateTime= date("Y-m-d");
$emp_name1 = $_POST["emp_name1"];
$emp_amount = $_POST["emp_amount"];	
$amount_type = $_POST["amount_type"];

 mysqli_query($connection,"insert into opening_salari(emp_name1,emp_amount,amount_type,date_time)
 values('".$emp_name1."','".$emp_amount."','".$amount_type."','".$dateTime."')");
}
//--------------------------------------

//-------------------------------------
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["close_emp"])) {
    $dateTime = date("Y-m-d");
    $emp_name2 = $_POST["emp_name2"];
    $paid = $_POST["paid"];    
    $payable = $_POST["payable"];
    $closing = $_POST["closing"];
    $date = date("Y-m-d");

    // Check if the row exists
    $checkQuery = "SELECT * FROM salari_close WHERE emp_name = '$emp_name2'";
    $result = mysqli_query($connection, $checkQuery);

    if (mysqli_num_rows($result) > 0) {
        // Row exists, update the record
        $updateQuery = "UPDATE salari_close 
                        SET paid = '$paid', payable = '$payable', closing = '$closing', date_time = '$date' 
                        WHERE emp_name = '$emp_name2'";
        mysqli_query($connection, $updateQuery);
    } else {
        // Row doesn't exist, insert a new record
        $insertQuery = "INSERT INTO salari_close (emp_name, paid, payable, closing, date_time) 
                        VALUES ('$emp_name2', '$paid', '$payable', '$closing', '$date')";
        mysqli_query($connection, $insertQuery);
    }

    // Redirect to salari_detail.php
    echo "<script type='text/javascript'>window.location.href = 'salari_detail.php?emp_name=$emp_name2';</script>";
}


// Fetch the opening salary details based on the employee name.
$sal = mysqli_query($connection, "SELECT * FROM opening_salari WHERE emp_name1 = '$supplier_name'");
$sal_g = mysqli_fetch_array($sal);

// Adjust emp_amount based on the amount_type.
$emp_amount = (int)$sal_g["emp_amount"];
if ($sal_g["amount_type"] === 'dr') {
    $emp_amount = -$emp_amount; // Make the amount negative for 'dr'
}

// Get the sum of employee advances (debits).
$dr = mysqli_query($connection, "SELECT SUM(emp_adv) AS emp_dr FROM adv_salari WHERE emp_name = '$supplier_name'");
$dr_get = mysqli_fetch_array($dr);

// Get the sum of employee payments (credits).
$cr = mysqli_query($connection, "SELECT SUM(emp_paid) AS emp_cr FROM salari_paid WHERE emp_name = '$supplier_name'");
$cr_get = mysqli_fetch_array($cr);
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>Whole Sale Retail</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;
		}
		
		/* Basic styling */
      .tab {
        display: none;
        padding: 20px;
    }
    .active {
        display: block;
    }
    .tab-buttons {
        display: flex;
    }
    .tab-button {
        cursor: pointer;
        padding: 10px 10px;
        background-color: #ffff;
        border: 1px solid #0A5064;
        border-radius: 5px 5px 0 0;
        margin-right: 5px;
		color:#212529;
    }
    .tab-button.active {
        background-color: #212529;
		color:#fff;
    }

    /* Background colors for tab content */
    #tab1 {
        background-color: #fff;
		color:#212529;
		padding:20px;
    }
    #tab2 {
        color:#212529;
		background-color: ;
    }
    #tab3 {
		color:#212529;
        background-color: ;
    }
  </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="">

<br />
<div class="container">
<div class="row">
<div class="col-sm-9">
<h3 style="color:#212529; font-weight:700;">Employee Salary Detail</h3>
</div>
<div class="col-sm-3" style="padding:10px; border-radius:7px; font-size:18px; 
border:1px solid #0A4657; background:#0A4657; color:#fff; 
">
<center>
<h5>Employee Detail</h5>

<?php echo 'Name : '.$supplier_name; ?>
<br />

</center>
</div>

<div class="col-sm-8"></div>
<div class="col-sm-4">
<br>
<a href="view_salari.php"><button type="button" class="btn btn-dark "><i class="fa fa-arrow-left"></i></button></a>
 <button type="button" class="btn btn-dark  " data-toggle="modal" data-target="#addopenModal">
                Open
            </button>
<button type="button" class="btn btn-dark " data-toggle="modal" data-target="#addPurchaseModal">
                 Paid
            </button>
            <button type="button" class="btn btn-dark " data-toggle="modal" data-target="#addpaidModal">
                Payable
            </button>
           
</div>
</div>
</div>


<div class="container">
 <div class="row">
 <div class="col-sm-1"></div>
 <div class="col-sm-10">
 <!-- Bootstrap Tab Navigation -->
<div class="tab-buttons">
    <div class="tab-button active" onclick="openTab(event, 'tab1')">Overview</div>
    <div class="tab-button" onclick="openTab(event, 'tab2')">Paid</div>
    <div class="tab-button" onclick="openTab(event, 'tab3')">Payable</div>

</div>
<!-- Tab Content -->
<div class="tab-container">

    <div id="tab1" class="tab active"  >
  
 
  <h4>Overview</h4>
     
     
     <div class="container" style="padding:20px; border-radius:14px; box-shadow: 0px 0px 5px 2px #ccc;">
     <br />
    <form method="post" action="salari_detail.php?emp_name=<?php echo $supplier_name; ?>" enctype="multipart/form-data">
    <table class="table table-stripped table-hover">
        <tr>
            <td style="font-size:18px;font-weight:600;color:#A31218;">Opening</td>
            <td class="text-right" style="font-weight:600; font-size:18px; color:#A31218;">
                <?php echo ' Rs ' . $emp_amount; ?>
            </td>
        </tr>
        <tr>
            <td style="font-size:18px;font-weight:600;">Payable</td>
            <td class="text-right" style="font-weight:600;font-size:18px;">
                Rs <?php echo $cr_get["emp_cr"]; ?>
            </td>
        </tr>
        <tr>
            <td style="font-size:18px;font-weight:600;">Paid</td>
            <td class="text-right" style="font-weight:600; font-size:18px;">
                Rs <?php echo $dr_get["emp_dr"]; ?>
            </td>
        </tr>
        <tr>
            <td style="font-size:18px;font-weight:600;">Closing</td>
            <td class="text-right" style="font-weight:600;font-size:18px;">
                Rs <?php
                    // Calculate the closing balance
                    $close = $emp_amount - (int)$dr_get["emp_dr"] + (int)$cr_get["emp_cr"];
                    echo $close;
                ?>
            </td>
        </tr>
    </table>

    <input type="hidden" name="emp_name2" value="<?php echo $supplier_name; ?>">
    <input type="hidden" name="paid" value="<?php echo $dr_get["emp_dr"]; ?>">
    <input type="hidden" name="payable" value="<?php echo $cr_get["emp_cr"]; ?>">
    <input type="hidden" name="closing" value="<?php echo $close; ?>">
    <button type="submit" class="btn btn-dark" name="close_emp" style="margin-bottom:20px;">Save</button>
</form>
    </div>
</div>
    <!-- Closing Info Tab -->
    <div <div id="tab2" class="tab">
        <h3 class="mb-3">Paid</h3>
        <br>
        <div class="row">
              <div class="col-sm-4">
    <label for="startDate">Start Date:</label>
    <input  class="form-control" style="width:250px;" type="date" id="startDatePOS">
    </div>
    <div class="col-sm-4">
    <label for="endDate">End Date:</label>
    <input class="form-control" style="width:250px;" type="date" id="endDatePOS">
</div>
<div class="col-sm-4">
  <button type="button" class="btn btn-dark" style="float:right;margin-top:30px;" onclick="downloadTableData('paidTableBody', 'Paid_Data.xlsx')">Download</button>
</div>
</div>
<hr>
        
         <table class=" table table-stripped text-center table-sm ">
  <tr class="bg-dark text-white">
    <td>Date</td>
    <td>Description</td>
    <td>Amount(Rs)</td>
    <td>Method</td>
    
  </tr>
  <tbody id="paidTableBody">
  <?php
  // Using a UNION to simulate FULL OUTER JOIN
  $query1 = "
    select * from adv_salari where emp_name = '$supplier_name'
  ";

  $result1 = mysqli_query($connection, $query1);

  while ($row1 = mysqli_fetch_array($result1)) {
    $date_time1 = $row1["date_time"];
    $emp_desc = $row1["emp_desc"] ? $row1["emp_desc"] : '-';
    $emp_adv = $row1["emp_adv"] ? ' ' . $row1["emp_adv"] : '-';
	$paid_by = $row1["paid_by"] ? '' . $row1["paid_by"] : '-';
	
  
  ?>
  <tr>
    <td><?php echo $date_time1; ?></td>
    <td><?php echo $emp_desc; ?></td>
    <td><?php echo $emp_adv; ?></td>
    <td class="text-capitalize"><?php echo $paid_by; ?></td>
   
   
      </tr>
  <?php
  }
  ?>
  </tbody>
</table>
    </div>
    
    <div <div id="tab3" class="tab">
        <h3>Payable</h3>
        <br>
        <div class="row">
              <div class="col-sm-4">
    <label for="startDate">Start Date:</label>
    <input  class="form-control" style="width:250px;" type="date" id="startDatePR">
    </div>
    <div class="col-sm-4">
    <label for="endDate">End Date:</label>
    <input class="form-control" style="width:250px;" type="date" id="endDatePR">
</div>
<div class="col-sm-4">
      <button type="button" class="btn btn-dark" style="float:right;margin-top:30px;" onclick="downloadTableData('payableTableBody', 'Payable_Data.xlsx')">Download</button>
</div>

</div>
<hr>
    <table class=" table table-stripped text-center table-sm ">
  <tr class="bg-dark text-white">
    <td>Date</td>
    <td>Description</td>
    <td>Amount(Rs)</td>
    <td>By.</td>
    
  </tr>
  <tbody id="payableTableBody">
  <?php
  // Using a UNION to simulate FULL OUTER JOIN
  $query = "
    select * from salari_paid where emp_name = '$supplier_name'
  ";

  $result = mysqli_query($connection, $query);

  while ($row = mysqli_fetch_array($result)) {
    $date_time = $row["date_time"];
    $emp_desc = $row["emp_des"] ? $row["emp_des"] : '-';
    $emp_adp = $row["emp_paid"] ? ' ' . $row["emp_paid"] : '-';
	 $user = $userName;
  
  ?>
  <tr>
    <td><?php echo $date_time; ?></td>
    <td><?php echo $emp_desc; ?></td>
    <td><?php echo $emp_adp; ?></td>
     <td class="text-capitalize"><?php echo $user; ?></td>
   
      </tr>
  <?php
  }
  ?>
  </tbody>
</table>
    
    
       
    </div>
</div>
</div>
<div class="col-sm-1"></div>
 </div>
</div>

<div class="modal fade" id="addopenModal" tabindex="-1" role="dialog" 
            aria-labelledby="addopenModalLabel" aria-hidden="true" style="margin-top:80px;">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title text-capitalize" id="addopenModalLabel">Add Opening Amount</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <!-- Form for adding purchase -->
                            <form method="post" action="salari_detail.php?emp_name=<?php echo $supplier_name; ?>" enctype="multipart/form-data">
                            
                                <input type="text" name="emp_name1" value="<?php echo $supplier_name; ?>" 
                                style="background:#0A4657; color:#fff;" class="form-control" readonly />
                                <br />
                                <input type="text" name="emp_amount" placeholder="Amount" class="form-control" />
                               
                               <br />
                                <select name="amount_type" class="form-control">
                                <option value="">Select type</option>                                
                                    <option value="dr">Recieable</option>
                                    <option value="cr">Payable</option>
                                   
                                </select>
                                <br />
                               
                                <button type="submit" name="open_emp"  class="btn btn-dark">Enter</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
<div class="modal fade" id="addPurchaseModal" tabindex="-1" role="dialog" 
            aria-labelledby="addPurchaseModalLabel" aria-hidden="true" style="margin-top:80px;">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title text-capitalize" id="addPurchaseModalLabel">Add Salary</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <!-- Form for adding purchase -->
                            <form method="post" action="salari_detail.php?emp_name=<?php echo $supplier_name; ?>" enctype="multipart/form-data">
                            
                                <input type="text" name="empName" value="<?php echo $supplier_name; ?>" 
                                style="background:#0A4657; color:#fff;" class="form-control" readonly />
                                <br />
                                <input type="text" name="emp_desc" placeholder="Description" class="form-control" />
                                <br />
                                <input type="text" name="emp_adv1" placeholder="Amount" class="form-control" />
                               <br />
                                <select name="paid_by" class="form-control">
                                <option value="">Select Method</option>                                
                                    <option value="cash">Cash</option>
                                    <option value="bank1">Bank 1</option>
                                    <option value="bank2">Bank 2 </option>
                                    <option value="bank3">Bank 3</option>
                                    <option value="other">Other</option>
                                </select>
                                <br />
                               
                                <button type="submit" name="emp_adv"  class="btn btn-dark">Enter</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal fade" id="addpaidModal" tabindex="-1" role="dialog" 
            aria-labelledby="addpaidModalLabel" aria-hidden="true" style="margin-top:80px;">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title text-capitalize" id="addpaidModalLabel">Add Paid</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <!-- Form for adding purchase -->
                            <form method="post" action="salari_detail.php?emp_name=<?php echo $supplier_name; ?>" enctype="multipart/form-data">
                            
                                <input type="text" name="emp_name" value="<?php echo $supplier_name; ?>" 
                                style="background:#0A4657; color:#fff;" class="form-control" readonly />
                                <br />
                                <input type="text" name="emp_paid" placeholder="Amount" class="form-control" />
                                <br />
                                 <input type="text" name="emp_des" placeholder="Description" class="form-control" />
                                <br />
                              
                               
                                <button type="submit" name="paid_emp"  class="btn btn-dark">Enter</button>
                            </form>
                        </div>
                    </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>
// Download function to export table data as an Excel file
function downloadTableData(tableBodyId, filename) {
    const tableBody = document.getElementById(tableBodyId);
    const rows = Array.from(tableBody.querySelectorAll("tr"));
    const data = [];

    // Loop through each row and extract cell data
    rows.forEach(row => {
        const rowData = Array.from(row.querySelectorAll("td")).map(cell => cell.innerText);
        data.push(rowData);
    });

    // Create workbook and worksheet, then download as Excel
    const ws = XLSX.utils.aoa_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    XLSX.writeFile(wb, filename);
}

// Filter function for Paid table
function filterPaidTableByDate() {
    const startDate = new Date(document.getElementById('startDatePOS').value);
    const endDate = new Date(document.getElementById('endDatePOS').value);
    const rows = document.querySelectorAll('#paidTableBody tr');

    rows.forEach(row => {
        const dateCell = row.cells[0].innerText;
        const rowDate = new Date(dateCell);

        // Show row if within date range, otherwise hide it
        if ((!isNaN(startDate) && rowDate < startDate) || (!isNaN(endDate) && rowDate > endDate)) {
            row.style.display = 'none';
        } else {
            row.style.display = '';
        }
    });
}

// Filter function for Payable table
function filterPayableTableByDate() {
    const startDate = new Date(document.getElementById('startDatePR').value);
    const endDate = new Date(document.getElementById('endDatePR').value);
    const rows = document.querySelectorAll('#payableTableBody tr');

    rows.forEach(row => {
        const dateCell = row.cells[0].innerText;
        const rowDate = new Date(dateCell);

        // Show row if within date range, otherwise hide it
        if ((!isNaN(startDate) && rowDate < startDate) || (!isNaN(endDate) && rowDate > endDate)) {
            row.style.display = 'none';
        } else {
            row.style.display = '';
        }
    });
}

// Add event listeners for Paid table date inputs
document.getElementById('startDatePOS').addEventListener('change', filterPaidTableByDate);
document.getElementById('endDatePOS').addEventListener('change', filterPaidTableByDate);

// Add event listeners for Payable table date inputs
document.getElementById('startDatePR').addEventListener('change', filterPayableTableByDate);
document.getElementById('endDatePR').addEventListener('change', filterPayableTableByDate);

 // 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>
   <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>