<?php
ob_start();
session_start();
require_once '../config/database.php';       // $pdo (Seven Credit DB)
require_once '../config/modules.php';         // company_enabled_modules(), module_on()
require_once '../config/module_access.php';   // mod_can_view(), mod_can_edit()

if (!isset($_SESSION['user_id']) || empty($_SESSION['company_id'])) {
    header('Location: ../auth/login.php'); exit;
}
$companyId   = (int)$_SESSION['company_id'];
$userId      = (int)$_SESSION['user_id'];
$role        = $_SESSION['role'] ?? '';
$companyName = $_SESSION['company_name'] ?? 'Company';

$enabled = company_enabled_modules($pdo, $companyId);
if (!module_on($enabled, 'jobs')) {
    http_response_code(403);
    exit('Job Management is not enabled for your company.');
}
if (!mod_can_admin($pdo, $companyId, $userId, $role, 'jobs')) {
    http_response_code(403);
    exit('You need Manage (admin) access for Job Management.');
}
if (!function_exists('esc')) {
    function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}

/*
|--------------------------------------------------------------------------
| Helper: pretty job number (JOB-YYYYMMDDHHMMSS -> dd/mm/YYYY (HHMMSS))
|--------------------------------------------------------------------------
*/
function formatJobNo($jobNo)
{
    $jobNo = (string)$jobNo;
    if (preg_match('/JOB-(\d{8})(\d{6})/', $jobNo, $matches)) {
        $dateRaw = $matches[1];
        $time    = $matches[2];
        $dateObj = DateTime::createFromFormat('Ymd', $dateRaw);
        $dateFormatted = $dateObj ? $dateObj->format('d/m/Y') : $dateRaw;
        return $dateFormatted . ' <span class="job-time">(' . $time . ')</span>';
    }
    return $jobNo;
}

/*
|--------------------------------------------------------------------------
| Month names for closed-job month filter
|--------------------------------------------------------------------------
*/
$monthNames = [
    1  => 'January',   2  => 'February', 3  => 'March',    4  => 'April',
    5  => 'May',       6  => 'June',     7  => 'July',     8  => 'August',
    9  => 'September', 10 => 'October',  11 => 'November', 12 => 'December',
];
$currentYear = (int)date('Y');

