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

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

$user_id = $_SESSION['user_id'];

// Get vendor ID from user
$sql_vendor = "SELECT id FROM vendors WHERE user_id = ?";
$stmt_vendor = $conn->prepare($sql_vendor);
$stmt_vendor->bind_param("i", $user_id);
$stmt_vendor->execute();
$result_vendor = $stmt_vendor->get_result();
$vendor = $result_vendor->fetch_assoc();

if (!$vendor) {
    header('Location: index.php');
    exit();
}

$vendor_id = $vendor['id'];

$sql = "SELECT mr.*, p.name as property_name, u.unit_number,
               t.first_name, t.last_name, t.phone
        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
        WHERE mr.assigned_vendor_id = ?
        AND mr.status IN ('Assigned', 'In Progress')
        ORDER BY 
            CASE mr.priority 
                WHEN 'Emergency' THEN 1 
                WHEN 'High' THEN 2 
                WHEN 'Medium' THEN 3 
                ELSE 4 
            END, 
            mr.scheduled_date ASC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $vendor_id);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php include 'layouts/main.php'; ?>

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

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Assigned 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>Priority</th>
                                                    <th>Scheduled</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
                                                                $priority_colors = [
                                                                    'Emergency' => 'danger',
                                                                    'High' => 'warning',
                                                                    'Medium' => 'info',
                                                                    'Low' => 'secondary'
                                                                ];
                                                                $priority_color = $priority_colors[$work_order['priority']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $priority_color; ?> text-<?php echo $priority_color; ?>">
                                                                    <?php echo htmlspecialchars($work_order['priority']); ?>
                                                                </span>
                                                            </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>
                                                                <span class="badge bg-soft-warning text-warning">
                                                                    <?php echo htmlspecialchars($work_order['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if ($work_order['status'] == 'Assigned'): ?>
                                                                    <button class="btn btn-primary btn-sm" 
                                                                            onclick="startWork(<?php echo $work_order['id']; ?>)">
                                                                        <i class="ri-play-line me-1"></i>Start Work
                                                                    </button>
                                                                <?php elseif ($work_order['status'] == 'In Progress'): ?>
                                                                    <button class="btn btn-success btn-sm" 
                                                                            onclick="completeWork(<?php echo $work_order['id']; ?>)">
                                                                        <i class="ri-check-line me-1"></i>Complete
                                                                    </button>
                                                                <?php endif; ?>
                                                            </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 work orders assigned</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'; ?>
    <script>
        function startWork(requestId) {
            window.location.href = 'update_maintenance_status.php?id=' + requestId + '&status=In Progress';
        }
        function completeWork(requestId) {
            window.location.href = 'update_maintenance_status.php?id=' + requestId + '&status=Completed';
        }
    </script>
</body>
</html>
