<?php

require_once $_SERVER['DOCUMENT_ROOT'] . '/core/includes/auth.php';
requirePermission('view_network_jobs');

$BASE = app_base_path();

$user_id = $_SESSION['user_id'] ?? 0;

if (!$user_id) {
    redirect_to($BASE . '/login.php');
    exit;
}

/* ===============================
   FETCH ASSIGNED JOBS
=================================*/

$stmt = $pdo->prepare("
    SELECT 
        id,
        title,
        province,
        city,
        suburb,
        status,
        created_at
    FROM network_jobs
    WHERE assigned_installer_id = ?
    AND status = 'ASSIGNED'
    ORDER BY created_at DESC
");

$stmt->execute([$user_id]);
$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

require_once $_SERVER['DOCUMENT_ROOT'] . '/core/includes/header.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/core/includes/sidebar.php';
?>

<div class="main-content">

    <div class="page-header">
        <h2>My Assigned Jobs</h2>
        <p class="page-subtitle">Jobs officially assigned to you.</p>
    </div>

    <?php if (empty($jobs)): ?>
        <div class="card">
            <p>No assigned jobs yet.</p>
        </div>
    <?php else: ?>
        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Job #</th>
                        <th>Title</th>
                        <th>Location</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($jobs as $job): ?>
                        <tr>
                            <td>#<?= htmlspecialchars($job['id']) ?></td>
                            <td><?= htmlspecialchars($job['title']) ?></td>
                            <td>
                                <?= htmlspecialchars($job['suburb']) ?>,
                                <?= htmlspecialchars($job['city']) ?>
                            </td>
                            <td><?= htmlspecialchars($job['status']) ?></td>
                            <td><?= htmlspecialchars($job['created_at']) ?></td>
                            <td>
                                <a class="btn-sm" href="<?= $BASE ?>/installer/network/view.php?id=<?= (int)$job['id'] ?>">
    View
</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>

</div>

<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/core/includes/footer.php'; ?>