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

// Get filters from the request
$customer_name = isset($_GET['customer_name']) ? trim($_GET['customer_name']) : '';
$route = isset($_GET['route']) ? trim($_GET['route']) : '';
$booker = isset($_GET['booker']) ? trim($_GET['booker']) : '';
$date = isset($_GET['date']) ? trim($_GET['date']) : '';

$filters_applied = !empty($customer_name) || !empty($route) || !empty($booker) || !empty($date);
$customer_data = [];

if ($filters_applied) {
    // Query to get opening amount
   $sql_opening = "SELECT creditor_name, route, booker, DATE(date_time) AS date_time, SUM(open_amount) AS opening_amount 
                FROM creditor_opening_amount 
                WHERE 1=1";

    if (!empty($customer_name)) $sql_opening .= " AND creditor_name = '" . mysqli_real_escape_string($connection, $customer_name) . "'";
    if (!empty($route)) $sql_opening .= " AND route = '" . mysqli_real_escape_string($connection, $route) . "'";
    if (!empty($booker)) $sql_opening .= " AND booker = '" . mysqli_real_escape_string($connection, $booker) . "'";
    if (!empty($date)) $sql_opening .= " AND DATE(date_time) = '" . mysqli_real_escape_string($connection, $date) . "'";
    $sql_opening .= " GROUP BY creditor_name, route, booker";

 
    
    $result_opening = mysqli_query($connection, $sql_opening);
    while ($row = mysqli_fetch_assoc($result_opening)) {
       $customer_data[$row['creditor_name']] = [
    'date_time' => $row['date_time'],
    'route' => $row['route'],
    'booker' => $row['booker'],
    'opening_amount' => $row['opening_amount'],
    'paid_amount' => 0,
    'discount_amount' => 0,
    'closing_balance' => 0
];
    }

    // Query to get paid amount
    $sql_paid = "SELECT cr_name, SUM(amount) AS paid_amount FROM credit_paid WHERE 1=1";
    if (!empty($customer_name)) $sql_paid .= " AND cr_name = '" . mysqli_real_escape_string($connection, $customer_name) . "'";
    if (!empty($route)) $sql_paid .= " AND route = '" . mysqli_real_escape_string($connection, $route) . "'";
    if (!empty($booker)) $sql_paid .= " AND booker = '" . mysqli_real_escape_string($connection, $booker) . "'";
    if (!empty($date)) $sql_paid .= " AND DATE(date_time) = '" . mysqli_real_escape_string($connection, $date) . "'";
    $sql_paid .= " GROUP BY cr_name";

    $result_paid = mysqli_query($connection, $sql_paid);
    while ($row = mysqli_fetch_assoc($result_paid)) {
        if (isset($customer_data[$row['cr_name']])) {
            $customer_data[$row['cr_name']]['paid_amount'] = $row['paid_amount'];
        }
    }

    // Query to get discount amount
    $sql_sales = "SELECT customer_name, SUM(discount_amount) AS discount_amount FROM log_user_sales WHERE 1=1";
    if (!empty($customer_name)) $sql_sales .= " AND customer_name = '" . mysqli_real_escape_string($connection, $customer_name) . "'";
    if (!empty($route)) $sql_sales .= " AND customer_id = '" . mysqli_real_escape_string($connection, $route) . "'";
    if (!empty($booker)) $sql_sales .= " AND customer_type = '" . mysqli_real_escape_string($connection, $booker) . "'";
    if (!empty($date)) $sql_sales .= " AND DATE(date_time) = '" . mysqli_real_escape_string($connection, $date) . "'";
    $sql_sales .= " GROUP BY customer_name";

    $result_sales = mysqli_query($connection, $sql_sales);
    while ($row = mysqli_fetch_assoc($result_sales)) {
        if (isset($customer_data[$row['customer_name']])) {
            $customer_data[$row['customer_name']]['discount_amount'] = $row['discount_amount'];
        }
    }

    // Calculate closing balance
    foreach ($customer_data as $name => $data) {
        $customer_data[$name]['closing_balance'] = 
            $data['opening_amount'] + $data['discount_amount'] - $data['paid_amount'] ;
    }
}
?>


