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

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

$user_id = $_SESSION['user_id'];
$status_filter = $_GET['status'] ?? '';

$sql = "SELECT i.*, l.lease_code, u.unit_number, p.name as property_name
        FROM invoices i
        JOIN leases l ON i.lease_id = l.id
        JOIN units u ON l.unit_id = u.id
        JOIN properties p ON u.property_id = p.id
        JOIN lease_tenants lt ON l.id = lt.lease_id AND lt.is_primary = 1
        WHERE lt.tenant_id = (SELECT tenant_id FROM tenants WHERE user_id = ?)";

$params = [$user_id];
$types = 'i';

if (!empty($status_filter)) {
    $sql .= " AND i.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

$sql .= " ORDER BY i.due_date DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Invoices')); ?>
    <?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' => 'Payments', 'title' => 'My Invoices')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-3">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status" onchange="this.form.submit()">
                                                <option value="">All Status</option>
                                                <option value="unpaid" <?php echo $status_filter == 'unpaid' ? 'selected' : ''; ?>>Unpaid</option>
                                                <option value="partial" <?php echo $status_filter == 'partial' ? 'selected' : ''; ?>>Partial</option>
                                                <option value="paid" <?php echo $status_filter == 'paid' ? 'selected' : ''; ?>>Paid</option>
                                                <option value="overdue" <?php echo $status_filter == 'overdue' ? 'selected' : ''; ?>>Overdue</option>
                                            </select>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">My Invoices</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Invoice #</th>
                                                    <th>Property/Unit</th>
                                                    <th>Description</th>
                                                    <th>Amount</th>
                                                    <th>Balance</th>
                                                    <th>Due Date</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($invoice = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($invoice['property_name']); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($invoice['unit_number']); ?></p>
                                                                </div>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($invoice['description'] ?? $invoice['type']); ?></td>
                                                            <td>KES <?php echo number_format($invoice['total_amount'], 2); ?></td>
                                                            <td>
                                                                <span class="fw-semibold <?php echo $invoice['balance'] > 0 ? 'text-danger' : 'text-success'; ?>">
                                                                    KES <?php echo number_format($invoice['balance'], 2); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo date('M d, Y', strtotime($invoice['due_date'])); ?></td>
                                                            <td>
                                                                <?php
                                                                $status_colors = [
                                                                    'paid' => 'success',
                                                                    'unpaid' => 'danger',
                                                                    'partial' => 'warning',
                                                                    'overdue' => 'danger'
                                                                ];
                                                                $color = $status_colors[$invoice['status']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $color; ?> text-<?php echo $color; ?>">
                                                                    <?php echo ucfirst($invoice['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if ($invoice['balance'] > 0): ?>
                                                                    <a href="pay_rent.php?invoice_id=<?php echo $invoice['id']; ?>" 
                                                                       class="btn btn-primary btn-sm">
                                                                        <i class="ri-money-dollar-circle-line me-1"></i>Pay
                                                                    </a>
                                                                <?php endif; ?>
                                                                <a href="print_invoice.php?id=<?php echo $invoice['id']; ?>" 
                                                                   target="_blank" class="btn btn-soft-secondary btn-sm">
                                                                    <i class="ri-printer-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="8" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No invoices found</p>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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

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