/*
|--------------------------------------------------------------------------
| Job types for the "Filter Type" control (distinct job_type in this company)
|--------------------------------------------------------------------------
*/
$jobTypeOptions = [];
try {
    $jt = $pdo->prepare("SELECT DISTINCT job_type FROM sp_jobs
                         WHERE company_id = ? AND job_type IS NOT NULL AND job_type <> ''
                         ORDER BY job_type ASC");
    $jt->execute([$companyId]);
    $jobTypeOptions = array_column($jt->fetchAll(PDO::FETCH_ASSOC), 'job_type');
} catch (Throwable $e) {
    $jobTypeOptions = [];
}

/*
|--------------------------------------------------------------------------
| Stat counts (scoped by company_id)
|--------------------------------------------------------------------------
*/
$totalMachines = 0; $totalJobs = 0; $openJobs = 0; $closedJobs = 0;
try {
    $mst = $pdo->prepare("SELECT COUNT(*) FROM sp_machines WHERE company_id = ?");
    $mst->execute([$companyId]);
    $totalMachines = (int)$mst->fetchColumn();
} catch (Throwable $e) { $totalMachines = 0; }

try {
    $cst = $pdo->prepare("SELECT
            COUNT(*) AS total,
            COUNT(CASE WHEN status = 'closed' THEN 1 END) AS closed_c,
            COUNT(CASE WHEN status <> 'closed' THEN 1 END) AS open_c
        FROM sp_jobs WHERE company_id = ?");
    $cst->execute([$companyId]);
    $counts = $cst->fetch(PDO::FETCH_ASSOC) ?: [];
    $totalJobs  = (int)($counts['total'] ?? 0);
    $openJobs   = (int)($counts['open_c'] ?? 0);
    $closedJobs = (int)($counts['closed_c'] ?? 0);
} catch (Throwable $e) { /* keep zeros */ }

/*
|--------------------------------------------------------------------------
| Search values - Recent (open) Jobs
|--------------------------------------------------------------------------
*/
$jobSearch  = trim($_GET['job_search'] ?? '');
$jobType    = trim($_GET['job_type'] ?? '');
if ($jobType !== '' && !in_array($jobType, $jobTypeOptions, true)) {
    $jobType = '';
}

/*
|--------------------------------------------------------------------------
| Search values - Closed Jobs
|--------------------------------------------------------------------------
*/
$closedJobSearch = trim($_GET['closed_job_search'] ?? '');
$closedJobType   = trim($_GET['closed_job_type'] ?? '');
$closedJobMonth  = (int)($_GET['closed_job_month'] ?? 0);
if ($closedJobType !== '' && !in_array($closedJobType, $jobTypeOptions, true)) {
    $closedJobType = '';
}
if ($closedJobMonth < 1 || $closedJobMonth > 12) {
    $closedJobMonth = 0;
}

/*
|--------------------------------------------------------------------------
| Build Recent (non-closed) jobs query
|--------------------------------------------------------------------------
*/
$recentSql = "
    SELECT
        j.id, j.job_no, j.job_type, j.sd_no, j.machine_no,
        j.issue_title, j.payment_type, j.status, j.open_date, j.created_at,
        c.customer_name AS customer_name,
        m.machine_model AS machine_model
    FROM sp_jobs j
    LEFT JOIN sp_customers c ON c.company_id = j.company_id AND c.sd_no = j.sd_no
    LEFT JOIN sp_machines  m ON m.company_id = j.company_id AND m.id = j.machine_id
    WHERE j.company_id = ? AND j.status <> 'closed'
";
$recentParams = [$companyId];

if ($jobSearch !== '') {
    $recentSql .= " AND (
        j.job_no LIKE ?
        OR j.issue_title LIKE ?
        OR j.machine_no LIKE ?
        OR c.customer_name LIKE ?
    ) ";
    $like = '%' . $jobSearch . '%';
    $recentParams[] = $like; $recentParams[] = $like;
    $recentParams[] = $like; $recentParams[] = $like;
}
if ($jobType !== '') {
    $recentSql .= " AND j.job_type = ? ";
    $recentParams[] = $jobType;
}
$recentSql .= " ORDER BY j.id DESC LIMIT 200 ";

$recentStmt = $pdo->prepare($recentSql);
$recentStmt->execute($recentParams);
$recentJobs = $recentStmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| Build Closed jobs query
|--------------------------------------------------------------------------
*/
$closedSql = "
    SELECT
        j.id, j.job_no, j.job_type, j.sd_no, j.machine_no,
        j.issue_title, j.payment_type, j.status, j.closed_at,
        c.customer_name AS customer_name,
        m.machine_model AS machine_model
    FROM sp_jobs j
    LEFT JOIN sp_customers c ON c.company_id = j.company_id AND c.sd_no = j.sd_no
    LEFT JOIN sp_machines  m ON m.company_id = j.company_id AND m.id = j.machine_id
    WHERE j.company_id = ? AND j.status = 'closed'
";
$closedParams = [$companyId];

if ($closedJobSearch !== '') {
    $closedSql .= " AND (
        j.job_no LIKE ?
        OR j.issue_title LIKE ?
        OR j.machine_no LIKE ?
        OR c.customer_name LIKE ?
    ) ";
    $like = '%' . $closedJobSearch . '%';
    $closedParams[] = $like; $closedParams[] = $like;
    $closedParams[] = $like; $closedParams[] = $like;
}
if ($closedJobType !== '') {
    $closedSql .= " AND j.job_type = ? ";
    $closedParams[] = $closedJobType;
}
if ($closedJobMonth > 0) {
    $closedSql .= " AND MONTH(j.closed_at) = ? AND YEAR(j.closed_at) = ? ";
    $closedParams[] = $closedJobMonth;
    $closedParams[] = $currentYear;
}
$closedSql .= " ORDER BY j.closed_at DESC, j.id DESC LIMIT 200 ";

$closedStmt = $pdo->prepare($closedSql);
$closedStmt->execute($closedParams);
$closedJobsList = $closedStmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| Excel export (pure PHP HTML-table technique -> .xls)
|--------------------------------------------------------------------------
*/
function xlsCell($v) {
    return '<td>' . htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8') . '</td>';
}
function jobNoPlain($jobNo) {
    $jobNo = (string)$jobNo;
    if (preg_match('/JOB-(\d{8})(\d{6})/', $jobNo, $m)) {
        $d = DateTime::createFromFormat('Ymd', $m[1]);
        return ($d ? $d->format('d/m/Y') : $m[1]) . ' (' . $m[2] . ')';
    }
    return $jobNo;
}

