<?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 all transactions (revenue and expenses)
$sql = "SELECT 
            'Revenue' as type,
            rp.payment_date as transaction_date,
            CONCAT('Rent Payment - ', i.invoice_number) as description,
            rp.amount as debit,
            0 as credit,
            'RENT' as account
        FROM rent_payments rp
        LEFT JOIN invoices i ON rp.invoice_id = i.id
        WHERE rp.payment_status = 'COMPLETED'
        AND rp.payment_date BETWEEN ? AND ?
        
        UNION ALL
        
        SELECT 
            'Expense' as type,
            e.incurred_date as transaction_date,
            CONCAT(e.category, ' - ', e.description) as description,
            0 as debit,
            e.amount as credit,
            e.category as account
        FROM expenses e
        WHERE e.status = 'paid'
        AND e.incurred_date BETWEEN ? AND ?
        
        ORDER BY transaction_date DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss", $start_date, $end_date, $start_date, $end_date);
$stmt->execute();
$result = $stmt->get_result();

$total_debit = 0;
$total_credit = 0;
?>
<?php include 'layouts/main.php'; ?>

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

                    <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">
                                    <h4 class="card-title mb-0">General Ledger</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Account</th>
                                                    <th>Description</th>
                                                    <th>Type</th>
                                                    <th class="text-end">Debit</th>
                                                    <th class="text-end">Credit</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($transaction = $result->fetch_assoc()): 
                                                        $total_debit += $transaction['debit'];
                                                        $total_credit += $transaction['credit'];
                                                    ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($transaction['transaction_date'])); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($transaction['account']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($transaction['description']); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-<?php echo $transaction['type'] == 'Revenue' ? 'success' : 'danger'; ?>">
                                                                    <?php echo htmlspecialchars($transaction['type']); ?>
                                                                </span>
                                                            </td>
                                                            <td class="text-end">
                                                                <?php if ($transaction['debit'] > 0): ?>
                                                                    <span class="text-success">KES <?php echo number_format($transaction['debit'], 2); ?></span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">-</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td class="text-end">
                                                                <?php if ($transaction['credit'] > 0): ?>
                                                                    <span class="text-danger">KES <?php echo number_format($transaction['credit'], 2); ?></span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">-</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                    <tr class="table-light">
                                                        <td colspan="4" class="text-end fw-bold">TOTALS:</td>
                                                        <td class="text-end fw-bold text-success">KES <?php echo number_format($total_debit, 2); ?></td>
                                                        <td class="text-end fw-bold text-danger">KES <?php echo number_format($total_credit, 2); ?></td>
                                                    </tr>
                                                    <tr class="table-light">
                                                        <td colspan="4" class="text-end fw-bold">BALANCE:</td>
                                                        <td colspan="2" class="text-end fw-bold text-<?php echo ($total_debit - $total_credit) >= 0 ? 'success' : 'danger'; ?>">
                                                            KES <?php echo number_format($total_debit - $total_credit, 2); ?>
                                                        </td>
                                                    </tr>
                                                <?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>
