<?php
include("db/cn.php");
include("common/tx.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
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'];
}
ob_end_flush();

// Fetch employee list for dropdown
$employees = mysqli_query($connection, "SELECT DISTINCT emp_name FROM adv_salari");

if (isset($_POST['filter'])) {
    $emp_name = $_POST['supplier'];
    $startDate = $_POST['startDate'];
    $endDate = $_POST['endDate'];

    // Query to fetch the last opening salary before or on the exact start date
    $query_opening = "SELECT emp_amount AS opening, amount_type, date_time AS trans_date 
                      FROM opening_salari 
                      WHERE emp_name1 = '$emp_name' 
                      AND date_time >= '$startDate'
                      ORDER BY date_time DESC 
                      LIMIT 1";

    $result_opening = mysqli_query($connection, $query_opening);
    $opening_row = mysqli_fetch_assoc($result_opening) ?? []; // Ensure $opening_row is an array

// If no opening balance is found, set the opening salary to zero
$opening_salary = $opening_row['opening'] ?? 0;

// Adjust the opening salary based on the amount_type (dr or cr)
if (($opening_row['amount_type'] ?? '') === 'dr') {
    $opening_salary = -abs($opening_salary); // Debit means negative opening
} elseif (($opening_row['amount_type'] ?? '') === 'cr') {
    $opening_salary = abs($opening_salary); // Credit means positive opening
}

    // Fetch payable transactions for the employee within the date range
    $query_payable = "SELECT date_time AS trans_date, emp_adv AS amount, 'Paid' AS description 
                      FROM adv_salari 
                      WHERE emp_name = '$emp_name' AND date_time >= '$startDate' AND date_time <= '$endDate'";
    $payable_transactions = mysqli_query($connection, $query_payable);

    // Fetch paid transactions for the employee within the date range
    $query_paid = "SELECT date_time AS trans_date, emp_paid AS amount, 'Payable' AS description 
                   FROM salari_paid 
                   WHERE emp_name = '$emp_name' AND date_time >= '$startDate' AND date_time <= '$endDate'";
    $paid_transactions = mysqli_query($connection, $query_paid);

    // Initialize totals
    $total_payable = 0;
    $total_paid = 0;
    $running_balance = $opening_salary; // Start with adjusted opening balance

    // Combine opening, payable, and paid transactions into one array
    $transactions = [];

    // Add the opening balance to the transactions array with the start date
    $transactions[] = [
        'trans_date' => $startDate,
        'description' => 'Opening Balance',
        'amount' => $opening_salary
    ];

    // Add all payable transactions
    while ($row = mysqli_fetch_assoc($payable_transactions)) {
        $transactions[] = $row;
    }

    // Add all paid transactions
    while ($row = mysqli_fetch_assoc($paid_transactions)) {
        $transactions[] = $row;
    }

    // Sort transactions by date
    usort($transactions, function($a, $b) {
        return strcmp($a['trans_date'], $b['trans_date']);
    });

    // Logic to carry over the closing balance as the opening of the next day
    $last_date = null;  // Track the date of the last processed transaction
    $carried_balance = $running_balance; // Track the carried-over balance
    $final_transactions = []; // Store the final sequence with balance carried over

    foreach ($transactions as $transaction) {
        $current_date = $transaction['trans_date'];

        // If the date changes, insert a new opening balance for the next day
        if ($last_date && $current_date != $last_date) {
            $next_day = date('Y-m-d', strtotime($last_date . ' +1 day'));
            $final_transactions[] = [
                'trans_date' => $next_day,
                'description' => 'Opening Balance',
                'amount' => 0, // Opening balance does not have an amount, just the balance carried over
                'balance' => $carried_balance
            ];
        }

        // Update the running balance based on the transaction type
        if ($transaction['description'] === 'Payable') {
            $total_payable += $transaction['amount'];
            $carried_balance += $transaction['amount'];
        } elseif ($transaction['description'] === 'Paid') {
            $total_paid += (int)$transaction['amount'];
            $carried_balance -= (int)$transaction['amount'];
        }

        // Add the transaction to the final list, including the running balance
        $transaction['balance'] = $carried_balance;
        $final_transactions[] = $transaction;

        // Update the last_date for the next iteration
        $last_date = $current_date;
    }
}
?>
<!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><?php echo $tx; ?></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>
 #table-container-wrapper {
    max-height: 460px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}

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, tr{
	  	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-fluid mt-5">
            <div class="row">
        <div class="col-sm-3">
    <h3 style="font-weight:700; color:#060606;">Salary Report</h3>
        </div>
        <div class="col-sm-6"></div>
        <div class="col-sm-3">

        </div>
    </div>
        <br>
            <form method="post">
                <div class="row">
                    <div class="col-md-3">
    <div class="form-group">
        <label for="supplier">Employee Name:</label>
        <select class="form-control" name="supplier" required>
            <option value="">Select Employee</option>
            <?php while($row = mysqli_fetch_array($employees)): ?>
                <option class="text-capitalize" value="<?= $row['emp_name'] ?>" <?= isset($emp_name) && $emp_name == $row['emp_name'] ? 'selected' : '' ?>>
                    <?= $row['emp_name'] ?>
                </option>
            <?php endwhile; ?>
        </select>
    </div>
</div>

                </div>

                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="startDate">Start Date:</label>
                            <input type="date" class="form-control" name="startDate" required>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="endDate">End Date:</label>
                            <input type="date" class="form-control" name="endDate" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                    <div class="form-group">
                        
                        <button type="submit" class="btn btn-dark" name="filter" style="margin-top:30px;">Filter</button>
                         <button id="downloadExcel" type='button' class="btn btn-dark " style="margin-top:30px;">Download </button>
                        
                         <a href="report_salari.php"><button type="button" class="btn btn-dark"  
                         style="margin-top:30px;"><i class="fas fa-sync-alt fa-1x"></i></button></a>
                          <button id="downloadPdf" type='button' class="btn btn-danger " 
                         style="margin-top:30px;"><i class="fas fa-file fa-1x"></i> Download Pdf</button>


                    </div>
                    
                </div>
                </div>
<br>

              <div id='report'>
                  
                <!-- Show selected employee name -->
                <?php if(isset($emp_name)): ?>
                    <h5 class="text-center" style="background:#0A4657;color:#fff; padding:20px; border-radius:10px;">
                        Salary Ledger Report: <strong style="text-transform:capitalize;"><?= $emp_name ?></strong></h5>
                <?php endif; ?>

                <?php if(isset($final_transactions)): ?>
                    <div class="col-sm-12" id="table-container-wrapper">
<table id="patientTable" class="table table-striped table-hover text-center table-sm bg-white"> 
    <thead>
        <tr class="bg-dark text-white">
            <th>Date</th>
            <th>Description</th>
            <th>Debit Amount (Rs)</th>
            <th>Credit Amount (Rs)</th>
            <th>Balance (Rs)</th>
        </tr>
    </thead>
<tbody>
    <?php foreach ($final_transactions as $transaction): ?>
        <?php 
        // Initialize variables to hold debit (paid) and credit (payable) amounts
        $debitAmount = '';  // Paid amount goes to Debit
        $creditAmount = ''; // Payable amount goes to Credit
        
        // Special handling for the opening balance
        if ($transaction['description'] === 'Opening Balance') {
            // Check the amount_type: 'dr' goes to Debit, 'cr' goes to Credit
            if (isset($opening_row['amount_type'])) {
                if ($opening_row['amount_type'] === 'dr') {
                    $debitAmount = number_format(abs((float)$transaction['amount']), 2); // 'dr' shows in Debit
                } elseif ($opening_row['amount_type'] === 'cr') {
                    $creditAmount = number_format(abs((float)$transaction['amount']), 2); // 'cr' shows in Credit
                }
            }
        } else {
            // Assign the correct amount to the appropriate column based on the description for paid and payable
            if ($transaction['description'] === 'Paid') {
                $debitAmount = is_numeric($transaction['amount']) ? number_format((float)$transaction['amount'], 2) : '0.00';  // Paid amount in Debit
            } elseif ($transaction['description'] === 'Payable') {
                $creditAmount = is_numeric($transaction['amount']) ? number_format((float)$transaction['amount'], 2) : '0.00'; // Payable amount in Credit
            }
        }

        // Display the transaction row
        ?>
        <tr style="color:#060606;">
            <td><?= htmlspecialchars($transaction['trans_date']) ?></td>
            <td><?= htmlspecialchars($transaction['description']) ?></td>
            <td><?= $debitAmount ?></td>
            <td><?= $creditAmount ?></td>
            <td><?= is_numeric($transaction['balance']) ? number_format((float)$transaction['balance'], 2) : '0.00' ?></td>
        </tr>
    <?php endforeach; ?>
</tbody>


</table>





</div>


                    <div class="row">
                        <div class="col-sm-12">
                            <table class="table bg-white" style="color:#060606;">
                                <tfoot>
                                    <tr>
                                        <th>Opening Salary:</th>
                                        <td>Rs <?= number_format($opening_salary, 2) ?></td>
                                    </tr>
                                    <tr>
                                        <th>Total Payable:</th>
                                        <td>Rs <?= number_format($total_payable, 2) ?></td>
                                    </tr>
                                    <tr>
                                        <th>Total Paid:</th>
                                        <td>Rs <?= number_format($total_paid, 2) ?></td>
                                    </tr>
                                    <tr>
                                        <th>Final Balance:</th>
                                        <td>Rs <?= number_format($carried_balance, 2) ?></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                <?php endif; ?>
              </div>

            </form>
        </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 src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<!-- JavaScript for exporting the table data to Excel -->
<script>
    document.getElementById('downloadExcel').addEventListener('click', function() {
        // Get the table element
        var table = document.getElementById('patientTable');

        // Clean the table to avoid potential issues with hidden rows or formatting
        var clone = table.cloneNode(true); // Clone the table
        var rows = clone.querySelectorAll('tr');

        // Remove hidden or empty rows if necessary
        rows.forEach(function(row) {
            if (row.style.display === 'none' || row.innerText.trim() === '') {
                row.remove();
            }
        });

        // Convert the table into a worksheet using SheetJS
        var workbook = XLSX.utils.table_to_book(clone, { sheet: "Patients" });

        // Export the Excel file with a proper name
        try {
            XLSX.writeFile(workbook, 'Salary_data.xlsx');
        } catch (error) {
            console.error("Error while writing the file: ", error);
            alert("Error generating Excel file. Please check if the SheetJS library is properly loaded.");
        }
    });
    
    
    document.getElementById("downloadPdf").addEventListener("click", function () {
    const { jsPDF } = window.jspdf;
    const report = document.getElementById("report");

    // Get current date & time
    const now = new Date();
    const formattedDateTime = now.toLocaleDateString() + " " + now.toLocaleTimeString();

    html2canvas(report, { scale: 2 }).then(canvas => {
        const imgData = canvas.toDataURL("image/png");
        const pdf = new jsPDF("p", "mm", "a4");
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (canvas.height * pdfWidth) / canvas.width;

        // Add report image shifted down for header
        pdf.addImage(imgData, "PNG", 0, 30, pdfWidth, pdfHeight);

        // === Header text ===
        pdf.setFont("helvetica", "bold");
        pdf.setFontSize(14);
        pdf.text("Salary Report", pdfWidth / 2, 12, { align: "center" });

        // Optional: Add print timestamp
        pdf.setFontSize(10);
        pdf.setFont("helvetica", "normal");
        pdf.text(`Printed: ${formattedDateTime}`, pdfWidth - 10, 20, { align: "right" });

        pdf.save("Salary-Report.pdf");
    });
});
    
</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>


    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>

</html>