<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
    header('location:login.php');
}
?>
<!doctype html>
<html lang="en">


<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>View Expense</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="images/favicon.ico" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">
    <style>
    ion-icon {
        font-size: 20px;
        margin-bottom: -5px;
    }
    </style>
</head>

<body>
    <!-- loader Start -->
    <div id="loading">
        <div id="loading-center">
        </div>
    </div>
    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php 
            include 'includes/sidebar.php';
        ?>
        <!-- TOP Nav Bar -->
        <?php include 'includes/header.php';?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <div id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between row">
                                <div class="iq-header-title col-lg-6">
                                    <h4 class="card-title"><a href="list_expense.php">Installment</a> > View Installment Recovery
                                    </h4>
                                </div>
                                <!-- <div class="col-lg-6">
                                    <button class="btn btn-primary  ps-5 pe-5" style="float:inline-end;">
                                        <a href="add_expense.php" class="text-white">
                                            <ion-icon name="add-outline" style="font-size:20px; margin-bottom:-4px">
                                            </ion-icon> Add
                                        </a>
                                    </button>
                                </div> -->
                            </div>
                            <!-- search bar -->
                           <?php 
include 'includes/config.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);

$customer_id = $_GET['customer_id'] ?? '';
$date_from   = $_GET['date_from'] ?? '';
$date_to     = $_GET['date_to'] ?? '';

$where = [];
$params = [];

if (!empty($customer_id)) {
    $where[] = "ci.customer_id = :customer_id";
    $params[':customer_id'] = $customer_id;
}

if (!empty($date_from) && !empty($date_to)) {
    $where[] = "ci.due_date BETWEEN :date_from AND :date_to";
    $params[':date_from'] = $date_from;
    $params[':date_to']   = $date_to;
}

$where_sql = $where ? "WHERE " . implode(" AND ", $where) : "";

// Installments query
$sql = "
    SELECT 
        ci.id, ci.invoice, ci.customer_id, c.name AS customer_name,
        ci.installment_no, ci.amount, ci.due_date, ci.status, ci.paid_date
    FROM customer_installments ci
    INNER JOIN contacts c ON ci.customer_id = c.id
    $where_sql
    ORDER BY ci.status ASC, ci.due_date ASC
