<?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
$sql_revenue = "SELECT SUM(amount) as total FROM rent_payments 
                WHERE payment_status = 'COMPLETED' AND payment_date BETWEEN ? AND ?";
$params_rev = [$start_date, $end_date];
$types_rev = 'ss';

if (!empty($property_id)) {
    $sql_revenue = "SELECT SUM(rp.amount) as total FROM rent_payments rp
                    JOIN leases l ON rp.lease_id = l.lease_id
                    JOIN units u ON l.unit_id = u.unit_id
                    WHERE rp.payment_status = 'COMPLETED' 
                    AND rp.payment_date BETWEEN ? AND ?
                    AND u.property_id = ?";
    $params_rev[] = $property_id;
    $types_rev .= 'i';
}

$stmt_rev = $conn->prepare($sql_revenue);
$stmt_rev->bind_param($types_rev, ...$params_rev);
$stmt_rev->execute();
$result_rev = $stmt_rev->get_result();
$revenue = $result_rev->fetch_assoc()['total'] ?? 0;

// Expenses
$sql_expenses = "SELECT SUM(amount) as total FROM expenses 
                 WHERE status = 'paid' AND incurred_date BETWEEN ? AND ?";
$params_exp = [$start_date, $end_date];
$types_exp = 'ss';

if (!empty($property_id)) {
    $sql_expenses = "SELECT SUM(amount) as total FROM expenses 
                     WHERE status = 'paid' AND incurred_date BETWEEN ? AND ? AND property_id = ?";
    $params_exp[] = $property_id;
    $types_exp .= 'i';
}

$stmt_exp = $conn->prepare($sql_expenses);
$stmt_exp->bind_param($types_exp, ...$params_exp);
$stmt_exp->execute();
$result_exp = $stmt_exp->get_result();
$expenses = $result_exp->fetch_assoc()['total'] ?? 0;

$profit = $revenue - $expenses;
$profit_margin = $revenue > 0 ? ($profit / $revenue) * 100 : 0;

// 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' => 'Profit & Loss Report')); ?>
    <?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' => 'Profit & Loss Report')); ?>

                    <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 Report
                                                </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">Profit & Loss Statement</h4>
                                    <p class="text-muted mb-0">
                                        Period: <?php echo date('M d, Y', strtotime($start_date)); ?> to <?php echo date('M d, Y', strtotime($end_date)); ?>
                                    </p>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-4">
                                        <div class="col-md-4">
                                            <div class="card bg-soft-success">
                                                <div class="card-body text-center">
                                                    <h6 class="text-muted mb-2">Total Revenue</h6>
                                                    <h3 class="text-success mb-0">KES <?php echo number_format($revenue, 2); ?></h3>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="card bg-soft-danger">
                                                <div class="card-body text-center">
                                                    <h6 class="text-muted mb-2">Total Expenses</h6>
                                                    <h3 class="text-danger mb-0">KES <?php echo number_format($expenses, 2); ?></h3>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="card bg-soft-<?php echo $profit >= 0 ? 'success' : 'danger'; ?>">
                                                <div class="card-body text-center">
                                                    <h6 class="text-muted mb-2">Net Profit/Loss</h6>
                                                    <h3 class="text-<?php echo $profit >= 0 ? 'success' : 'danger'; ?> mb-0">
                                                        KES <?php echo number_format($profit, 2); ?>
                                                    </h3>
                                                    <small class="text-muted">Margin: <?php echo number_format($profit_margin, 2); ?>%</small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Item</th>
                                                    <th class="text-end">Amount (KES)</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td><strong>REVENUE</strong></td>
                                                    <td class="text-end"><strong><?php echo number_format($revenue, 2); ?></strong></td>
                                                </tr>
                                                <tr>
                                                    <td>&nbsp;&nbsp;Rental Income</td>
                                                    <td class="text-end"><?php echo number_format($revenue, 2); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>EXPENSES</strong></td>
                                                    <td class="text-end"><strong><?php echo number_format($expenses, 2); ?></strong></td>
                                                </tr>
                                                <tr class="table-light">
                                                    <td><strong>NET PROFIT/LOSS</strong></td>
                                                    <td class="text-end">
                                                        <strong class="text-<?php echo $profit >= 0 ? 'success' : 'danger'; ?>">
                                                            <?php echo number_format($profit, 2); ?>
                                                        </strong>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>

                                    <div class="mt-3">
                                        <button class="btn btn-success" onclick="window.print()">
                                            <i class="ri-printer-line me-1"></i>Print Report
                                        </button>
                                        <button class="btn btn-primary ms-2" onclick="exportPNL()">
                                            <i class="ri-download-line me-1"></i>Export
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        function exportPNL() {
            window.location.href = 'export_pnl.php?start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&property_id=<?php echo $property_id; ?>';
        }
    </script>
</body>
</html>
