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

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

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

$sql = "SELECT mr.*, p.property_name, p.property_code, u.unit_number, 
               t.first_name, t.last_name, t.phone
        FROM maintenance_requests mr
        LEFT JOIN properties p ON mr.property_id = p.property_id
        LEFT JOIN units u ON mr.unit_id = u.unit_id
        LEFT JOIN tenants t ON mr.tenant_id = t.tenant_id
        WHERE 1=1";

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

if (!empty($search)) {
    $sql .= " AND (mr.request_code LIKE ? OR t.first_name LIKE ? OR t.last_name LIKE ? OR p.property_name LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ssss';
}

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

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

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

$sql .= " ORDER BY 
            CASE mr.priority 
                WHEN 'EMERGENCY' THEN 1 
                WHEN 'HIGH' THEN 2 
                WHEN 'MEDIUM' THEN 3 
                ELSE 4 
            END, 
            mr.created_at DESC";

// Get properties for filter
$sql_properties = "SELECT * FROM properties ORDER BY property_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' => 'Maintenance Requests')); ?>
    <?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' => 'Maintenance', 'title' => 'Maintenance Requests')); ?>

                    <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 request code or tenant">
                                        </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['property_id']; ?>" 
                                                            <?php echo $property_id == $prop['property_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($prop['property_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </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="NEW" <?php echo $status_filter == 'NEW' ? 'selected' : ''; ?>>New</option>
                                                <option value="ASSIGNED" <?php echo $status_filter == 'ASSIGNED' ? 'selected' : ''; ?>>Assigned</option>
                                                <option value="IN_PROGRESS" <?php echo $status_filter == 'IN_PROGRESS' ? 'selected' : ''; ?>>In Progress</option>
                                                <option value="COMPLETED" <?php echo $status_filter == 'COMPLETED' ? 'selected' : ''; ?>>Completed</option>
                                            </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="PLUMBING" <?php echo $category_filter == 'PLUMBING' ? 'selected' : ''; ?>>Plumbing</option>
                                                <option value="ELECTRICAL" <?php echo $category_filter == 'ELECTRICAL' ? 'selected' : ''; ?>>Electrical</option>
                                                <option value="HVAC" <?php echo $category_filter == 'HVAC' ? 'selected' : ''; ?>>HVAC</option>
                                                <option value="APPLIANCE" <?php echo $category_filter == 'APPLIANCE' ? 'selected' : ''; ?>>Appliance</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 Maintenance Requests</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Request Code</th>
                                                    <th>Property/Unit</th>
                                                    <th>Tenant</th>
                                                    <th>Category</th>
                                                    <th>Priority</th>
                                                    <th>Status</th>
                                                    <th>Created</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($request = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($request['request_code']); ?></span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($request['property_name'] ?? 'N/A'); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($request['unit_number'] ?? 'N/A'); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <?php echo htmlspecialchars($request['first_name'] . ' ' . $request['last_name']); ?>
                                                                    </h5>
                                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($request['phone'] ?? ''); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $category_badges = [
                                                                    'PLUMBING' => 'badge-soft-info',
                                                                    'ELECTRICAL' => 'badge-soft-warning',
                                                                    'HVAC' => 'badge-soft-danger',
                                                                    'APPLIANCE' => 'badge-soft-primary',
                                                                    'STRUCTURAL' => 'badge-soft-secondary',
                                                                    'PEST' => 'badge-soft-success'
                                                                ];
                                                                $badge_class = $category_badges[$request['category']] ?? 'badge-soft-secondary';
                                                                ?>
                                                                <span class="badge <?php echo $badge_class; ?>">
                                                                    <?php echo htmlspecialchars($request['category']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $priority_colors = [
                                                                    'EMERGENCY' => 'danger',
                                                                    'HIGH' => 'warning',
                                                                    'MEDIUM' => 'info',
                                                                    'LOW' => 'secondary'
                                                                ];
                                                                $priority_color = $priority_colors[$request['priority']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $priority_color; ?> text-<?php echo $priority_color; ?>">
                                                                    <?php echo htmlspecialchars($request['priority']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status_badges = [
                                                                    'NEW' => 'badge-soft-info',
                                                                    'ASSIGNED' => 'badge-soft-warning',
                                                                    'IN_PROGRESS' => 'badge-soft-primary',
                                                                    'COMPLETED' => 'badge-soft-success',
                                                                    'CANCELLED' => 'badge-soft-danger',
                                                                    'ON_HOLD' => 'badge-soft-secondary'
                                                                ];
                                                                $badge_class = $status_badges[$request['status']] ?? 'badge-soft-secondary';
                                                                ?>
                                                                <span class="badge <?php echo $badge_class; ?>">
                                                                    <?php echo str_replace('_', ' ', $request['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo date('M d, Y', strtotime($request['created_at'])); ?></td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-soft-secondary btn-sm dropdown-toggle" 
                                                                            type="button" data-bs-toggle="dropdown">
                                                                        Actions
                                                                    </button>
                                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                                        <li>
                                                                            <a class="dropdown-item" href="maintenance_request_details.php?id=<?php echo $request['request_id']; ?>">
                                                                                <i class="ri-eye-line align-bottom me-2 text-muted"></i>View
                                                                            </a>
                                                                        </li>
                                                                        <?php if ($request['status'] == 'NEW' || $request['status'] == 'ASSIGNED'): ?>
                                                                        <li>
                                                                            <a class="dropdown-item" href="assign_vendor.php?id=<?php echo $request['request_id']; ?>">
                                                                                <i class="ri-user-add-line align-bottom me-2 text-muted"></i>Assign Vendor
                                                                            </a>
                                                                        </li>
                                                                        <?php endif; ?>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?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 maintenance requests found</p>
                                                            </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>
