<?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');
$property_id = $_GET['property_id'] ?? '';

// Revenue summary
$sql_revenue = "SELECT 
                    DATE_FORMAT(payment_date, '%Y-%m') as month,
                    SUM(amount) as revenue
                FROM rent_payments 
                WHERE payment_status = 'COMPLETED' 
                AND payment_date BETWEEN ? AND ?
                GROUP BY DATE_FORMAT(payment_date, '%Y-%m')
                ORDER BY month";

$stmt_rev = $conn->prepare($sql_revenue);
$stmt_rev->bind_param("ss", $start_date, $end_date);
$stmt_rev->execute();
$result_revenue = $stmt_rev->get_result();

// Expense summary
$sql_expenses = "SELECT 
                    category,
                    SUM(amount) as total
                FROM expenses 
                WHERE status = 'paid' 
                AND incurred_date BETWEEN ? AND ?
                GROUP BY category
                ORDER BY total DESC";

$stmt_exp = $conn->prepare($sql_expenses);
$stmt_exp->bind_param("ss", $start_date, $end_date);
$stmt_exp->execute();
$result_expenses = $stmt_exp->get_result();

// Get properties for filter
$sql_properties = "SELECT * FROM properties ORDER BY name";
$result_properties = $conn->query($sql_properties);
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Financial Reports')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</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' => 'Reports', 'title' => 'Financial Reports')); ?>

                    <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">Start Date</label>
                                            <input type="date" class="form-control" name="start_date" 
                                                   value="<?php echo htmlspecialchars($start_date); ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <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-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['id']; ?>" 
                                                            <?php echo $property_id == $prop['id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($prop['name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">&nbsp;</label>
                                            <div>
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="ri-search-line me-1"></i>Generate
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Revenue Trend</h4>
                                </div>
                                <div class="card-body">
                                    <div style="height: 300px;">
                                        <canvas id="revenueChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Expenses by Category</h4>
                                </div>
                                <div class="card-body">
                                    <div style="height: 300px;">
                                        <canvas id="expensesChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        // Revenue Chart
        const revenueData = {
            labels: [<?php 
                $months = [];
                while($row = $result_revenue->fetch_assoc()) {
                    $months[] = "'" . date('M Y', strtotime($row['month'] . '-01')) . "'";
                }
                echo implode(',', $months);
            ?>],
            datasets: [{
                label: 'Revenue (KES)',
                data: [<?php 
                    $result_revenue->data_seek(0);
                    $amounts = [];
                    while($row = $result_revenue->fetch_assoc()) {
                        $amounts[] = $row['revenue'];
                    }
                    echo implode(',', $amounts);
                ?>],
                borderColor: 'rgb(75, 192, 192)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                tension: 0.4
            }]
        };

        new Chart(document.getElementById('revenueChart'), {
            type: 'line',
            data: revenueData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });

        // Expenses Chart
        const expensesData = {
            labels: [<?php 
                $categories = [];
                while($row = $result_expenses->fetch_assoc()) {
                    $categories[] = "'" . $row['category'] . "'";
                }
                echo implode(',', $categories);
            ?>],
            datasets: [{
                data: [<?php 
                    $result_expenses->data_seek(0);
                    $exp_amounts = [];
                    while($row = $result_expenses->fetch_assoc()) {
                        $exp_amounts[] = $row['total'];
                    }
                    echo implode(',', $exp_amounts);
                ?>],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.8)',
                    'rgba(54, 162, 235, 0.8)',
                    'rgba(255, 206, 86, 0.8)',
                    'rgba(75, 192, 192, 0.8)',
                    'rgba(153, 102, 255, 0.8)'
                ]
            }]
        };

        new Chart(document.getElementById('expensesChart'), {
            type: 'pie',
            data: expensesData,
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });
    </script>
</body>
</html>