if (($_GET['export'] ?? '') === 'excel') {
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename=open_jobs_' . date('Ymd_His') . '.xls');
    echo "\xEF\xBB\xBF";
    echo '<table border="1"><thead><tr>'
       . '<th>Job No</th><th>Type</th><th>Customer</th><th>Machine No</th>'
       . '<th>Machine Model</th><th>Issue</th><th>Status</th><th>Open Date</th>'
       . '</tr></thead><tbody>';
    foreach ($recentJobs as $job) {
        $cust = ($job['customer_name'] ?? '') !== '' ? $job['customer_name'] : ($job['sd_no'] ?: '-');
        echo '<tr>'
           . xlsCell(jobNoPlain($job['job_no'] ?? ''))
           . xlsCell($job['job_type'] ?? '-')
           . xlsCell($cust ?: '-')
           . xlsCell($job['machine_no'] ?? '-')
           . xlsCell($job['machine_model'] ?? '-')
           . xlsCell($job['issue_title'] ?? '-')
           . xlsCell(ucwords(str_replace('_', ' ', $job['status'] ?? '')))
           . xlsCell($job['open_date'] ?? '')
           . '</tr>';
    }
    echo '</tbody></table>';
    exit;
}

if (($_GET['export_closed'] ?? '') === 'excel') {
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename=closed_jobs_' . date('Ymd_His') . '.xls');
    echo "\xEF\xBB\xBF";
    echo '<table border="1"><thead><tr>'
       . '<th>Job No</th><th>Type</th><th>Customer</th><th>Machine No</th>'
       . '<th>Machine Model</th><th>Issue</th><th>Closed</th>'
       . '</tr></thead><tbody>';
    foreach ($closedJobsList as $job) {
        $cust = ($job['customer_name'] ?? '') !== '' ? $job['customer_name'] : ($job['sd_no'] ?: '-');
        echo '<tr>'
           . xlsCell(jobNoPlain($job['job_no'] ?? ''))
           . xlsCell($job['job_type'] ?? '-')
           . xlsCell($cust ?: '-')
           . xlsCell($job['machine_no'] ?? '-')
           . xlsCell($job['machine_model'] ?? '-')
           . xlsCell($job['issue_title'] ?? '-')
           . xlsCell($job['closed_at'] ?? '')
           . '</tr>';
    }
    echo '</tbody></table>';
    exit;
}

