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

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

$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$property_id = $_GET['property_id'] ?? '';

$sql = "SELECT i.*, t.first_name, t.last_name, t.email, 
               p.property_name, u.unit_number, l.lease_code
        FROM invoices i
        LEFT JOIN tenants t ON i.tenant_id = t.tenant_id
        LEFT JOIN leases l ON i.lease_id = l.lease_id
        LEFT JOIN units u ON l.unit_id = u.unit_id
        LEFT JOIN properties p ON u.property_id = p.property_id
        WHERE 1=1";

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

if (!empty($search)) {
    $sql .= " AND (i.invoice_number LIKE ? OR t.first_name LIKE ? OR t.last_name LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'sss';
}

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

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

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

// Get properties for filter
$sql_properties = "SELECT * FROM properties ORDER BY property_name";
$result_properties = $conn->query($sql_properties);

if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => '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' => 'Financials', 'title' => '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-4">
                                            <label class="form-label">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search); ?>" 
                                                   placeholder="Search by invoice number or tenant">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Property</label>
                                            <select class="form-select" name="property_id">
                                                <option value="">All Properties</option>
                                                <?php while($prop = $result_properties->fetch_assoc()): ?>
                                                    <option value="<?php echo $prop['property_id']; ?>" 
                                                            <?php echo $property_id == $prop['property_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($prop['property_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status">
                                                <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>
                                        <div class="col-md-2">
                                            <label class="form-label">&nbsp;</label>
                                            <div>
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="ri-search-line me-1"></i>Filter
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">All Invoices</h4>
                                    <div class="flex-shrink-0">
                                        <button class="btn btn-success" onclick="generateMonthlyInvoices()">
                                            <i class="ri-file-add-line align-bottom me-1"></i>Generate Monthly Invoices
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Invoice #</th>
                                                    <th>Tenant</th>
                                                    <th>Property/Unit</th>
                                                    <th>Type</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()): ?>
                                                        <?php
                                                        $due_date = strtotime($invoice['due_date']);
                                                        $today = strtotime('today');
                                                        $is_overdue = $due_date < $today && $invoice['status'] != 'PAID';
                                                        ?>
                                                        <tr>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($invoice['invoice_number']); ?></span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <?php echo htmlspecialchars($invoice['first_name'] . ' ' . $invoice['last_name']); ?>
                                                                    </h5>
                                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($invoice['email'] ?? ''); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($invoice['property_name'] ?? 'N/A'); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($invoice['unit_number'] ?? 'N/A'); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($invoice['invoice_type'] ?? 'Rent'); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($invoice['total_amount'], 2); ?></span>
                                                            </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 if ($is_overdue): ?>
                                                                    <span class="text-danger"><?php echo date('M d, Y', $due_date); ?></span>
                                                                    <small class="d-block text-danger">Overdue</small>
                                                                <?php else: ?>
                                                                    <?php echo date('M d, Y', $due_date); ?>
                                                                <?php endif; ?>
                                                            </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 $invoice['status']; ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-soft-secondary btn-sm dropdown-toggle" 
                                                                            type="button" data-bs-toggle="dropdown">
                                                                        Actions
                                                                    </button>
                                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                                        <li>
                                                                            <a class="dropdown-item" href="invoice_details.php?id=<?php echo $invoice['invoice_id']; ?>">
                                                                                <i class="ri-eye-line align-bottom me-2 text-muted"></i>View
                                                                            </a>
                                                                        </li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="print_invoice.php?id=<?php echo $invoice['invoice_id']; ?>" target="_blank">
                                                                                <i class="ri-printer-line align-bottom me-2 text-muted"></i>Print
                                                                            </a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="9" 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'; ?>
    <script>
        function generateMonthlyInvoices() {
            if (confirm('Generate monthly rent invoices for all active leases?')) {
                window.location.href = 'generate_invoices.php';
            }
        }
    </script>
</body>
</html>
