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

// Fetch user session details
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'];
}

// Initialize search variables
$ledgercode = $_POST["ledgercode"] ?? "";
$description = $_POST["description"] ?? "";
$startperiod = $_POST["startperiod"] ?? "";
$endperiod = $_POST["endperiod"] ?? "";

// Build SQL Query for entries
$sql = "SELECT * FROM entries WHERE 1=1"; // Start with a base query

if (!empty($ledgercode)) {
    $sql .= " AND (ledger_code_dr = '$ledgercode' OR ledger_code_cr = '$ledgercode')";
}
if (!empty($description)) {
    $sql .= " AND (description_dr LIKE '%$description%' OR description_cr LIKE '%$description%')";
}
if (!empty($startperiod) && !empty($endperiod)) {
    $sql .= " AND (postdate >= '$startperiod' AND postdate <= '$endperiod')";
}

// Fetch the ledger opening balance based on the ledger code and description
$rec2 = mysqli_query($connection, 
    "SELECT obalance 
     FROM ledger 
     WHERE (ledgecode = '$ledgercode' OR description LIKE '%$description%')"
);

$openb = 0; // Default opening balance
if ($rec2 && mysqli_num_rows($rec2) > 0) {
    $row2 = mysqli_fetch_array($rec2);
    $openb = $row2["obalance"] ?? 0; // Set opening balance or default to 0
}

// Execute the query for entries
$rec3 = mysqli_query($connection, $sql);

// Handle the case when no results are returned
if (!$rec3 || mysqli_num_rows($rec3) === 0) {
    echo "No entries found for the given criteria.";
}
?>

<!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>Alfaizan Tax Consultant</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-dark{
	background:#0A4657;
	color:#fff;
	 border:1px #0A4657 solid;
	
	}  
.btn-dark: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:600;
    color:#000;
}
.form-control{
    font-weight:500;
    color:#000;
}
.btn-dark{
    color:#fff;
    font-weight:700;
}

#table-container{
    max-height:410px;
    overflow-y:auto;
}
  </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">
<div class="container" style="margin-top:20px;">
                     <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 " style="font-weight:700; color:#000;">Ledger View</h1>        
                    </div>
</div>     

<div class="">

                    <div class="container-fluid" >
                    <form action="report.php" method="post" enctype="multipart/form-data">
                    <div class="row" style="">
                    
                    <div class="col-sm-1"></div>
                    <div class="col-sm-10" style="border:#ccc solid 1px; padding:30px; border-radius:20px;background-color:#F2F2F2; box-shadow: 0px 4px 10px rgba(10, 79, 99, 0.5);">
                    <div class="row">
                        <div class="col-4">
                             <h5 class="text-black" style="color:#000; font-weight:700;">Description
                        <input type="text" name="description" id="description" class="form-control" style="width:280px;" placeholder="Enter Description" >
                        </div>
                        <div class="col-4">
                             <span style="color:#000;font-weight:700;">
                                 &nbsp;Ledger Code:&nbsp;
                        <input type="text" name="ledgercode" id="ledgercode" placeholder="Ledger Code " class="form-control" style="width:280px;"></span></h5>
                        </div>
                    </div>
                   
                   
                   
                    <p>Asset detial show data, this information will update soon</p>
                        <input type="hidden" id="opening_balance" value="<?php echo $openb; ?>">
                    <div class="row">
                    <div class="col-sm-7"> 
                   <h5 class="" style="color:#000;font-weight:700;">Opening Balance -------- <span class="opening-balance"><?php echo $openb; ?></span></h5>
                    <br>
                   <?php 
// Initialize variables to avoid undefined warnings
$ledgecode = $_POST['ledgercode'] ?? ''; // Assuming it's from user input
$description = $_POST["description"] ?? '';

// Your SQL query to fetch data from the database
$sql = "SELECT amount_dr FROM entries WHERE (ledger_code_dr = '$ledgecode' OR description_dr LIKE '%$description%')";

if($_POST){
    $startperiod = $_POST["startperiod"] ?? '';
    $endperiod = $_POST["endperiod"] ?? '';
    $sql = "SELECT amount_dr FROM entries WHERE (ledger_code_dr = '$ledgecode' OR description_dr LIKE '%$description%') 
            AND postdate >= '$startperiod' AND postdate <= '$endperiod'";
}

$rec1 = $connection->query($sql);

// Initialize total amounts
$totalAmountDr = 0;

// Check if there are rows in the result
if ($rec1->num_rows > 0) {
    // Loop through each row and accumulate totals
    while ($row1 = $rec1->fetch_assoc()) {
        $amountDr = $row1["amount_dr"];
        // Accumulate total amounts
        $totalAmountDr += (int)$amountDr;
    }
}

