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

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

$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$vendor_id = $_GET['vendor_id'] ?? '';

$sql = "SELECT mr.*, p.name as property_name, u.unit_number, 
               t.first_name, t.last_name, t.phone,
               v.company_name as vendor_name
        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 users t ON mr.requester_id = t.id
        LEFT JOIN vendors v ON mr.assigned_vendor_id = v.id
        WHERE mr.status IN ('ASSIGNED', 'IN_PROGRESS', 'COMPLETED')";

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

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

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

if (!empty($vendor_id)) {
    $sql .= " AND mr.assigned_vendor_id = ?";
    $params[] = $vendor_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.scheduled_date ASC";

// Get vendors for filter
$sql_vendors = "SELECT * FROM vendors WHERE status = 'active' ORDER BY company_name";
$result_vendors = $conn->query($sql_vendors);

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' => 'Work Orders')); ?>
    <?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' => 'Work Orders')); ?>

                    <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 ticket number or tenant">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Vendor</label>
                                            <select class="form-select" name="vendor_id">
                                                <option value="">All Vendors</option>
                                                <?php while($vendor = $result_vendors->fetch_assoc()): ?>
                                                    <option value="<?php echo $vendor['id']; ?>" 
                                                            <?php echo $vendor_id == $vendor['id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($vendor['company_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status">
                                                <option value="">All Status</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-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 Work Orders</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Ticket #</th>
                                                    <th>Property/Unit</th>
                                                    <th>Tenant</th>
                                                    <th>Category</th>
                                                    <th>Vendor</th>
                                                    <th>Scheduled</th>
                                                    <th>Cost</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($work_order = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($work_order['ticket_number']); ?></span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($work_order['property_name'] ?? 'N/A'); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($work_order['unit_number'] ?? 'N/A'); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <?php echo htmlspecialchars($work_order['first_name'] . ' ' . $work_order['last_name']); ?>
                                                                    </h5>
                                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($work_order['phone'] ?? ''); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($work_order['category']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if ($work_order['vendor_name']): ?>
                                                                    <span class="fw-semibold"><?php echo htmlspecialchars($work_order['vendor_name']); ?></span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">Unassigned</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($work_order['scheduled_date']): ?>
                                                                    <?php echo date('M d, Y H:i', strtotime($work_order['scheduled_date'])); ?>
                                                                <?php else: ?>
                                                                    <span class="text-muted">Not scheduled</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($work_order['final_cost']): ?>
                                                                    <span class="fw-semibold">KES <?php echo number_format($work_order['final_cost'], 2); ?></span>
                                                                <?php elseif ($work_order['cost_estimate']): ?>
                                                                    <span class="text-muted">Est: KES <?php echo number_format($work_order['cost_estimate'], 2); ?></span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">-</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status_badges = [
                                                                    'ASSIGNED' => 'badge-soft-warning',
                                                                    'IN_PROGRESS' => 'badge-soft-primary',
                                                                    'COMPLETED' => 'badge-soft-success',
                                                                    'ON_HOLD' => 'badge-soft-secondary'
                                                                ];
                                                                $badge_class = $status_badges[$work_order['status']] ?? 'badge-soft-secondary';
                                                                ?>
                                                                <span class="badge <?php echo $badge_class; ?>">
                                                                    <?php echo str_replace('_', ' ', $work_order['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <a href="work_order_details.php?id=<?php echo $work_order['id']; ?>" 
                                                                   class="btn btn-soft-secondary btn-sm">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="9" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No work orders 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>