";
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$installments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Customer list only with installments
$custStmt = $conn->query("
    SELECT DISTINCT c.id, c.name 
    FROM contacts c
    INNER JOIN customer_installments ci ON ci.customer_id = c.id
    ORDER BY c.name ASC
");
$customers = $custStmt->fetchAll(PDO::FETCH_ASSOC);

?>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<style>
.paid { background:#d4edda; }
.pending { background:#f8d7da; }
.total { font-weight:bold; }
@media print { .no-print { display:none; } }
</style>

<!-- Filters -->
<form method="GET" class="row g-2 mb-3 no-print">
   <div class="col-md-4">
    <select name="customer_id" class="form-control select2">
        <option value="">-- Select Customer --</option>
        <?php foreach($customers as $cust): ?>
            <option value="<?= $cust['id'] ?>" <?= $customer_id==$cust['id']?'selected':'' ?>>
                <?= htmlspecialchars($cust['name']) ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>

    <div class="col-md-3">
        <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>">
    </div>
    <div class="col-md-3">
        <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($date_to) ?>">
    </div>
    <div class="col-md-2">
        <button type="submit" class="btn btn-primary w-100">Filter</button>
    </div>
</form>

<!-- Table -->
<div style="overflow:auto; max-height:600px;">
<table class="table table-hover table-bordered text-center align-middle">
    <thead class="table-dark">
        <tr>
            <th>#</th>
            <th>Invoice</th>
            <th>Customer</th>
            <th>Installment No</th>
            <th>Due Date</th>
            <th>Amount</th>
            <th>Status</th>
            <th>Paid Date</th>
            <th class="no-print">Action</th>
        </tr>
    </thead>
    <tbody>
    <?php if ($installments): 
        $sr=1; $total_amount=0;
        foreach($installments as $inst):
            $total_amount+=$inst['amount']; ?>
            <tr class="<?= $inst['status']=='paid'?'paid':'pending' ?>">
                <td><?= $sr++ ?></td>
                <td><?= htmlspecialchars($inst['invoice']) ?></td>
                <td><?= htmlspecialchars($inst['customer_name']) ?></td>
                <td><?= $inst['installment_no'] ?></td>
                <td><?= date("d-m-Y", strtotime($inst['due_date'])) ?></td>
                <td><?= number_format($inst['amount'],2) ?></td>
                <td><?= ucfirst($inst['status']) ?></td>
                <td><?= $inst['paid_date']?date("d-m-Y",strtotime($inst['paid_date'])):"-" ?></td>
                <td class="no-print">
                    <?php if($inst['status']=='pending'): ?>
                        <button class="btn btn-success btn-sm payBtn" 
                            data-id="<?= $inst['id'] ?>" 
                            data-amount="<?= $inst['amount'] ?>" 
                            data-customer="<?= htmlspecialchars($inst['customer_name']) ?>"
                            data-invoice="<?= $inst['invoice'] ?>">
                            Pay
                        </button>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        <tr class="table-info total">
            <td colspan="5">Total</td>
            <td><?= number_format($total_amount,2) ?></td>
            <td colspan="3"></td>
        </tr>
    <?php else: ?>
        <tr><td colspan="9">No records found</td></tr>
    <?php endif; ?>
    </tbody>
</table>
</div>

<!-- Payment Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1" aria-labelledby="paymentModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header py-2">
        <h6 class="modal-title" id="paymentModalLabel">Pay Installment</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="paymentForm">
          <input type="hidden" id="inst_id">
          <input type="hidden" id="inst_invoice">
          <input type="hidden" id="inst_customer">

          <div class="mb-2">
            <label class="form-label">Max Amount</label>
            <input type="text" id="max_amount" class="form-control form-control-sm" readonly>
          </div>
          <div class="mb-2">
            <label class="form-label">Enter Amount</label>
            <input type="number" id="paid_amount" class="form-control form-control-sm" required>
          </div>
        </form>
      </div>
      <div class="modal-footer py-2">
        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary btn-sm" id="confirmPay">Pay Now</button>
      </div>
    </div>
  </div>
</div>

<script>
$(document).ready(function(){

    // open modal on pay button
    $(".payBtn").on("click", function(){
        let id       = $(this).data("id");
        let amount   = $(this).data("amount");
        let customer = $(this).data("customer");
        let invoice  = $(this).data("invoice");

        $("#inst_id").val(id);
        $("#inst_invoice").val(invoice);
        $("#inst_customer").val(customer);
        $("#max_amount").val(amount);
        $("#paid_amount").val(amount);

        $("#paymentModal").modal("show");
    });

    // confirm payment
    $("#confirmPay").on("click", function(){
        let id     = $("#inst_id").val();
        let paid   = $("#paid_amount").val();
        let max    = $("#max_amount").val();

        if(paid && !isNaN(paid) && paid > 0 && parseFloat(paid) <= parseFloat(max)){
            $.post("pay_installment.php", {id:id, paid:paid}, function(res){
                alert(res);
                $("#paymentModal").modal("hide");
                window.open("print/receipt.php?id="+id, "_blank"); // receipt open
                location.reload();
            });
        } else {
            alert("Invalid amount entered.");
        }
    });

});
</script>


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

        </div>
    </div>
    </div>
    <!-- Wrapper END -->
    <!-- Footer -->
    <footer class="iq-footer">
        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-6">
                    <ul class="list-inline mb-0">
                        <li class="list-inline-item"><a href="privacy-policy.html">Privacy Policy</a></li>
                        <li class="list-inline-item"><a href="terms-of-service.html">Terms of Use</a></li>
                    </ul>
                </div>
                <div class="col-lg-6 text-right">
                    Copyright <span id="copyright">
                        <script>
                        document.getElementById('copyright').appendChild(document.createTextNode(new Date()
                            .getFullYear()))
                        </script>
                    </span> <a href="#">Vito</a> All Rights Reserved.
                </div>
            </div>
        </div>
    </footer>
    <nav class="iq-float-menu">
        <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
        <label class="iq-float-menu-open-button" for="menu-open">
            <span class="lines line-1"></span>
            <span class="lines line-2"></span>
            <span class="lines line-3"></span>
        </label>
        <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode"
            data-mode="rtl"><i class="ri-text-direction-r"></i></button>
        <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode"
            id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
        <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i
                class="ri-palette-line"></i></button>
    </nav>
    <!-- Footer END -->
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="js/jquery.min.js"></script>
    <!-- Rtl and Darkmode -->
    <script src="js/rtl.js"></script>
    <script src="js/customizer.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Appear JavaScript -->
    <script src="js/jquery.appear.js"></script>
    <!-- Countdown JavaScript -->
    <script src="js/countdown.min.js"></script>
    <!-- Counterup JavaScript -->
    <script src="js/waypoints.min.js"></script>
    <script src="js/jquery.counterup.min.js"></script>
    <!-- Wow JavaScript -->
    <script src="js/wow.min.js"></script>
    <!-- Apexcharts JavaScript -->
    <script src="js/apexcharts.js"></script>
    <!-- Slick JavaScript -->
    <script src="js/slick.min.js"></script>
    <!-- Select2 JavaScript -->
    <script src="js/select2.min.js"></script>
    <!-- Owl Carousel JavaScript -->
    <script src="js/owl.carousel.min.js"></script>
    <!-- Magnific Popup JavaScript -->
    <script src="js/jquery.magnific-popup.min.js"></script>
    <!-- Smooth Scrollbar JavaScript -->
    <script src="js/smooth-scrollbar.js"></script>
    <!-- lottie JavaScript -->
    <script src="js/lottie.js"></script>
    <!-- Chart Custom JavaScript -->
    <script src="js/chart-custom.js"></script>
    <!-- Custom JavaScript -->
    <script src="js/custom.js"></script>
</body>

<!-- Mirrored from templates.iqonic.design/vito/html/main/data-table.html by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 21 Aug 2024 10:45:18 GMT -->

</html>