$sql2 = "SELECT amount_cr FROM entries WHERE (ledger_code_cr = '$ledgecode' OR description_cr LIKE '%$description%')";

if($_POST){
    $startperiod = $_POST["startperiod"] ?? '';
    $endperiod = $_POST["endperiod"] ?? '';
    $sql2 = "SELECT amount_cr FROM entries WHERE (ledger_code_cr = '$ledgecode' OR description_cr LIKE '%$description%') 
            AND postdate >= '$startperiod' AND postdate <= '$endperiod'";
}

$rec6 = $connection->query($sql2);

// Initialize total amounts
$totalAmountCr = 0;

// Check if there are rows in the result
if ($rec6->num_rows > 0) {
    // Loop through each row and accumulate totals
    while ($row5 = $rec6->fetch_assoc()) {
        $amountCr = $row5["amount_cr"];
        // Accumulate total amounts
        $totalAmountCr += (int)$amountCr;
    }
}

// Calculate final closing balance
$closing_final = $openb + $totalAmountDr;
$close = $closing_final - $totalAmountCr;
?>

                     

                   <span style="font-size:14px;color:#064F6D;">Total <b style="color:#000;">Debit(Dr)</b> During the Period -------- <span class="debit-total">0 Dr</span></span><br>
                    <span style="font-size:14px; color:#064F6D;">Total <b style="color:#000;">Credit(Cr)</b> During the Period -------- <span class="credit-total">0 Cr</span></span>
                    
                    <br><br>
                    </div>
                    <div class="col-sm-5">
<h5 class="" style="color:#000;font-weight:700;">Closing Balance -------- <span class="closing-balance">0</span></h5>
                    
                    </div>
                    </div>
                    <div class="row">
                     <div class="col-sm-3" style="color:#000; font-weight:700; ">
                     
                     
                      Period From<br>
                      Start From <br>                 
                    <input type="date" class="form-control" name="startperiod" />
                     </div>
                     <div class="col-sm-4" style="color:#000; font-weight:700; ">
                     <br>End From<br>
                    <input type="date" class="form-control" name="endperiod" />
                    
                     </div>
                     <div class="col-sm-5">
                     <br><br>
                     <button type="submit" class="btn btn-dark" style="width:120px; border-radius:20px;">Get</button>
                     <button id="downloadExcel" type="button" class="btn btn-dark" style="width:120px; border-radius:20px;">Download</button>
                     <a href="report.php" class="btn btn-dark" style="width:120px; border-radius:20px;"><i class="fas fa-sync fa-1x"></i></a>
                     </div>
                    
                    </div>
                    
                    
                    
                    </div>
                    <div class="col-sm-1"></div>
                    </div>
                    </div>
                    
                    <div class="row">
                    <div class="col-sm-1"></div>
                    <div class="col-sm-10">
                    <br><br>
                    
                   <p style="font-weight:700; font-size:23px;color:#000;"> Accounting Entries</p>

<div class="table-responsive" id="table-container">
<table id="ledgertable" class="table table-bordered text-center bg-white " style="color:#000; font-weight:700;">
    <thead>
    <tr class="" style="font-weight:800;">
        <th style="color:#fff;background:#064F6D;"> Entry No</th>
        <th style="color:#fff;background:#064F6D;">Ledger Code</th>
        <th style="color:#fff;background:#064F6D;">Ledger category</th>
        <th style="color:#fff;background:#064F6D;">Description</th>
        
        <th style="color:#fff;background:#064F6D;">Amount Dr</th>
        <th style="color:#fff;background:#064F6D;">Amount Cr</th>
    </tr>
    </thead>
    <tbody >

    <?php
	$sr_no = 1;
    while ($row3 = mysqli_fetch_array($rec3)) {
        ?>
        <tr>
            <td  class="bg-dark text-white"><?php echo $row3["id"]; ?></td>
            <td><?php echo $row3["ledger_code_dr"]; ?></td>
            <td style=""><?php echo $row3["ledger_category_dr"]; ?></td>
            <td style="text-transform:capitalize; color:#0A4657; font-weight:900;"><?php echo $row3["description_dr"]; ?></td>
          
            <td><?php echo $row3["amount_dr"]; ?></td>
            <td></td>
        </tr>
        <tr>
            <td th class=" text-white" style="background:#0A4F63;"><?php echo  $row3["id"]; ?></td>
            <td ><?php echo $row3["ledger_code_cr"]; ?></td>
            <td style="color:#0A4657;"><?php echo $row3["ledger_category_cr"]; ?></td>
            <td style="text-transform:capitalize; color:#567043;font-weight:900;"><?php echo $row3["description_cr"]; ?></td>
           
            <td></td>
            <td><?php echo $row3["amount_cr"]; ?></td>
        </tr>
        <?php
    }
    ?>
    </tbody>
