<?php
session_start();
// Include necessary files and configurations

// Check if company_id is set in the session
if (!isset($_SESSION['company_id'])) {
    // Redirect to login page or handle the error as needed
    die("Access denied. Please log in to access this page.");
}
$companyId = $_SESSION['company_id']; 

include 'includes/dbconn.php';

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

if (!$invoice_id) {
    echo "No invoice ID provided";
    exit; // Exit if no invoice ID is provided
}

// Fetch invoice details from the database
$invoiceQuery = "SELECT invoices.*, clients.client_name, clients.address, clients.phone_number, clients.company FROM invoices JOIN clients ON invoices.client_id = clients.client_id WHERE invoices.invoice_id = ?";
$stmt = $conn->prepare($invoiceQuery);
$stmt->bind_param('i', $invoice_id);
$stmt->execute();
$invoiceResult = $stmt->get_result();

if ($invoiceResult->num_rows === 0) {
    echo "No invoice found with ID: " . htmlspecialchars($invoice_id);
    exit; // Exit if no invoice is found
}

$invoice = $invoiceResult->fetch_assoc();

// Fetch line items for the invoice
$lineItemsQuery = "SELECT * FROM invoice_line_items WHERE invoice_id = ?";
$lineItemsStmt = $conn->prepare($lineItemsQuery);
$lineItemsStmt->bind_param('i', $invoice_id);
$lineItemsStmt->execute();
$lineItemsResult = $lineItemsStmt->get_result();

$lineItems = [];
while ($lineItem = $lineItemsResult->fetch_assoc()) {
    $lineItems[] = $lineItem;
}

// 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();
}


// Close the database connection
$conn->close();
?>


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

<head>

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

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

