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

require_once $_SERVER['DOCUMENT_ROOT'] . '/core/config/database.php';

$BASE = app_base_path();

$userId = $_SESSION['user_id'] ?? null;
if (!$userId) {
    redirect_to($BASE . '/login.php');
    exit;
}

/* =========================================================
   HELPERS
========================================================= */
function countStatus(PDO $pdo, int $userId, array $statusArray): int {
    if (empty($statusArray)) return 0;

    $placeholders = implode(',', array_fill(0, count($statusArray), '?'));
    $params = array_merge([$userId], $statusArray);

    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM network_jobs
        WHERE assigned_installer_id = ?
          AND status IN ($placeholders)
    ");
    $stmt->execute($params);
    return (int)$stmt->fetchColumn();
}

function statusBadge($status): string {
    $status = strtoupper((string)$status);

    $map = [
        'ASSIGNED'            => ['bg' => '#eef2ff', 'fg' => '#3730a3'],
        'IN_PROGRESS'         => ['bg' => '#ecfeff', 'fg' => '#155e75'],
        'COMPLETION_PENDING'  => ['bg' => '#fff7ed', 'fg' => '#9a3412'],
        'VERIFIED'            => ['bg' => '#ecfdf5', 'fg' => '#166534'],
        'CLOSED'              => ['bg' => '#f3f4f6', 'fg' => '#111827'],
    ];

    $c = $map[$status] ?? ['bg' => '#f3f4f6', 'fg' => '#111827'];

    return '<span style="
        display:inline-block;
        padding:4px 10px;
        border-radius:999px;
        font-size:12px;
        font-weight:700;
        background:'.$c['bg'].';
        color:'.$c['fg'].';
        white-space:nowrap;
    ">'.$status.'</span>';
}

/* =========================================================
   COUNTS
========================================================= */
$assigned   = countStatus($pdo, (int)$userId, ['ASSIGNED']);
$inProgress = countStatus($pdo, (int)$userId, ['IN_PROGRESS']);
$pending    = countStatus($pdo, (int)$userId, ['COMPLETION_PENDING']);
$completed  = countStatus($pdo, (int)$userId, ['VERIFIED','CLOSED']);

/* =========================================================
   KPI — Completion Rate (%)
   Based on VERIFIED/CLOSED over (VERIFIED/CLOSED/COMPLETION_PENDING)
========================================================= */
$kpiDen = max(0, $completed + $pending);
$completionRate = ($kpiDen > 0) ? round(($completed / $kpiDen) * 100) : 0;

