<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$invoice_id = $_GET['id'] ?? '';

if (empty($invoice_id)) {
    header('Location: list_invoices.php');
    exit();
}

// Get invoice details
$sql = "SELECT i.*, l.lease_code, u.unit_number, p.property_name,
               t.first_name, t.last_name, t.email, t.phone
        FROM invoices i
        JOIN leases l ON i.lease_id = l.lease_id
        JOIN units u ON l.unit_id = u.unit_id
        JOIN properties p ON u.property_id = p.property_id
        JOIN lease_tenants lt ON l.lease_id = lt.lease_id AND lt.is_primary = 1
        JOIN tenants t ON lt.tenant_id = t.tenant_id
        WHERE i.invoice_id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$result = $stmt->get_result();
$invoice = $result->fetch_assoc();

if (!$invoice) {
    header('Location: list_invoices.php');
    exit();
}

// Get payments for this invoice
$sql_payments = "SELECT * FROM rent_payments 
                 WHERE invoice_id = ? 
                 ORDER BY payment_date DESC";

$stmt_payments = $conn->prepare($sql_payments);
$stmt_payments->bind_param("i", $invoice_id);
$stmt_payments->execute();
$result_payments = $stmt_payments->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Invoice Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Invoices', 'title' => 'Invoice Details')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="list_invoices.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i>Back to Invoices
                            </a>
                            <a href="print_invoice.php?id=<?php echo $invoice_id; ?>" target="_blank" class="btn btn-info ms-2">
                                <i class="ri-printer-line me-1"></i>Print Invoice
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Invoice <?php echo htmlspecialchars($invoice['invoice_number']); ?></h4>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-4">
                                        <div class="col-md-6">
                                            <h6 class="text-muted mb-3">Bill To:</h6>
                                            <p class="mb-1"><strong><?php echo htmlspecialchars($invoice['first_name'] . ' ' . $invoice['last_name']); ?></strong></p>
                                            <p class="mb-1"><?php echo htmlspecialchars($invoice['email']); ?></p>
                                            <p class="mb-1"><?php echo htmlspecialchars($invoice['phone']); ?></p>
                                        </div>
                                        <div class="col-md-6 text-end">
                                            <p class="mb-1"><strong>Invoice Date:</strong> <?php echo date('M d, Y', strtotime($invoice['invoice_date'])); ?></p>
                                            <p class="mb-1"><strong>Due Date:</strong> <?php echo date('M d, Y', strtotime($invoice['due_date'])); ?></p>
                                            <p class="mb-1"><strong>Status:</strong> 
                                                <span class="badge bg-soft-<?php echo $invoice['status'] == 'paid' ? 'success' : 'danger'; ?>">
                                                    <?php echo ucfirst($invoice['status']); ?>
                                                </span>
                                            </p>
                                        </div>
                                    </div>

                                    <div class="mb-4">
                                        <h6 class="text-muted mb-2">Property Information:</h6>
                                        <p class="mb-1"><strong>Property:</strong> <?php echo htmlspecialchars($invoice['property_name']); ?></p>
                                        <p class="mb-1"><strong>Unit:</strong> <?php echo htmlspecialchars($invoice['unit_number']); ?></p>
                                        <p class="mb-1"><strong>Lease:</strong> <?php echo htmlspecialchars($invoice['lease_code']); ?></p>
                                    </div>

                                    <div class="table-responsive mb-4">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Description</th>
                                                    <th class="text-end">Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($invoice['description'] ?? $invoice['type']); ?></td>
                                                    <td class="text-end">KES <?php echo number_format($invoice['total_amount'], 2); ?></td>
                                                </tr>
                                                <tr class="table-light">
                                                    <td><strong>Total Amount</strong></td>
                                                    <td class="text-end"><strong>KES <?php echo number_format($invoice['total_amount'], 2); ?></strong></td>
                                                </tr>
                                                <?php if ($invoice['balance'] > 0): ?>
                                                    <tr>
                                                        <td><strong>Amount Paid</strong></td>
                                                        <td class="text-end text-success">KES <?php echo number_format($invoice['total_amount'] - $invoice['balance'], 2); ?></td>
                                                    </tr>
                                                    <tr class="table-danger">
                                                        <td><strong>Balance Due</strong></td>
                                                        <td class="text-end"><strong>KES <?php echo number_format($invoice['balance'], 2); ?></strong></td>
                                                    </tr>
                                                <?php else: ?>
                                                    <tr class="table-success">
                                                        <td><strong>Status</strong></td>
                                                        <td class="text-end"><strong>Fully Paid</strong></td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <div class="card mt-3">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Payment History</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Reference</th>
                                                    <th>Amount</th>
                                                    <th>Method</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_payments && $result_payments->num_rows > 0): ?>
                                                    <?php while($payment = $result_payments->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($payment['payment_date'])); ?></td>
                                                            <td><?php echo htmlspecialchars($payment['payment_reference']); ?></td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($payment['amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info"><?php echo htmlspecialchars($payment['payment_method']); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-success"><?php echo htmlspecialchars($payment['payment_status']); ?></span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center py-4">
                                                            <div class="text-muted">No payments recorded</div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Quick Actions</h4>
                                </div>
                                <div class="card-body">
                                    <?php if ($invoice['balance'] > 0): ?>
                                        <a href="list_payments.php?invoice_id=<?php echo $invoice_id; ?>" class="btn btn-primary w-100 mb-2">
                                            <i class="ri-money-dollar-circle-line me-1"></i>Record Payment
                                        </a>
                                    <?php endif; ?>
                                    <a href="print_invoice.php?id=<?php echo $invoice_id; ?>" target="_blank" class="btn btn-info w-100 mb-2">
                                        <i class="ri-printer-line me-1"></i>Print Invoice
                                    </a>
                                    <a href="lease_details.php?id=<?php echo $invoice['lease_id']; ?>" class="btn btn-secondary w-100">
                                        <i class="ri-file-text-line me-1"></i>View Lease
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
