<?php
// Continue Payment
if (isset($_POST['pay_now_btn'])) {
    $invoice_id = intval($_POST['invoice_id']);
    $reg_number = $_POST['reg_number'];
    $amount_to_pay = floatval($_POST['pay_now']);

    // Get current paid and total
    $stmt = $connection->prepare("SELECT amount_paid, total_amount FROM inventory_invoices WHERE id = ?");
    $stmt->bind_param("i", $invoice_id);
    $stmt->execute();
    $stmt->bind_result($current_paid, $total_amount);
    $stmt->fetch();
    $stmt->close();

    $new_paid = $current_paid + $amount_to_pay;
    $new_balance = $total_amount - $new_paid;

    if ($new_paid > $total_amount) {
        $_SESSION['msg'] = "Payment exceeds total invoice amount.";
        $_SESSION['type'] = "danger";
    } else {
        // ✅ Determine payment status
        if ($new_paid == 0) {
            $status = "Unpaid";
        } elseif ($new_paid >= $total_amount) {
            $status = "Paid";
        } else {
            $status = "Balance";
        }

        // ✅ Update amount_paid, balance, and status
        $stmt = $connection->prepare("UPDATE inventory_invoices 
                                      SET amount_paid = ?, balance = ?, payment_status = ? 
                                      WHERE id = ?");
        $stmt->bind_param("ddsi", $new_paid, $new_balance, $status, $invoice_id);
        if ($stmt->execute()) {
            $_SESSION['msg'] = "Payment updated successfully.";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "Failed to update payment.";
            $_SESSION['type'] = "danger";
        }
        $stmt->close();
    }

    header("Location: view_invoice");
    exit;
}




// Handle invoice delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_invoice'], $_POST['invoice_id'])) {
    $invoice_id = (int)$_POST['invoice_id'];

    $connection->begin_transaction();
    try {
        $connection->query("DELETE FROM inventory_invoice_items WHERE invoice_id = $invoice_id");
        $connection->query("DELETE FROM inventory_invoices WHERE id = $invoice_id");

        $connection->commit();
        $_SESSION['msg'] = "Invoice deleted successfully.";
        $_SESSION['type'] = "success";
    } catch (Exception $e) {
        $connection->rollback();
        $_SESSION['msg'] = "Failed to delete invoice: " . $e->getMessage();
        $_SESSION['type'] = "danger";
    }

    header("Location: view_invoice");
    exit;
}

// Fetch all invoices
$invoices = $connection->query("SELECT * FROM inventory_invoices ORDER BY id DESC");
?>

<div class="page-title">
    <h1><i class="fa fa-file-invoice-dollar"></i> View All Invoices</h1>
</div>

<div class="card">
    <div class="panel panel-primary">
        <div class="panel-heading">Invoice List</div>
        <div class="panel-body">
            <div class="table-responsive">
                <table class="table table-bordered table-striped" id="myTable">
                    <thead class="thead-dark">
                        <tr>
                            <th>Invoice No</th>
                            <th>Reg No</th>
                            <th>Student Name</th>
                            <th>Class</th>
                            <th>Issued At</th>
                            <th>Cashier</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($invoice = $invoices->fetch_assoc()): ?>
                            <tr>
                                <td><?= htmlspecialchars($invoice['invoice_no']) ?></td>
                                <td><?= htmlspecialchars($invoice['reg_number']) ?></td>
                                <td><?= htmlspecialchars($invoice['student_name']) ?></td>
                                <td><?= htmlspecialchars($invoice['student_class']) ?></td>
                                <td><?= date('Y-m-d H:i', strtotime($invoice['issued_at'])) ?></td>
                                <td><?= htmlspecialchars($invoice['created_by']) ?></td>
                                <td>
                                <!-- Continue Payment (Icon Button with Tooltip) -->
                                <button type="button" class="btn btn-sm btn-info" data-toggle="modal" data-target="#payModal<?= $invoice['id'] ?>" title="Continue Payment" <?= ($invoice['total_amount'] - $invoice['amount_paid'] <= 0) ? 'disabled' : '' ?>>
                                    <i class="fa fa-credit-card"></i>
                                </button>
                            
                                <!-- View Invoice (Modal Trigger Button) -->
                                <button type="button" class="btn btn-sm btn-info" data-toggle="modal" data-target="#viewModal<?= $invoice['id'] ?>" title="View Invoice">
                                    <i class="fa fa-eye"></i>
                                </button>
                            
                                <!-- Print Invoice -->
                                <a href="print_invoice.php?invoice_id=<?= $invoice['id'] ?>" target="_blank" class="btn btn-sm btn-primary" title="Print Invoice">
                                    <i class="fa fa-print"></i>
                                </a>
                            
                                <!-- Delete Invoice -->
                                <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this invoice?');">
                                    <input type="hidden" name="invoice_id" value="<?= $invoice['id'] ?>">
                                    <button type="submit" name="delete_invoice" class="btn btn-sm btn-danger" title="Delete Invoice">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </form>
                            </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- All Modals -->