/* =========================================================
   RECENT ACTIVE JOBS (B)
   Active = ASSIGNED, IN_PROGRESS, COMPLETION_PENDING
========================================================= */
$recentActiveStmt = $pdo->prepare("
    SELECT id, title, suburb, city, status, created_at
    FROM network_jobs
    WHERE assigned_installer_id = ?
      AND status IN ('ASSIGNED','IN_PROGRESS','COMPLETION_PENDING')
    ORDER BY created_at DESC
    LIMIT 5
");
$recentActiveStmt->execute([$userId]);
$recentJobs = $recentActiveStmt->fetchAll(PDO::FETCH_ASSOC);

/* =========================================================
   QUICK START — Start Job directly from dashboard (A)
   Only allows ASSIGNED -> IN_PROGRESS (safe)
========================================================= */
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['start_job_id'])) {
    $startId = (int)($_POST['start_job_id'] ?? 0);

    if ($startId > 0) {
        // Only start if it's assigned to this installer and still ASSIGNED
        $upd = $pdo->prepare("
            UPDATE network_jobs
            SET status = 'IN_PROGRESS',
                updated_at = NOW()
            WHERE id = ?
              AND assigned_installer_id = ?
              AND status = 'ASSIGNED'
        ");
        $upd->execute([$startId, $userId]);

        // Refresh back
        redirect_to($BASE . '/installer/dashboard.php');
        exit;
    } else {
        $error = "Invalid job selected.";
    }
}

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>National Field Dashboard</h2>
        <p class="page-subtitle">
            Welcome, <?= htmlspecialchars($_SESSION['full_name']) ?>
        </p>
    </div>

    <?php if (!empty($error)): ?>
        <div class="alert-error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <!-- Quick Actions (D: better mobile spacing) -->
    <div style="
        display:flex;
        gap:10px;
        flex-wrap:wrap;
        margin:14px 0 18px;
    ">
        <a class="btn-primary" href="<?= $BASE ?>/installer/network/invites.php">My Invites</a>
        <a class="btn-secondary" href="<?= $BASE ?>/installer/network/my_jobs.php">My Jobs</a>
    </div>

    <!-- Summary Cards + KPI (B) -->
    <div style="
        display:grid;
        grid-template-columns:repeat(auto-fit,minmax(200px,1fr));
        gap:14px;
    ">

        <div class="card">
            <h4>Assigned</h4>
            <p style="font-size:30px;font-weight:800;margin:6px 0 0;"><?= $assigned ?></p>
        </div>

        <div class="card">
            <h4>In Progress</h4>
            <p style="font-size:30px;font-weight:800;margin:6px 0 0;"><?= $inProgress ?></p>
        </div>

        <div class="card">
            <h4>Awaiting Verification</h4>
            <p style="font-size:30px;font-weight:800;margin:6px 0 0;color:#f59e0b;"><?= $pending ?></p>
        </div>

        <div class="card">
            <h4>Completed</h4>
            <p style="font-size:30px;font-weight:800;margin:6px 0 0;color:#16a34a;"><?= $completed ?></p>
        </div>

        <div class="card">
            <h4>Completion Rate</h4>
            <p style="font-size:30px;font-weight:800;margin:6px 0 0;"><?= (int)$completionRate ?>%</p>
            <p style="margin:6px 0 0;color:#6b7280;font-size:12px;">
                Based on Completed vs Pending
            </p>
        </div>

    </div>

    <br>

    <!-- Recent Active Jobs (B) + Start button (A) -->
    <div class="card">
        <div style="
            display:flex;
            justify-content:space-between;
            align-items:flex-end;
            gap:12px;
            flex-wrap:wrap;
            margin-bottom:10px;
        ">
            <div>
                <h4 style="margin:0;">Recent Active Jobs</h4>
                <p style="margin:6px 0 0;color:#6b7280;font-size:13px;">
                    ASSIGNED, IN_PROGRESS, and Awaiting Verification
                </p>
            </div>

            <!-- (C) Notification badge style hint (dashboard-level) -->
            <?php if ($pending > 0): ?>
                <div style="
                    padding:6px 10px;
                    border-radius:999px;
                    background:#fff7ed;
                    color:#9a3412;
                    font-weight:800;
                    font-size:12px;
                    white-space:nowrap;
                ">
                    <?= (int)$pending ?> awaiting OPS verification
                </div>
            <?php endif; ?>
        </div>

        <?php if (empty($recentJobs)): ?>
            <p>No active jobs yet.</p>
        <?php else: ?>
            <div class="table-wrap">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="min-width:220px;">Job</th>
                            <th style="min-width:180px;">Location</th>
                            <th>Status</th>
                            <th style="min-width:120px;">Date</th>
                            <th style="min-width:170px;"></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($recentJobs as $j): ?>
                        <tr>
                            <td>#<?= (int)$j['id'] ?> — <?= htmlspecialchars($j['title']) ?></td>
                            <td><?= htmlspecialchars(($j['suburb'] ?? '') . ', ' . ($j['city'] ?? '')) ?></td>
                            <td><?= statusBadge($j['status']) ?></td>
                            <td><?= !empty($j['created_at']) ? date('d M Y', strtotime($j['created_at'])) : '' ?></td>
                            <td style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
                                <a class="btn-primary btn-sm"
                                   href="<?= $BASE ?>/installer/network/view.php?id=<?= (int)$j['id'] ?>">
                                   View
                                </a>

                                <?php if (strtoupper((string)$j['status']) === 'ASSIGNED'): ?>
                                    <form method="POST" style="margin:0;">
                                        <input type="hidden" name="start_job_id" value="<?= (int)$j['id'] ?>">
                                        <button type="submit" class="btn-secondary btn-sm">
                                            Start
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

    <style>
        /* (D) Mobile polish: make table actions stack nicely and reduce spacing */
        @media (max-width: 600px) {
            .page-header h2 { font-size: 30px; }
            .table-wrap { overflow-x: auto; }
            .btn-primary.btn-sm, .btn-secondary.btn-sm { padding: 8px 10px; }
            .card { padding: 16px; }
        }
    </style>

</div>

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