<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../../includes/auth.php';
requirePermission('manage_network_jobs');

require_once __DIR__ . '/../../../config/database.php';

$BASE = app_base_path();

/* ===============================
   KPI COUNTS
=================================*/
function countJobs($pdo, array $statuses): int {
    $placeholders = implode(',', array_fill(0, count($statuses), '?'));
    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM network_jobs
        WHERE status IN ($placeholders)
    ");
    $stmt->execute($statuses);
    return (int)$stmt->fetchColumn();
}

$kpi = [
    'SUBMITTED'            => countJobs($pdo, ['SUBMITTED']),
    'INVITED_FOR_QUOTE'    => countJobs($pdo, ['INVITED_FOR_QUOTE']),
    'QUOTES_RECEIVED'      => countJobs($pdo, ['QUOTES_RECEIVED']),
    'ASSIGNED'             => countJobs($pdo, ['ASSIGNED']),
    'IN_PROGRESS'          => countJobs($pdo, ['IN_PROGRESS']),
    'COMPLETION_PENDING'   => countJobs($pdo, ['COMPLETION_PENDING']),
    'VERIFIED'             => countJobs($pdo, ['VERIFIED']),
    'CLOSED'               => countJobs($pdo, ['CLOSED']),
    'CANCELLED'            => countJobs($pdo, ['CANCELLED']),
];