<?php 
$invoices->data_seek(0); // Reset result pointer
while ($invoice = $invoices->fetch_assoc()):
    $invoice_id = $invoice['id'];

    // Fetch invoice items directly (without inventory_items join)
    $items = $connection->query("SELECT * 
        FROM inventory_invoice_items 
        WHERE invoice_id = $invoice_id");
?>
<!-- Continue Payment Modal -->
                                <div class="modal fade" id="payModal<?= $invoice['id'] ?>" tabindex="-1" role="dialog" aria-labelledby="payModalLabel<?= $invoice['id'] ?>" aria-hidden="true">
                                    <div class="modal-dialog" role="document">
                                        <form method="POST" action="">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="payModalLabel<?= $invoice['id'] ?>">Continue Payment for Invoice #<?= htmlspecialchars($invoice['invoice_no']) ?></h5>
                                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                        <span aria-hidden="true">&times;</span>
                                                    </button>
                                                </div>
                                                <div class="modal-body">
                                                    <input type="hidden" name="invoice_id" value="<?= $invoice['id'] ?>">
                                                    <div class="form-group">
                                                        <label>Student Name</label>
                                                        <input type="text" class="form-control" readonly value="<?= htmlspecialchars($invoice['student_name']) ?>">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Total Amount</label>
                                                        <input type="text" class="form-control" readonly value="₦<?= number_format($invoice['total_amount'], 2) ?>">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Amount Paid</label>
                                                        <input type="text" class="form-control" readonly value="₦<?= number_format($invoice['amount_paid'], 2) ?>">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Balance</label>
                                                        <?php $balance = $invoice['total_amount'] - $invoice['amount_paid']; ?>
                                                        <input type="text" class="form-control" readonly value="₦<?= number_format($balance, 2) ?>">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Pay Now (₦)</label>
                                                        <input type="number" step="0.01" name="pay_now" class="form-control" required max="<?= $balance ?>" min="0.01" placeholder="Enter amount" <?= ($balance <= 0) ? 'readonly' : '' ?>>
                                                        <?php if ($balance <= 0): ?>
                                                            <small class="form-text text-muted">No payment required (balance cleared).</small>
                                                        <?php else: ?>
                                                            <small class="form-text text-muted">Enter an amount up to ₦<?= number_format($balance, 2) ?>.</small>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="submit" name="pay_now_btn" class="btn btn-primary" <?= ($balance <= 0) ? 'disabled' : '' ?>>Pay</button>
                                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
<div class="modal fade" id="viewModal<?= $invoice_id ?>" tabindex="-1" role="dialog" aria-labelledby="modalTitle<?= $invoice_id ?>" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Invoice #<?= htmlspecialchars($invoice['invoice_no']) ?></h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <p><strong>Student Name:</strong> <?= htmlspecialchars($invoice['student_name']) ?></p>
                <p><strong>Class:</strong> <?= htmlspecialchars($invoice['student_class']) ?></p>
                <p><strong>Total:</strong> ₦<?= number_format($invoice['total_amount'], 2) ?></p>
                <p><strong>Balance:</strong> ₦<?= number_format($invoice['balance'], 2) ?></p>
                <p><strong>Issued At:</strong> <?= date('Y-m-d H:i', strtotime($invoice['issued_at'])) ?></p>
                <p><strong>By:</strong> <?= htmlspecialchars($invoice['created_by']) ?></p>
                <h5 class="mt-3">Invoice Items</h5>
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Item</th>
                            <th>Quantity</th>
                            <th>Unit Price</th>
                            <th>Total Price</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($item = $items->fetch_assoc()): ?>
                        <tr>
                            <td><?= htmlspecialchars($item['item_name']) ?></td>
                            <td><?= $item['quantity'] ?></td>
                            <td>₦<?= number_format($item['unit_price'], 2) ?></td>
                            <td>₦<?= number_format($item['total_price'], 2) ?></td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php endwhile; ?>