<!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">
        <link href="../css/sb-admin-2.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;
		}
		
.text-primary{
	  	
		}
  </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">
    <div class="row">
        <div class="col-sm-5">
            <h3 style="font-weight:700;color:#000;">Customer Closing Report</h3>
        </div>
        <div class="col-sm-7"></div>
    </div>
    <br>
    <?php
    $c = mysqli_query($connection,"select * from credit_note GROUP BY cr_name");
    $r = mysqli_query($connection,"select * from credit_note GROUP BY route");
    $b = mysqli_query($connection,"select * from credit_note GROUP BY booker");
    ?>
<form action="report_cus.php" method="GET">
    <div class="row">
        <div class="col-sm-3">
            <div class="form-group">
                <label>Select Customer</label>
                <select class="form-control" name="customer_name">
                    <option value="">Select</option>
                    <?php
                    while($cr = mysqli_fetch_array($c)){ 
                    ?>
                    <option value="<?php echo $cr["cr_name"]; ?>"><?php echo $cr["cr_name"]; ?></option>
                    <?php
                    }
                    ?>
                </select>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="form-group">
                <label>Select Route</label>
                <select class="form-control" name="route">
                    <option value="">Select</option> 
                    <?php
                    while($rr = mysqli_fetch_array($r)){ 
                    ?>
                    <option value="<?php echo $rr["route"]; ?>"><?php echo $rr["route"]; ?></option>
                    <?php
                    }
                    ?>
                </select>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="form-group">
                <label>Select Booker</label>
                <select class="form-control" name="booker">
                    <option value="">Select</option>
                    <?php
                    while($br = mysqli_fetch_array($b)){ 
                    ?>
                    <option value="<?php echo $br["booker"]; ?>"><?php echo $br["booker"]; ?></option>
                    <?php
                    }
                    ?>
                </select>
            </div>
        </div>
        <div class="col-sm-4">
            <div class="form-group">
                <label>Date</label>
                <input type="date" class="form-control" name="date">
            </div>
        </div>
        <div class="col-sm-4">
            <button type="submit" class="btn btn-dark" style="margin-top:30px;">Filter</button>
            <a href="report_cus.php" class="btn btn-dark" style="margin-top:30px;"><i class="fas fa-sync fa-1x"></i></a>
            <button type="button" class="btn btn-dark" style="margin-top:30px;">Download</button>
        </div>
    </div>
</form>
    <div class="row">
   <table class="table table-striped table-hover text-center">
        <thead class="bg-dark text-white">
            <tr>
                <th>Date</th>
                <th>Customer</th>
                <th>Route</th>
                <th>Booker</th>
                <th>Closing Balance</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($customer_data as $name => $data) { ?>
                <tr>
                    <td><?php echo $data['date_time']; ?></td>
                    <td><?php echo $name; ?></td>
                    <td><?php echo $data['route']; ?></td>
                    <td><?php echo $data['booker']; ?></td>
                 
                    <td><strong><?php echo number_format($data['closing_balance'], 2); ?></strong></td>
                </tr>
            <?php } ?>
        </tbody>
    </table>
</div>

</div>

            </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://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>
$(document).ready(function(){
    $("#filterButton").click(function(){
        var customer_name = $("select[name='customer_name']").val();
        var route = $("select[name='route']").val();
        var booker = $("select[name='booker']").val();
        var date = $("input[name='date']").val();
        
        $.ajax({
            url: "report_cus.php",
            type: "GET",
            data: {customer_name: customer_name, route: route, booker: booker, date: date},
            success: function(data) {
                $("#reportTable").html($(data).find("#reportTable").html());
            }
        });
    });
});
</script>

</body>

</html>