<?php
include("db/cn.php"); // Include your database connection
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();

// Check if the filter form is submitted
if (isset($_POST['filter'])) {
    // Convert dates to the correct format 'YYYY-MM-DD'
    $creditor = $_POST['supplier'];  // Get the selected creditor from dropdown
    $startDate = date('Y-m-d', strtotime($_POST['startDate'])); // Ensure the date is in 'YYYY-MM-DD' format
    $endDate = date('Y-m-d', strtotime($_POST['endDate']));     // Ensure the date is in 'YYYY-MM-DD' format

    error_log("Creditor: $creditor, Start Date: $startDate, End Date: $endDate");

    // Fetch the opening cash from creditor_opening_amount table for the most recent date before or on the start date
    $openingQuery = "
        SELECT open_amount AS amount
        FROM creditor_opening_amount 
        WHERE creditor_name = '$creditor' 
        AND date_time BETWEEN '$startDate' AND '$endDate' 
        ORDER BY date_time LIMIT 1";

    $openingResult = mysqli_query($connection, $openingQuery);
    if (!$openingResult) {
        error_log("SQL Error: " . mysqli_error($connection));
    }
    $openingRow = mysqli_fetch_assoc($openingResult);
    $openingBalance = $openingRow ? $openingRow['amount'] : 0;

    $transactions = []; // Array to store all transactions

    // Fetch all transactions from log_user_sales table (include paid_by field)
    $creditSalesQuery = "
        SELECT date_time AS date, discount_amount AS amount, paid_by 
        FROM log_user_sales 
        WHERE customer_name = '$creditor' 
         AND paid_by = 'credit'
        AND date_time BETWEEN '$startDate' AND '$endDate' 
        GROUP BY order_id";

    $creditSalesResult = mysqli_query($connection, $creditSalesQuery);
    while ($row = mysqli_fetch_assoc($creditSalesResult)) {
        $transactions[] = [
            'date' => $row['date'],
            'description' => 'Credit Sale',
            'amount' => $row['amount'],
            'paid_by' => $row['paid_by']
        ];
    }

// Fetch all transactions from log_user_sales table (include paid_by field)
    $creditPOSQuery = "
        SELECT date_time AS date, cash_amount AS amount, paid_by 
        FROM log_user_sales 
        WHERE customer_name = '$creditor' 
         AND paid_by = 'credit'
        AND date_time BETWEEN '$startDate' AND '$endDate' 
        GROUP BY order_id";

    $creditposResult = mysqli_query($connection, $creditPOSQuery);
    while ($row = mysqli_fetch_assoc($creditposResult)) {
        $transactions[] = [
            'date' => $row['date'],
            'description' => 'POS Cash Received',
            'amount' => $row['amount'],
            'paid_by' => $row['paid_by']
        ];
    }
   // Fetch Credit Sale Returns from order_detail table (include paid_by field)
    $creditReturnQuery = "
        SELECT date_time AS date, discount_amount AS amount, paid_by, status 
        FROM log_user_sales 
        WHERE customer_name = '$creditor' AND status = 'refund'
         AND paid_by = 'credit'
        AND date_time BETWEEN '$startDate' AND '$endDate' 
        GROUP BY r_order_id";

    $creditReturnResult = mysqli_query($connection, $creditReturnQuery);
    while ($row = mysqli_fetch_assoc($creditReturnResult)) {
        $transactions[] = [
            'date' => $row['date'],
            'description' => 'Credit Sale Return',
            'amount' => -$row['amount'],
            'paid_by' => $row['paid_by']
        ];
    }

    // Fetch Credit Received from credit_paid table (include paid_by field)
    $creditReceivedQuery = "
        SELECT date_time AS date, amount, paid_by 
        FROM credit_paid 
        WHERE cr_name = '$creditor' 
        AND date_time BETWEEN '$startDate' AND '$endDate'";

    $creditReceivedResult = mysqli_query($connection, $creditReceivedQuery);
    while ($row = mysqli_fetch_assoc($creditReceivedResult)) {
        $transactions[] = [
            'date' => $row['date'],
            'description' => 'Credit Received',
            'amount' => -$row['amount'],
            'paid_by' => $row['paid_by']
        ];
    }

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

    // Calculate the running balance starting with the opening balance
    $balance = $openingBalance;
}