/* ===============================
   PENDING VERIFICATION LIST
=================================*/
$pendingStmt = $pdo->prepare("
    SELECT id, title, category, suburb, city, province, installer_phone, completed_at, updated_at
    FROM network_jobs
    WHERE status = 'COMPLETION_PENDING'
    ORDER BY completed_at DESC, updated_at DESC
    LIMIT 15
");
$pendingStmt->execute();
$pendingJobs = $pendingStmt->fetchAll(PDO::FETCH_ASSOC);

/* ===============================
   RECENT JOBS
=================================*/
$recentStmt = $pdo->prepare("
    SELECT id, title, category, suburb, city, status, created_at
    FROM network_jobs
    ORDER BY created_at DESC
    LIMIT 10
");
$recentStmt->execute();
$recentJobs = $recentStmt->fetchAll(PDO::FETCH_ASSOC);

/* ===============================
   STATUS BADGE
=================================*/
function statusBadge(string $status): string {
    $s = strtoupper(trim($status));

    $map = [
        'SUBMITTED'           => ['bg'=>'#eef2ff','fg'=>'#3730a3'],
        'INVITED_FOR_QUOTE'   => ['bg'=>'#fef3c7','fg'=>'#92400e'],
        'QUOTES_RECEIVED'     => ['bg'=>'#ede9fe','fg'=>'#5b21b6'],
        'ASSIGNED'            => ['bg'=>'#ecfeff','fg'=>'#155e75'],
        'IN_PROGRESS'         => ['bg'=>'#dcfce7','fg'=>'#166534'],
        'COMPLETION_PENDING'  => ['bg'=>'#fff7ed','fg'=>'#9a3412'],
        'VERIFIED'            => ['bg'=>'#ecfdf5','fg'=>'#166534'],
        'CLOSED'              => ['bg'=>'#f3f4f6','fg'=>'#111827'],
        'CANCELLED'           => ['bg'=>'#fee2e2','fg'=>'#991b1b'],
    ];

    $c = $map[$s] ?? ['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;
    ">'.$s.'</span>';
}

require_once __DIR__ . '/../../../includes/header.php';
require_once __DIR__ . '/../../../includes/sidebar.php';
?>

<div class="main-content">

    <div class="page-header">
        <h2>National Network — OPS Dashboard</h2>
        <p class="page-subtitle">Operations overview + verification queue</p>
    </div>

    <!-- Quick Actions -->
    <div style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:18px;">
        <a class="btn-primary" href="<?= $BASE ?>/operations/network/index.php">All Jobs</a>
        <a class="btn-secondary" href="<?= $BASE ?>/operations/network/index.php">Open Queue</a>
    </div>

    <!-- KPI Cards -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:18px;">
        <div class="card"><h4>Submitted</h4><p style="font-size:28px;font-weight:800;"><?= $kpi['SUBMITTED'] ?></p></div>
        <div class="card"><h4>Invited for Quote</h4><p style="font-size:28px;font-weight:800;"><?= $kpi['INVITED_FOR_QUOTE'] ?></p></div>
        <div class="card"><h4>Quotes Received</h4><p style="font-size:28px;font-weight:800;"><?= $kpi['QUOTES_RECEIVED'] ?></p></div>

        <div class="card"><h4>Assigned</h4><p style="font-size:28px;font-weight:800;"><?= $kpi['ASSIGNED'] ?></p></div>
        <div class="card"><h4>In Progress</h4><p style="font-size:28px;font-weight:800;"><?= $kpi['IN_PROGRESS'] ?></p></div>

        <div class="card">
            <h4>Completion Pending</h4>
            <p style="font-size:28px;font-weight:800;color:#f59e0b;"><?= $kpi['COMPLETION_PENDING'] ?></p>
            <p style="margin:0;color:#6b7280;font-size:12px;">Needs admin verification</p>
        </div>

        <div class="card"><h4>Verified</h4><p style="font-size:28px;font-weight:800;color:#16a34a;"><?= $kpi['VERIFIED'] ?></p></div>
        <div class="card"><h4>Closed</h4><p style="font-size:28px;font-weight:800;"><?= $kpi['CLOSED'] ?></p></div>
        <div class="card"><h4>Cancelled</h4><p style="font-size:28px;font-weight:800;color:#dc2626;"><?= $kpi['CANCELLED'] ?></p></div>
    </div>

    <br>

    <!-- Pending Verification -->
    <div class="card">
        <h4 style="margin-bottom:12px;">Awaiting Verification</h4>

        <?php if (empty($pendingJobs)): ?>
            <p>No jobs awaiting verification.</p>
        <?php else: ?>
            <div class="table-wrap">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Job</th>
                            <th>Location</th>
                            <th>Phone</th>
                            <th>Completed</th>
                            <th>Status</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($pendingJobs as $j): ?>
                            <tr>
                                <td>#<?= (int)$j['id'] ?> — <?= htmlspecialchars($j['title']) ?></td>
                                <td><?= htmlspecialchars(($j['suburb'] ?? '').', '.($j['city'] ?? '')) ?></td>
                                <td><?= htmlspecialchars($j['installer_phone'] ?? '') ?></td>
                                <td><?= !empty($j['completed_at']) ? date('d M Y H:i', strtotime($j['completed_at'])) : '' ?></td>
                                <td><?= statusBadge($j['status']) ?></td>
                                <td>
                                    <a class="btn-primary btn-sm"
                                       href="<?= $BASE ?>/operations/network/view.php?id=<?= (int)$j['id'] ?>">
                                       View
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

    <br>

    <!-- Recent Jobs -->
    <div class="card">
        <h4 style="margin-bottom:12px;">Recent Jobs</h4>

        <?php if (empty($recentJobs)): ?>
            <p>No jobs found.</p>
        <?php else: ?>
            <div class="table-wrap">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Job</th>
                            <th>Category</th>
                            <th>Location</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recentJobs as $j): ?>
                            <tr>
                                <td>#<?= (int)$j['id'] ?> — <?= htmlspecialchars($j['title']) ?></td>
                                <td><?= htmlspecialchars($j['category'] ?? '') ?></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>
                                    <a class="btn-primary btn-sm"
                                       href="<?= $BASE ?>/operations/network/view.php?id=<?= (int)$j['id'] ?>">
                                       View
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

</div>

<?php require_once __DIR__ . '/../../../includes/footer.php'; ?>