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

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

$user_id = $_SESSION['user_id'];
$month = $_GET['month'] ?? date('Y-m');

$sql = "SELECT 
            'Revenue' as type,
            rp.payment_date as date,
            CONCAT('Rent - ', i.invoice_number) as description,
            rp.amount as amount,
            'credit' as transaction_type
        FROM rent_payments rp
        JOIN leases l ON rp.lease_id = l.id
        JOIN units u ON l.unit_id = u.id
        JOIN properties p ON u.property_id = p.id
        LEFT JOIN invoices i ON rp.invoice_id = i.id
        WHERE p.owner_id = ?
        AND rp.payment_status = 'COMPLETED'
        AND DATE_FORMAT(rp.payment_date, '%Y-%m') = ?
        
        UNION ALL
        
        SELECT 
            'Expense' as type,
            e.incurred_date as date,
            CONCAT(e.category, ' - ', e.description) as description,
            e.amount as amount,
            'debit' as transaction_type
        FROM expenses e
        JOIN properties p ON e.property_id = p.id
        WHERE p.owner_id = ?
        AND e.status = 'paid'
        AND DATE_FORMAT(e.incurred_date, '%Y-%m') = ?
        
        ORDER BY date DESC";

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

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

                    <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">Month</label>
                                            <input type="month" class="form-control" name="month" 
                                                   value="<?php echo htmlspecialchars($month); ?>">
                                        </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>View
                                                </button>
                                            </div>
                                        </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">Statement for <?php echo date('F Y', strtotime($month . '-01')); ?></h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Type</th>
                                                    <th>Description</th>
                                                    <th class="text-end">Debit</th>
                                                    <th class="text-end">Credit</th>
                                                    <th class="text-end">Balance</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $balance = 0;
                                                if ($result && $result->num_rows > 0): 
                                                ?>
                                                    <?php while($transaction = $result->fetch_assoc()): 
                                                        if ($transaction['transaction_type'] == 'credit') {
                                                            $balance += $transaction['amount'];
                                                        } else {
                                                            $balance -= $transaction['amount'];
                                                        }
                                                    ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($transaction['date'])); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-<?php echo $transaction['type'] == 'Revenue' ? 'success' : 'danger'; ?>">
                                                                    <?php echo htmlspecialchars($transaction['type']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($transaction['description']); ?></td>
                                                            <td class="text-end">
                                                                <?php if ($transaction['transaction_type'] == 'debit'): ?>
                                                                    <span class="text-danger">KES <?php echo number_format($transaction['amount'], 2); ?></span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">-</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td class="text-end">
                                                                <?php if ($transaction['transaction_type'] == 'credit'): ?>
                                                                    <span class="text-success">KES <?php echo number_format($transaction['amount'], 2); ?></span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">-</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td class="text-end fw-semibold">
                                                                KES <?php echo number_format($balance, 2); ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="6" class="text-center py-4">
                                                            <div class="text-muted">No transactions found</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>
