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

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

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

$sql = "SELECT e.*, p.name as property_name, v.company_name as vendor_name
        FROM expenses e
        LEFT JOIN properties p ON e.property_id = p.id
        LEFT JOIN vendors v ON e.vendor_id = v.id
        WHERE p.owner_id = ?
        AND e.incurred_date BETWEEN ? AND ?";

$params = [$user_id, $start_date, $end_date];
$types = 'iss';

if (!empty($property_id)) {
    $sql .= " AND e.property_id = ?";
    $params[] = $property_id;
    $types .= 'i';
}

$sql .= " ORDER BY e.incurred_date DESC";

// Get properties for filter
$sql_properties = "SELECT * FROM properties WHERE owner_id = ? ORDER BY name";
$stmt_prop = $conn->prepare($sql_properties);
$stmt_prop->bind_param("i", $user_id);
$stmt_prop->execute();
$result_properties = $stmt_prop->get_result();

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

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

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

                    <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">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">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">&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">Expense History</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>Property</th>
                                                    <th>Category</th>
                                                    <th>Description</th>
                                                    <th>Vendor</th>
                                                    <th>Amount</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($expense = $result->fetch_assoc()): 
                                                        $total_expenses += $expense['amount'];
                                                    ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($expense['incurred_date'])); ?></td>
                                                            <td><?php echo htmlspecialchars($expense['property_name'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($expense['category']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($expense['description'] ?? 'N/A'); ?></td>
                                                            <td><?php echo htmlspecialchars($expense['vendor_name'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <span class="fw-semibold text-danger">KES <?php echo number_format($expense['amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-success text-success">
                                                                    <?php echo ucfirst(str_replace('_', ' ', $expense['status'])); ?>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                    <tr class="table-light">
                                                        <td colspan="5" class="text-end fw-bold">Total:</td>
                                                        <td class="fw-bold text-danger">KES <?php echo number_format($total_expenses, 2); ?></td>
                                                        <td></td>
                                                    </tr>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center py-4">
                                                            <div class="text-muted">No expenses 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>