// Fetch creditor names to populate the dropdown
$creditorQuery = "SELECT DISTINCT cr_name FROM credit_note";
$creditorResult = mysqli_query($connection, $creditorQuery);
?>
<!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;
		}
		
 #table-container-wrapper {
    max-height: 560px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}

  </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-5">
     <h3 style="color:#060606; font-weight:700;">Customer Ledger Report</h3>
        </div>
        <div class="col-sm-4"></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">Customer Name:</label>
                        <select class="form-control" name="supplier" required>
                            <option value="">Select Customer</option>
                            <?php
                            // Populate creditor names in the dropdown
                            while ($row = mysqli_fetch_assoc($creditorResult)): ?>
                                <option style="color:#060606;" value="<?= $row['cr_name'] ?>"><?= $row['cr_name'] ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">
                    <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-4">
                    <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>
                         <a href="report_recieve.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="downloadExcel" class="btn btn-dark " style="margin-top:30px;">Download </button>

                    </div>
                </div>
            </div>
        </form>

        <br>
        <?php if (isset($transactions)): ?>
            <h5 class="text-center" style="background:#0A4657;color:#fff; padding:20px; border-radius:10px; text-transform:capitalize;">
                Customer Ledger Report: <strong><?= $creditor ?></strong>
            </h5>
<div class="col-sm-12" id="table-container-wrapper">
    <table id="patientTable" class="table table-striped table-hover text-center table-sm bg-wite">
        <thead>
        <tr class="bg-dark text-white">
            <th>Date</th>
            <th>Description</th>
            <th>Paid By</th>
            <th>Debit Amount (Rs)</th>
            <th>Credit Amount (Rs)</th>
            <th>Balance (Rs)</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td style="color:#0A4657; font-weight:700;"><?= $startDate ?></td>
            <td style="color:#0A4657; font-weight:700;">Opening Balance</td>
            <td>-</td>
            <td style="color:#0A4657; font-weight:700;"><?= number_format($openingBalance, 2) ?></td>
            <td></td>
            <td style="color:#0A4657; font-weight:700;"><?= number_format($openingBalance, 2) ?></td>
        </tr>
        <?php foreach ($transactions as $transaction): ?>
            <?php 
            $positiveAmount = '';
            $negativeAmount = '';
            
            // Determine whether the transaction is positive or negative
            if ($transaction['paid_by'] === 'credit' && 
                ($transaction['description'] === 'Credit Sale' || $transaction['description'] === 'Credit Sale Return')) {
                $balance += $transaction['amount'];
                if ($transaction['amount'] > 0) {
                    $positiveAmount = number_format($transaction['amount'], 2);
                } else {
                    $negativeAmount = number_format(abs($transaction['amount']), 2);
                }
            } elseif ($transaction['description'] === 'POS Cash Received' && $transaction['paid_by'] === 'credit') {
                $balance -= $transaction['amount'];
                $negativeAmount = number_format($transaction['amount'], 2);
            } elseif ($transaction['description'] === 'Credit Received' && 
                      in_array($transaction['paid_by'], ['cash', 'bank1', 'bank2', 'bank3', 'other'])) {
                $balance += $transaction['amount'];
                if ($transaction['amount'] > 0) {
                    $positiveAmount = number_format($transaction['amount'], 2);
                } else {
                    $negativeAmount = number_format(abs($transaction['amount']), 2);
                }
            }
            ?>
            <tr style="color:#060606;">
                <td><?= $transaction['date'] ?></td>
                <td><?= $transaction['description'] ?></td>
                <td><?= ucfirst($transaction['paid_by']) ?></td>
                <td><?= $positiveAmount ?></td>
                <td><?= $negativeAmount ?></td>
                <td><?= number_format($balance, 2) ?></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>Final Balance:</th>
                            <td><?= number_format($balance, 2) ?></td>
                        </tr>
                        </tfoot>
                    </table>

                </div>
            </div>
        <?php endif; ?>
    </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>

<!-- 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, 'Recieveable_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.");
        }
    });
</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>