<?php
// Include necessary files and configurations
include 'services/session.php';

// Include database connection file
include('includes/dbconn.php');

// Retrieve invoice_id from the URL
$invoice_id = isset($_GET['invoice_id']) ? $_GET['invoice_id'] : null;

// Check if invoice_id is available
if ($invoice_id) {
    $query = "SELECT total_amount FROM invoices WHERE invoice_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $invoice_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $totalAmount = $row['total_amount'];
    }
    $stmt->close();
}

?>

<!DOCTYPE html>
<html lang="en">

<head>

    <?php
    $title = "Create Invoice Payment";
    include 'partials/title-meta.php';
    ?>

    <link href="assets/libs/mohithg-switchery/switchery.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/multiselect/css/multi-select.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/selectize/css/selectize.bootstrap3.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/bootstrap-touchspin/jquery.bootstrap-touchspin.min.css" rel="stylesheet" type="text/css" />

    <?php
    include 'partials/head-css.php';
    ?>

</head>

<?php
include 'partials/body.php';
?>

<!-- Begin page -->
<div id="wrapper">

    <?php
    $pagetitle = "Create Invoice Payment";
    include 'partials/menu.php';
    ?>

    <!-- ============================================================== -->
    <!-- Start Page Content here -->
    <!-- ============================================================== -->

    <div class="content-page">
        <div class="content">

            <!-- Start Content-->
            <div class="container-fluid">

                <div class="card">
                    <div class="card-body">
                        <h4 class="header-title">Create Invoice Payment</h4>
                        <p class="sub-header">Capture invoice payment details.</p>

                        <form class="needs-validation" novalidate action="mark_payment.php" method="post">
                            <div class="row">
                                <div class="col-lg-4">
                                    <div class="mb-2">
                                        <label for="invoice_number" class="form-label">Invoice Number</label>
                                        <input type="text" class="form-control" id="invoice_number" name="invoice_number" placeholder="Invoice Number" value="<?php echo $invoice_id; ?>" readonly>
                                    </div>
                                    <div class="mb-2">
                                        <label for="totalAmount" class="form-label">Total Amount</label>
                                        <input type="text" class="form-control" id="totalAmount" name="totalAmount" value="<?php echo htmlspecialchars(number_format($totalAmount, 2)); ?>" readonly>
                                    </div>
                                </div>
                        
                                <div class="col-lg-4">
                                    <div class="mb-2">
                                        <label for="paymentMode" class="form-label">Payment Mode</label>
                                        <input type="text" class="form-control" id="paymentMode" name="paymentMode" placeholder="Enter payment mode" required>
                                    </div>
                                    <div class="mb-2">
                                        <label for="paymentReference" class="form-label">Payment Reference</label>
                                        <input type="text" class="form-control" id="paymentReference" name="paymentReference" placeholder="Enter payment reference" required>
                                    </div>
                                </div>
                                
                                <div class="col-lg-3">
                                    <div class="mb-2">
                                        <label for="paymentAmount" class="form-label">Payment Amount</label>
                                        <input type="text" class="form-control" id="paymentAmount" name="paymentAmount" placeholder="Enter payment amount" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="pay_balance" class="form-label">Balance</label>
                                        <input type="text" class="form-control" id="balance" name="balance" placeholder="Balance" readonly>
                                    </div>
                                </div>
                            </div>
                        
                            <button class="btn btn-primary" type="submit">Mark Payment</button>
                        </form>


                    </div> <!-- end card-body-->
                </div> <!-- end card-->

            </div> <!-- container -->

        </div> <!-- content -->

        <?php
        include 'partials/footer.php';
        ?>

    </div>

    <!-- ============================================================== -->
    <!-- End Page content -->
    <!-- ============================================================== -->

</div>
<!-- END wrapper -->

<?php
include 'partials/right-sidebar.php';
?>

<?php
include 'partials/footer-scripts.php';
?>

<!-- Plugin js-->
<script src="assets/libs/parsleyjs/parsley.min.js"></script>

<!-- Validation init js-->
<script src="assets/js/pages/form-validation.init.js"></script>

<!-- App js -->
<script src="assets/js/app.min.js"></script>
<script src="assets/libs/selectize/js/standalone/selectize.min.js"></script>
<script src="assets/libs/mohithg-switchery/switchery.min.js"></script>
<script src="assets/libs/multiselect/js/jquery.multi-select.js"></script>
<script src="assets/libs/select2/js/select2.min.js"></script>
<script src="assets/libs/jquery-mockjax/jquery.mockjax.min.js"></script>
<script src="assets/libs/devbridge-autocomplete/jquery.autocomplete.min.js"></script>
<script src="assets/libs/bootstrap-touchspin/jquery.bootstrap-touchspin.min.js"></script>
<script src="assets/libs/bootstrap-maxlength/bootstrap-maxlength.min.js"></script>
<script>
    function updateBalance() {
        var paymentAmount = parseFloat(document.getElementById('paymentAmount').value) || 0;
        var totalAmount = parseFloat(document.getElementById('totalAmount').value) || 0;
        
        // Calculate and update the balance
        var balance = totalAmount - paymentAmount;
        document.getElementById('pay_balance').value = balance.toFixed(2);
    }

    // Attach the updateBalance function to the input event of the payment amount field
    document.getElementById('paymentAmount').addEventListener('input', updateBalance);
</script>

<!--<script>
    function updateBalance() {
        var invoiceId = document.getElementById('invoice_number').value;
        var paymentAmount = parseFloat(document.getElementById('paymentAmount').value) || 0;

        // Send AJAX request to get total amount based on the invoice_id
        $.ajax({
            type: "POST",
            url: "get_total_amount.php",
            data: { invoice_id: invoiceId },
            success: function(response) {
                // Handle the response and update the total amount
                var totalAmount = parseFloat(response) || 0;
                document.getElementById('total_amount').value = totalAmount.toFixed(2);

                // Now calculate and update the balance
                var balance = totalAmount - paymentAmount;
                document.getElementById('pay_balance').value = balance.toFixed(2);
            },
            error: function() {
                alert("An error occurred while fetching total amount.");
            }
        });
    }

    // Attach the updateBalance function to the input event of the payment amount field
    document.getElementById('paymentAmount').addEventListener('input', updateBalance);
</script> -->

<script>
    // Get today's date
    var today = new Date();

    // Format it as YYYY-MM-DD (which is the format commonly used in databases)
    var formattedDate = today.toISOString().substr(0, 10);

    // Set the default value of the input field to today's date
    document.getElementById("start_date").value = formattedDate;
</script>

</body>

</html>
