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

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

$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$method_filter = $_GET['method'] ?? '';
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

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

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

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

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

if (!empty($method_filter)) {
    $sql .= " AND rp.payment_method = ?";
    $params[] = $method_filter;
    $types .= 's';
}

if (!empty($start_date)) {
    $sql .= " AND rp.payment_date >= ?";
    $params[] = $start_date;
    $types .= 's';
}

if (!empty($end_date)) {
    $sql .= " AND rp.payment_date <= ?";
    $params[] = $end_date;
    $types .= 's';
}

$sql .= " ORDER BY rp.payment_date DESC";

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' => 'Payments')); ?>
    <?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' => 'Payments Received')); ?>

                    <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">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search); ?>" 
                                                   placeholder="Search by reference or tenant">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status">
                                                <option value="">All Status</option>
                                                <option value="COMPLETED" <?php echo $status_filter == 'COMPLETED' ? 'selected' : ''; ?>>Completed</option>
                                                <option value="PENDING" <?php echo $status_filter == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                                <option value="FAILED" <?php echo $status_filter == 'FAILED' ? 'selected' : ''; ?>>Failed</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Method</label>
                                            <select class="form-select" name="method">
                                                <option value="">All Methods</option>
                                                <option value="M-Pesa" <?php echo $method_filter == 'M-Pesa' ? 'selected' : ''; ?>>M-Pesa</option>
                                                <option value="Bank Transfer" <?php echo $method_filter == 'Bank Transfer' ? 'selected' : ''; ?>>Bank Transfer</option>
                                                <option value="Cash" <?php echo $method_filter == 'Cash' ? 'selected' : ''; ?>>Cash</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Start Date</label>
                                            <input type="date" class="form-control" name="start_date" 
                                                   value="<?php echo htmlspecialchars($start_date); ?>">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">End Date</label>
                                            <input type="date" class="form-control" name="end_date" 
                                                   value="<?php echo htmlspecialchars($end_date); ?>">
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label">&nbsp;</label>
                                            <div>
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="ri-search-line"></i>
                                                </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">Payment History</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Payment Date</th>
                                                    <th>Reference</th>
                                                    <th>Tenant</th>
                                                    <th>Property/Unit</th>
                                                    <th>Invoice</th>
                                                    <th>Amount</th>
                                                    <th>Method</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php 
                                                    $total_amount = 0;
                                                    while($payment = $result->fetch_assoc()): 
                                                        $total_amount += $payment['amount'];
                                                    ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($payment['payment_date'])); ?></td>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($payment['payment_reference'] ?? 'N/A'); ?></span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <?php echo htmlspecialchars($payment['first_name'] . ' ' . $payment['last_name']); ?>
                                                                    </h5>
                                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($payment['email'] ?? ''); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($payment['property_name'] ?? 'N/A'); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($payment['unit_number'] ?? 'N/A'); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <a href="invoice_details.php?id=<?php echo $payment['invoice_id']; ?>" class="text-primary">
                                                                    <?php echo htmlspecialchars($payment['invoice_number'] ?? 'N/A'); ?>
                                                                </a>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($payment['amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($payment['payment_method'] ?? 'N/A'); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status_colors = [
                                                                    'COMPLETED' => 'success',
                                                                    'PENDING' => 'warning',
                                                                    'FAILED' => 'danger'
                                                                ];
                                                                $color = $status_colors[$payment['payment_status']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $color; ?> text-<?php echo $color; ?>">
                                                                    <?php echo $payment['payment_status']; ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <a href="payment_details.php?id=<?php echo $payment['payment_id']; ?>" class="btn btn-soft-secondary btn-sm">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                    <tr class="table-light">
                                                        <td colspan="5" class="text-end fw-bold">Total:</td>
                                                        <td class="fw-bold">KES <?php echo number_format($total_amount, 2); ?></td>
                                                        <td colspan="3"></td>
                                                    </tr>
                                                <?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 payments 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>
