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

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

$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-t');

// Get bank transactions (from payments table)
$sql_bank = "SELECT rp.*, t.first_name, t.last_name, l.lease_code, 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 invoices i ON rp.invoice_id = i.invoice_id
             WHERE rp.payment_method = 'Bank Transfer'
             AND rp.payment_date BETWEEN ? AND ?
             ORDER BY rp.payment_date DESC";

$stmt = $conn->prepare($sql_bank);
$stmt->bind_param("ss", $start_date, $end_date);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php include 'layouts/main.php'; ?>

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

                    <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">Start Date</label>
                                            <input type="date" class="form-control" name="start_date" 
                                                   value="<?php echo htmlspecialchars($start_date); ?>">
                                        </div>
                                        <div class="col-md-4">
                                            <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-4">
                                            <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">Bank Reconciliation</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>Tenant</th>
                                                    <th>Invoice</th>
                                                    <th>Amount</th>
                                                    <th>Status</th>
                                                    <th>Verified</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($transaction = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($transaction['payment_date'])); ?></td>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($transaction['payment_reference']); ?></span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <?php echo htmlspecialchars($transaction['first_name'] . ' ' . $transaction['last_name']); ?>
                                                                    </h5>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <a href="invoice_details.php?id=<?php echo $transaction['invoice_id']; ?>" class="text-primary">
                                                                    <?php echo htmlspecialchars($transaction['invoice_number'] ?? 'N/A'); ?>
                                                                </a>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($transaction['amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status_colors = [
                                                                    'COMPLETED' => 'success',
                                                                    'PENDING' => 'warning',
                                                                    'FAILED' => 'danger'
                                                                ];
                                                                $color = $status_colors[$transaction['payment_status']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $color; ?> text-<?php echo $color; ?>">
                                                                    <?php echo $transaction['payment_status']; ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if ($transaction['payment_status'] == 'COMPLETED'): ?>
                                                                    <span class="badge bg-soft-success text-success">Verified</span>
                                                                <?php else: ?>
                                                                    <span class="badge bg-soft-warning text-warning">Pending</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($transaction['payment_status'] == 'PENDING'): ?>
                                                                    <button class="btn btn-soft-success btn-sm" 
                                                                            onclick="verifyPayment(<?php echo $transaction['payment_id']; ?>)">
                                                                        <i class="ri-check-line"></i> Verify
                                                                    </button>
                                                                <?php else: ?>
                                                                    <a href="payment_details.php?id=<?php echo $transaction['payment_id']; ?>" 
                                                                       class="btn btn-soft-secondary btn-sm">
                                                                        <i class="ri-eye-line"></i>
                                                                    </a>
                                                                <?php endif; ?>
                                                            </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 bank transactions 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 verifyPayment(paymentId) {
            if (confirm('Verify this payment?')) {
                window.location.href = 'verify_payment.php?id=' + paymentId;
            }
        }
    </script>
</body>
</html>