</head>

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

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

    <?php $pagetitle = "Invoice Details";
    include 'partials/menu.php'; ?>
            
            <!-- ============================================================== -->
            <!-- Start Page Content here -->
            <!-- ============================================================== -->

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

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

                    <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-body">
                                 
                                    <div class="panel-body">
                                        <div class="clearfix">
                                            <div class="float-start">
                                                <h3>Faida Accounting System</h3>
                                                
                                            </div>
                                            <div class="float-end">
                                                <h4>Invoice ID: <br>
                                                    <strong><?php echo isset($invoice['invoice_id']) ? htmlspecialchars($invoice['invoice_id']) : 'Not Available'; ?></strong>
                                                </h4>
                                            </div>
                                        </div>
                                        <hr>
                                        <div class="row">
                                            <div class="col-md-12">
    
                                                <div class="float-start mt-3">
                                                    <address>
                                                        Client Name: <strong><?php echo htmlspecialchars($invoice['client_name']); ?></strong><br>
                                                        Company: <strong><?php echo htmlspecialchars($invoice['company']); ?><br></strong>
                                                        Client Address: <strong><?php echo htmlspecialchars($invoice['address']) . ', ' . htmlspecialchars($invoice['state']); ?><br></strong>
                                                        Client Phone: <strong><abbr title="Phone">P:</abbr> <?php echo htmlspecialchars($invoice['phone_number']); ?></strong>
                                                    </address>
                                                </div>
                                                <div class="float-end mt-3">
                                                    <p><strong>Due Date: </strong> <?php echo htmlspecialchars($invoice['due_date']); ?></p>
                                                    <p class="m-t-10"><strong>Order Status: </strong> <span class="label label-pink"><?php echo htmlspecialchars($invoice['payment_status']); ?></span></p>
                                                    <p class="m-t-10"><strong>Order ID: </strong> #<?php echo isset($invoice['invoice_id']) ? htmlspecialchars($invoice['invoice_id']) : 'Not Available'; ?></p>
                                                </div>
                                            </div><!-- end col -->
                                        </div>
                                        <!-- end row -->
    
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="table-responsive">
                                                    <table class="table mt-4">
                                                        <thead>
                                                        <tr><th>#</th>
                                                            <th>Item</th>
                                                            <th>Description</th>
                                                            <th>Quantity</th>
                                                            <th>Unit Cost</th>
                                                            <th>Total</th>
                                                        </tr></thead>
                                                        <tbody>
                                                            <?php foreach ($lineItems as $index => $item): ?>
                                                                <tr>
                                                                    <td><?php echo $index + 1; ?></td>
                                                                    <td><?php echo htmlspecialchars($item['invoice_id']); ?></td> <!-- Assuming 'description' is the item name -->
                                                                    <td><?php echo htmlspecialchars($item['description']); ?></td>
                                                                    <td><?php echo htmlspecialchars($item['quantity']); ?></td>
                                                                    <td>$<?php echo htmlspecialchars($item['unit_price']); ?></td>
                                                                    <td>$<?php echo htmlspecialchars($item['total_amount']); ?></td>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-xl-6 col-6">
                                                <div class="clearfix mt-4">
                                                    <h5 class="small text-dark fw-normal">PAYMENT TERMS AND POLICIES</h5>
    
                                                    <small>
                                                        All accounts are to be paid within 7 days from receipt of
                                                        invoice. To be paid by cheque or credit card or direct payment
                                                        online. If account is not paid within 7 days the credits details
                                                        supplied as confirmation of work undertaken will be charged the
                                                        agreed quoted fee noted above.
                                                    </small>
                                                </div>
                                            </div>
                                            <div class="col-xl-3 col-6 offset-xl-3">
                                                <p class="text-end"><b>Sub-total:</b> <?php echo htmlspecialchars($item['total_amount']); ?></p>
                                                <p class="text-end">Discount: <?php echo htmlspecialchars($item['discount']); ?></p>
                                                <p class="text-end">VAT: <?php echo htmlspecialchars($item['tax']); ?></p>
                                                <hr>
                                                <h3 class="text-end">USD <?php echo htmlspecialchars($item['total_amount']); ?></h3>
                                            </div>
                                        </div>
                                        <hr>
                                        <div class="d-print-none">
                                            <div class="float-end">
                                                <a href="javascript:window.print()" class="btn btn-dark waves-effect waves-light"><i class="fa fa-print"></i></a>
                                            </div>
                                            <div class="d-print-none mt-4">
                                                <input type="hidden" id="invoiceId" value="<?php echo $invoice_id; ?>">

                                                 <button type="button" class="btn btn-success rounded-pill waves-effect waves-light" onclick="markPayment()">
                                                        <span class="btn-label"><i class="mdi mdi-cash usd"></i></span>Mark Payment
                                                    </button>
                                                <button type="button" class="btn btn-success waves-effect waves-light" data-bs-toggle="modal" data-bs-target="#con-close-modal">Responsive Modal</button>    
                                            </div>
                                            
                                            <div id="con-close-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
                                            <div class="modal-dialog">
                                                <div class="modal-content">
                                                    <form id="paymentForm" novalidate action="mark_payment.php" method="post"> 
                                                    <div class="modal-header">
                                                        <h4 class="modal-title">Payment Processing for Invoice # <?php echo $invoice_id; ?></h4>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <div class="mb-3">
                                                                    <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>
                                                            <div class="col-md-6">
                                                                <div class="mb-3">
                                                                    <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>
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <div class="mb-3">
                                                                    <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>
                                                            <div class="col-md-6">
                                                                <div class="mb-3">
                                                                    <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>
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <div class="mb-3">
                                                                     <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>
                                                            <div class="col-md-6">
                                                                <div class="mb-3">
                                                                   <label for="pay_balance" class="form-label">Balance</label>
                                                                   <input type="text" class="form-control" id="pay_balance" name="balance" placeholder="Balance" readonly>
                                                                </div>
                                                            </div>
                                                        </div>
                                                         <input type="hidden" name="invoice_id" value="<?php echo $invoice_id; ?>">
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary rounded-pill waves-effect waves-light" data-bs-dismiss="modal">Close</button>
                                                        <button class="btn btn-success rounded-pill waves-effect waves-light" type="submit">Mark Payment</button>
                                                    </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div><!-- /.modal -->

                                            <div class="clearfix"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                          
                        </div>

                    </div>
                    <!-- end row -->        
                    
                </div> <!-- container-fluid -->

                </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'; ?>

        <!-- App js -->
<script src="assets/js/app.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
    $(document).ready(function() {
        $('#client_name').select2();
    });
</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 markPayment() {
        // Assuming $invoice_id is already set on your page
        var invoiceId = "<?php echo $invoice_id; ?>";

        // Redirect to process_payment.php with the invoice_id
        window.location.href = "process_payment.php?invoice_id=" + invoiceId;
    }
</script>

    </body>
</html>