$created = isset($_GET['created']) && $_GET['created'] === '1';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Job Dashboard - Service Portal</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; }
        html, body { max-width: 100%; overflow-x: hidden; }
        body {
            margin: 0;
            font-family: 'Noto Sans Lao', 'Inter', Arial, sans-serif;
            background: #f3f6fb;
            color: #111827;
            -webkit-font-smoothing: antialiased;
        }

        /* Dark top strip */
        .sp-topbar {
            background: #0f172a; color: #fff; padding: 14px 22px;
            display: flex; justify-content: space-between; align-items: center;
            flex-wrap: wrap; gap: 10px;
        }
        .sp-topbar .brand { font-size: 18px; font-weight: 700; }
        .sp-topbar .who { color: #93c5fd; font-size: 14px; font-weight: 600; }

        .container { max-width: 1200px; margin: 24px auto; padding: 0 16px; }

        .nav-links { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 22px; }
        .nav-links a {
            background: #fff; border: 1px solid #dbe3ee; padding: 10px 14px;
            border-radius: 10px; text-decoration: none; color: #1f2937; font-weight: bold;
        }
        .nav-links a:hover { background: #eff6ff; }
        .nav-links a.active { background: #2563eb; color: #fff; border-color: #2563eb; }

        .cards {
            display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
            gap: 16px; margin-bottom: 24px;
        }
        .card-stat {
            background: #fff; border-radius: 16px; padding: 20px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.05); min-width: 0;
        }
        .card-stat .label { color: #6b7280; font-size: 14px; margin-bottom: 8px; }
        .card-stat .value { font-size: 28px; font-weight: bold; color: #111827; }

        .section {
            background: #fff; border-radius: 16px; padding: 20px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.05); margin-bottom: 20px;
            min-width: 0; overflow: hidden;
        }
        .section-title-row {
            display: flex; align-items: center; justify-content: space-between;
            gap: 12px; margin-bottom: 12px; flex-wrap: wrap;
        }
        .section-title-row h2 { margin: 0; font-size: 20px; }

        .search-form {
            display: flex; gap: 8px; align-items: center; flex-wrap: wrap;
            width: 100%; max-width: 100%;
        }
        .search-form input[type="text"], .search-form select {
            padding: 9px 12px; border: 1px solid #d1d5db; border-radius: 8px;
            min-width: 180px; background: #fff; max-width: 100%;
            font-size: 14px; color: #111827;
        }
        .search-form input[type="text"] { min-width: 260px; }
        .search-form button, .export-btn {
            background: #2563eb; color: #fff; border: none; padding: 9px 14px;
            border-radius: 8px; font-weight: bold; cursor: pointer; text-decoration: none;
            display: inline-block;
        }
        .search-form button:hover { background: #1d4ed8; }
        .export-btn { background: #059669; }
        .export-btn:hover { background: #047857; }
        .small-link { color: #2563eb; text-decoration: none; font-size: 13px; font-weight: bold; }
        .small-link:hover { text-decoration: underline; }

        .table-wrap { width: 100%; max-width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; }
        .table-scroll {
            max-height: 420px; overflow-y: auto; overflow-x: auto;
            border: 1px solid #e5e7eb; border-radius: 10px;
        }
        .table-scroll thead th { position: sticky; top: 0; background: #f8fafc; z-index: 2; }
        table { width: 100%; min-width: 760px; border-collapse: collapse; }
        th, td {
            text-align: left; padding: 12px 10px; border-bottom: 1px solid #e5e7eb;
            font-size: 14px; vertical-align: top; white-space: normal; word-break: break-word;
        }
        th { background: #f8fafc; }
        .muted { color: #6b7280; }
        .job-no { white-space: nowrap; }
        .job-no a { color: #2563eb; font-weight: 700; text-decoration: none; }
        .job-no a:hover { text-decoration: underline; }
        .job-time { display: block; margin-top: 2px; }

        .job-type-badge {
            display: inline-block; padding: 4px 8px; border-radius: 999px;
            font-size: 11px; font-weight: bold; background: #ede9fe; color: #6d28d9;
        }
        .status {
            display: inline-block; padding: 6px 10px; border-radius: 999px;
            font-size: 12px; font-weight: bold; white-space: nowrap;
        }
        .status-open        { background: #dbeafe; color: #1d4ed8; }
        .status-assigned    { background: #fef3c7; color: #92400e; }
        .status-in_progress { background: #e0e7ff; color: #4338ca; }
        .status-closed      { background: #dcfce7; color: #166534; }

        th:last-child { text-align: center; }
        .action-cell { width: 90px; text-align: center; position: relative; }
        .action-menu { position: relative; display: inline-block; }
        .action-btn {
            width: 35px; height: 35px; border: none; border-radius: 8px;
            background: #f3f4f6; cursor: pointer; display: inline-flex;
            align-items: center; justify-content: center;
        }
        .action-btn:hover { background: #e5e7eb; }
        .action-dots { display: flex; flex-direction: column; gap: 3px; align-items: center; }
        .action-dots span { width: 4px; height: 4px; background: #6b7280; border-radius: 999px; display: block; }
        .action-dropdown {
            position: absolute; top: calc(100% + 8px); right: 0; min-width: 140px;
            background: #fff; border: 1px solid #e5e7eb; border-radius: 12px;
            box-shadow: 0 12px 30px rgba(15, 23, 42, 0.12); padding: 8px 0; z-index: 50; display: none;
        }
        .action-dropdown.show { display: block; }
        .action-dropdown a {
            display: block; padding: 10px 14px; text-decoration: none; color: #111827;
            font-size: 14px; white-space: nowrap; text-align: left;
        }
        .action-dropdown a:hover { background: #f8fafc; }
        .action-dropdown a.close-link { color: #b45309; font-weight: bold; }

        .message {
            background: #dcfce7; color: #166534; padding: 12px; border-radius: 10px; margin-bottom: 14px;
        }

        @media (max-width: 768px) {
            .cards { grid-template-columns: 1fr 1fr; gap: 12px; }
            .search-form input[type="text"] { flex: 1 1 100%; min-width: 0; width: 100%; }
        }
        @media (max-width: 480px) { .cards { grid-template-columns: 1fr; } }
    </style>
</head>
<body>
    <div class="sp-topbar">
        <div class="brand">Seven Digital &mdash; Service Portal</div>
        <div class="who">Welcome, <?= esc($companyName) ?></div>
    </div>

    <div class="container">

        <div class="nav-links">
            <a href="sp_jobs_admin.php" class="active">Dashboard</a>
            <a href="sp_job_add.php">Open Job</a>
            <a href="../company/staff.php">Staff</a>
            <a href="sp_staff_payments.php">Staff Payment</a>
            <a href="sp_payment_types.php">Payment Types</a>
            <a href="dashboard.php">Back to Company</a>
            <a href="../auth/logout.php">Logout</a>
        </div>

        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;gap:12px;flex-wrap:wrap;">
            <h1 style="margin:0;font-size:26px;font-weight:800;">Admin Dashboard</h1>
        </div>

        <?php if ($created): ?>
            <div class="message">Job created successfully.</div>
        <?php endif; ?>

        <div class="cards">
            <div class="card-stat">
                <div class="label">Total Machines</div>
                <div class="value"><?= esc($totalMachines) ?></div>
            </div>
            <div class="card-stat">
                <div class="label">Total Jobs</div>
                <div class="value"><?= esc($totalJobs) ?></div>
            </div>
            <div class="card-stat">
                <div class="label">Open Jobs</div>
                <div class="value"><?= esc($openJobs) ?></div>
            </div>
            <div class="card-stat">
                <div class="label">Closed Jobs</div>
                <div class="value"><?= esc($closedJobs) ?></div>
            </div>
        </div>

        <!-- Recent Jobs -->
        <div class="section">
            <div class="section-title-row">
                <h2>Recent Jobs</h2>
                <form method="GET" class="search-form">
                    <input type="text" name="job_search"
                        placeholder="Search job no, issue, customer, machine..."
                        value="<?= esc($jobSearch) ?>">

                    <select name="job_type">
                        <option value="">All Types</option>
                        <?php foreach ($jobTypeOptions as $t): ?>
                            <option value="<?= esc($t) ?>" <?= $jobType === $t ? 'selected' : '' ?>>
                                <?= esc(ucwords(str_replace('_', ' ', $t))) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <button type="submit">Search</button>
                    <button type="submit" name="export" value="excel" class="export-btn">Export Excel</button>

                    <?php if ($jobSearch !== '' || $jobType !== ''): ?>
                        <a href="sp_jobs_admin.php" class="small-link">Clear</a>
                    <?php endif; ?>
                </form>
            </div>

            <div class="table-wrap table-scroll">
                <table class="table-recent-jobs">
                    <thead>
                        <tr>
                            <th>Job No</th>
                            <th>Type</th>
                            <th>Customer</th>
                            <th>Machine</th>
                            <th>Issue</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($recentJobs): ?>
                            <?php foreach ($recentJobs as $job): ?>
                                <?php
                                    $statusClass = 'status-' . preg_replace('/[^a-z_]/', '', (string)($job['status'] ?? ''));
                                    $cust = ($job['customer_name'] ?? '') !== '' ? $job['customer_name'] : ($job['sd_no'] ?: '-');
                                ?>
                                <tr>
                                    <td class="job-no">
                                        <a href="sp_job_view.php?id=<?= (int)$job['id'] ?>">
                                            <?= formatJobNo($job['job_no']) ?>
                                        </a>
                                    </td>
                                    <td>
                                        <span class="job-type-badge">
                                            <?= esc(($job['job_type'] ?? '') !== '' ? ucwords(str_replace('_', ' ', $job['job_type'])) : '-') ?>
                                        </span>
                                    </td>
                                    <td><?= esc($cust ?: '-') ?></td>
                                    <td>
                                        <?= esc($job['machine_no'] ?? '-') ?><br>
                                        <span class="muted"><?= esc($job['machine_model'] ?? '-') ?></span>
                                    </td>
                                    <td><?= esc($job['issue_title'] ?? '-') ?></td>
                                    <td>
                                        <span class="status <?= esc($statusClass) ?>">
                                            <?= esc(ucwords(str_replace('_', ' ', $job['status'] ?? ''))) ?>
                                        </span>
                                    </td>
                                    <td class="action-cell">
                                        <div class="action-menu">
                                            <button type="button" class="action-btn" onclick="toggleActionMenu(this)">
                                                <span class="action-dots"><span></span><span></span><span></span></span>
                                            </button>
                                            <div class="action-dropdown">
                                                <a href="sp_job_view.php?id=<?= (int)$job['id'] ?>">View</a>
                                                <a href="sp_job_edit.php?id=<?= (int)$job['id'] ?>">Edit</a>
                                                <a href="sp_job_close.php?id=<?= (int)$job['id'] ?>" class="close-link">Close</a>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="7" class="muted">No active job records found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Closed Jobs -->
        <div class="section">
            <div class="section-title-row">
                <h2>Closed Jobs</h2>
                <form method="GET" class="search-form">
                    <input type="text" name="closed_job_search"
                        placeholder="Search closed job no, issue, customer, machine..."
                        value="<?= esc($closedJobSearch) ?>">

                    <select name="closed_job_type">
                        <option value="">All Types</option>
                        <?php foreach ($jobTypeOptions as $t): ?>
                            <option value="<?= esc($t) ?>" <?= $closedJobType === $t ? 'selected' : '' ?>>
                                <?= esc(ucwords(str_replace('_', ' ', $t))) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <select name="closed_job_month">
                        <option value="0">All Months (<?= esc($currentYear) ?>)</option>
                        <?php foreach ($monthNames as $monthNumber => $monthLabel): ?>
                            <option value="<?= esc($monthNumber) ?>" <?= $closedJobMonth === $monthNumber ? 'selected' : '' ?>>
                                <?= esc($monthLabel) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <button type="submit">Search</button>
                    <button type="submit" name="export_closed" value="excel" class="export-btn">Export Excel</button>

                    <?php if ($closedJobSearch !== '' || $closedJobType !== '' || $closedJobMonth > 0): ?>
                        <a href="sp_jobs_admin.php" class="small-link">Clear</a>
                    <?php endif; ?>
                </form>
            </div>

            <div class="table-wrap table-scroll">
                <table>
                    <thead>
                        <tr>
                            <th>Job No</th>
                            <th>Type</th>
                            <th>Customer</th>
                            <th>Machine</th>
                            <th>Issue</th>
                            <th>Closed</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($closedJobsList): ?>
                            <?php foreach ($closedJobsList as $job): ?>
                                <?php $cust = ($job['customer_name'] ?? '') !== '' ? $job['customer_name'] : ($job['sd_no'] ?: '-'); ?>
                                <tr>
                                    <td class="job-no">
                                        <a href="sp_job_view.php?id=<?= (int)$job['id'] ?>">
                                            <?= formatJobNo($job['job_no']) ?>
                                        </a>
                                    </td>
                                    <td>
                                        <span class="job-type-badge">
                                            <?= esc(($job['job_type'] ?? '') !== '' ? ucwords(str_replace('_', ' ', $job['job_type'])) : '-') ?>
                                        </span>
                                    </td>
                                    <td><?= esc($cust ?: '-') ?></td>
                                    <td>
                                        <?= esc($job['machine_no'] ?? '-') ?><br>
                                        <span class="muted"><?= esc($job['machine_model'] ?? '-') ?></span>
                                    </td>
                                    <td><?= esc($job['issue_title'] ?? '-') ?></td>
                                    <td><?= esc($job['closed_at'] ?? '-') ?></td>
                                    <td class="action-cell">
                                        <div class="action-menu">
                                            <button type="button" class="action-btn" onclick="toggleActionMenu(this)">
                                                <span class="action-dots"><span></span><span></span><span></span></span>
                                            </button>
                                            <div class="action-dropdown">
                                                <a href="sp_job_view.php?id=<?= (int)$job['id'] ?>">View</a>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="7" class="muted">No closed job records found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>

    <script>
        function toggleActionMenu(button) {
            const dropdown = button.nextElementSibling;
            document.querySelectorAll('.action-dropdown').forEach(menu => {
                if (menu !== dropdown) menu.classList.remove('show');
            });
            dropdown.classList.toggle('show');
        }
        document.addEventListener('click', function (event) {
            if (!event.target.closest('.action-menu')) {
                document.querySelectorAll('.action-dropdown').forEach(menu => menu.classList.remove('show'));
            }
        });
    </script>
</body>
</html>
<?php ob_end_flush(); ?>