</table>
</div>
          </div>
                    <div class="col-sm-1"></div>
                    </div>
                    </form>
                  


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


</div>    
</body>
 <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></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>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>
<script>
    // Function to reset totals to zero (or show null/zero if the filter hasn't run)
    function resetTotals() {
        document.querySelector('.opening-balance').textContent = '0';
        document.querySelector('.debit-total').textContent = '0 Dr';
        document.querySelector('.credit-total').textContent = '0 Cr';
        document.querySelector('.closing-balance').textContent = '0';
    }

    // Initial reset to zero when the page loads (before any filtering)
    document.addEventListener('DOMContentLoaded', function() {
        resetTotals();
    });

    // Event listener for form submission (filter application)
    document.querySelector('form').addEventListener('submit', function(event) {
        event.preventDefault(); // Prevent form submission to avoid page reload

        // Get input values for filtering
        const description = document.getElementById('description').value.toLowerCase();
        const ledgerCode = document.getElementById('ledgercode').value.toLowerCase();
        const startPeriod = document.querySelector('input[name="startperiod"]').value;
        const endPeriod = document.querySelector('input[name="endperiod"]').value;

        // Fetch the opening balance from the hidden input
        const openingBalance = parseFloat(document.getElementById('opening_balance').value) || 0;

        // Initialize variables to store calculated totals
        let totalDebit = 0;
        let totalCredit = 0;
        let rowCount = 0; // Keep track of how many rows are visible after filtering

        // Get all table rows from the ledger table
        const rows = document.querySelectorAll('#ledgertable tbody tr');

        // Loop through each row and apply the filtering conditions
        rows.forEach(function(row) {
            const ledgerCodeDr = row.cells[1].textContent.toLowerCase();
            const ledgerCodeCr = row.cells[6] ? row.cells[6].textContent.toLowerCase() : ''; // Some rows may not have a credit cell
            const descriptionDr = row.cells[3].textContent.toLowerCase();
            const descriptionCr = row.cells[7] ? row.cells[7].textContent.toLowerCase() : ''; // Some rows may not have a credit description
            const postDate = new Date(row.cells[0].textContent); // Assuming the entry date is in the first column

            let showRow = true;

            // Apply description and ledger code filters
            if (description && !(descriptionDr.includes(description) || descriptionCr.includes(description))) {
                showRow = false;
            }
            if (ledgerCode && !(ledgerCodeDr.includes(ledgerCode) || ledgerCodeCr.includes(ledgerCode))) {
                showRow = false;
            }

            // Apply date range filter
            if (startPeriod && endPeriod && (postDate < new Date(startPeriod) || postDate > new Date(endPeriod))) {
                showRow = false;
            }

            // Show or hide the row based on filter results
            if (showRow) {
                row.style.display = ''; // Show row if it matches filters
                rowCount++; // Count visible rows

                // Add the debit and credit amounts from the visible rows
                const debit = parseFloat(row.cells[4].textContent) || 0; // Debit in 5th cell
                const credit = parseFloat(row.cells[5].textContent) || 0; // Credit in 6th cell

                totalDebit += debit;
                totalCredit += credit;
            } else {
                row.style.display = 'none'; // Hide row if it doesn't match filters
            }
        });

        // Calculate the closing balance only if there are matching rows, else set to 0
        const closingBalance = rowCount > 0 ? (openingBalance + totalDebit - totalCredit) : 0;

        // Update the page with recalculated values or set to 0 if no rows are visible
        if (rowCount > 0) {
            document.querySelector('.opening-balance').textContent = openingBalance.toFixed(2);
            document.querySelector('.debit-total').textContent = totalDebit.toFixed(2) + ' Dr';
            document.querySelector('.credit-total').textContent = totalCredit.toFixed(2) + ' Cr';
            document.querySelector('.closing-balance').textContent = closingBalance.toFixed(2);
        } else {
            resetTotals(); // Reset totals to zero if no matching rows
        }
    });
</script>



<script>
    document.getElementById('downloadExcel').addEventListener('click', function() {
        // Get the table element
        var table = document.getElementById('ledgertable');

        // 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: "Ledger View" });

        // Export the Excel file with a proper name
        try {
            XLSX.writeFile(workbook, 'Ledger_view.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.");
        }
    });
</script>
</body>

</html>