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

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

$search = $_GET['search'] ?? '';
$category_filter = $_GET['category'] ?? '';
$status_filter = $_GET['status'] ?? '';
$property_id = $_GET['property_id'] ?? '';
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

$sql = "SELECT e.*, p.name as property_name, p.property_code,
               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 1=1";

$params = [];
$types = '';

if (!empty($search)) {
    $sql .= " AND (e.description LIKE ? OR e.reference_no LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ss';
}

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

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

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

if (!empty($start_date)) {
    $sql .= " AND e.incurred_date >= ?";
    $params[] = $start_date;
    $types .= 's';
}

if (!empty($end_date)) {
    $sql .= " AND e.incurred_date <= ?";
    $params[] = $end_date;
    $types .= 's';
}

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

// Get properties for filter
$sql_properties = "SELECT * FROM properties ORDER BY name";
$result_properties = $conn->query($sql_properties);

if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => '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' => 'Accounting', 'title' => '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">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search); ?>" 
                                                   placeholder="Search by description or reference">
                                        </div>
                                        <div class="col-md-2">
                                            <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-2">
                                            <label class="form-label">Category</label>
                                            <select class="form-select" name="category">
                                                <option value="">All Categories</option>
                                                <option value="Utilities" <?php echo $category_filter == 'Utilities' ? 'selected' : ''; ?>>Utilities</option>
                                                <option value="Repair" <?php echo $category_filter == 'Repair' ? 'selected' : ''; ?>>Repair</option>
                                                <option value="Salary" <?php echo $category_filter == 'Salary' ? 'selected' : ''; ?>>Salary</option>
                                                <option value="Legal" <?php echo $category_filter == 'Legal' ? 'selected' : ''; ?>>Legal</option>
                                                <option value="Marketing" <?php echo $category_filter == 'Marketing' ? 'selected' : ''; ?>>Marketing</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status">
                                                <option value="">All Status</option>
                                                <option value="pending_approval" <?php echo $status_filter == 'pending_approval' ? 'selected' : ''; ?>>Pending</option>
                                                <option value="approved" <?php echo $status_filter == 'approved' ? 'selected' : ''; ?>>Approved</option>
                                                <option value="paid" <?php echo $status_filter == 'paid' ? 'selected' : ''; ?>>Paid</option>
                                            </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>Filter
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">All Expenses</h4>
                                    <div class="flex-shrink-0">
                                        <a href="add_expense.php" class="btn btn-primary">
                                            <i class="ri-add-line align-bottom me-1"></i>Add Expense
                                        </a>
                                    </div>
                                </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>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php 
                                                    $total_amount = 0;
                                                    while($expense = $result->fetch_assoc()): 
                                                        $total_amount += $expense['amount'];
                                                    ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($expense['incurred_date'])); ?></td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($expense['property_name'] ?? 'N/A'); ?></h5>
                                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($expense['property_code'] ?? ''); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($expense['category']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($expense['description'] ?? 'N/A'); ?></span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($expense['vendor_name'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($expense['amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status_colors = [
                                                                    'pending_approval' => 'warning',
                                                                    'approved' => 'info',
                                                                    'paid' => 'success'
                                                                ];
                                                                $color = $status_colors[$expense['status']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $color; ?> text-<?php echo $color; ?>">
                                                                    <?php echo ucfirst(str_replace('_', ' ', $expense['status'])); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <a href="expense_details.php?id=<?php echo $expense['id']; ?>" 
                                                                   class="btn btn-soft-secondary btn-sm">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                    <tr class="table-light">
                                                        <td colspan="5" class="text-end fw-bold">Total:</td>
                                                        <td class="fw-bold">KES <?php echo number_format($total_amount, 2); ?></td>
                                                        <td colspan="2"></td>
                                                    </tr>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="8" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No expenses found</p>
                                                                <a href="add_expense.php" class="btn btn-primary btn-sm mt-2">
                                                                    <i class="ri-add-line me-1"></i>Add First Expense
                                                                </a>
                                                            </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>
