<?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', strtotime('-1 month'));
$end_date = $_GET['end_date'] ?? date('Y-m-t');
$property_id = $_GET['property_id'] ?? '';

$sql = "SELECT mr.*, p.name as property_name, u.unit_number,
               v.company_name as vendor_name,
               COUNT(*) as total_requests
        FROM maintenance_requests mr
        LEFT JOIN properties p ON mr.property_id = p.id
        LEFT JOIN units u ON mr.unit_id = u.id
        LEFT JOIN vendors v ON mr.assigned_vendor_id = v.id
        WHERE mr.created_at BETWEEN ? AND ?";

$params = [$start_date, $end_date];
$types = 'ss';

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

$sql .= " GROUP BY mr.category, mr.status
          ORDER BY total_requests DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->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' => 'Maintenance 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' => 'Reports', 'title' => 'Maintenance 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">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>Generate
                                                </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">Maintenance Report</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Category</th>
                                                    <th>Status</th>
                                                    <th>Total Requests</th>
                                                    <th>Average Cost</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($row = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($row['category']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-primary text-primary">
                                                                    <?php echo htmlspecialchars($row['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo $row['total_requests']; ?></td>
                                                            <td>
                                                                <?php if ($row['final_cost']): ?>
                                                                    KES <?php echo number_format($row['final_cost'], 2); ?>
                                                                <?php else: ?>
                                                                    <span class="text-muted">N/A</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="4" class="text-center py-4">
                                                            <div class="text-muted">No maintenance data 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>
