<?php
require_once 'db.php';
requireAdmin();

$message = $_SESSION['success_message'] ?? '';
unset($_SESSION['success_message']);

$error = '';

/*
|--------------------------------------------------------------------------
| Load payment types from DB
|--------------------------------------------------------------------------
| This makes new items like "Setup New Machine" show automatically.
*/$paymentTypeRows = $pdo->query("
    SELECT code, label
    FROM payment_types
    WHERE status = 'active'
    ORDER BY sort_order ASC, label ASC
")->fetchAll();

$paymentTypeMap = [];
foreach ($paymentTypeRows as $row) {
    $paymentTypeMap[$row['code']] = $row['label'];
}

function paymentTypeLabel($paymentType, $paymentTypeMap)
{
    return $paymentTypeMap[$paymentType]
        ?? ucwords(str_replace('_', ' ', $paymentType ?: 'Other'));
}

/*
|--------------------------------------------------------------------------
| 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'
];

/*
|--------------------------------------------------------------------------
| Machine CSV Upload
|--------------------------------------------------------------------------
*/
if (isset($_POST['upload_machines_csv'])) {
    if (!isset($_FILES['machines_csv']) || $_FILES['machines_csv']['error'] !== 0) {
        $error = 'Please choose a valid CSV file.';
    } else {
        $fileTmp = $_FILES['machines_csv']['tmp_name'];

        if (!is_uploaded_file($fileTmp)) {
            $error = 'Invalid uploaded file.';
        } else {
            $handle = fopen($fileTmp, 'r');

            if (!$handle) {
                $error = 'Could not open CSV file.';
            } else {
                $header = fgetcsv($handle);

                $expectedHeader = [
                    'customer_id',
                    'unique_machine_no',
                    'machine_model',
                    'serial_no',
                    'customer_name',
                    'location_text',
                    'meter_date',
                    'main_email',
                    'invoice_email',
                    'cc_email',
                    'telephone',
                    'status'
                ];

                if (!$header) {
                    $error = 'CSV file is empty.';
                } else {
                    $header = array_map('trim', $header);

                    if (isset($header[0])) {
                        $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', $header[0]);
                    }

                    if ($header !== $expectedHeader) {
                        $error = 'Invalid CSV header. Please use the required machine CSV format.';
                    } else {
                        $inserted = 0;
                        $skipped = 0;

                        $stmt = $pdo->prepare("
                            INSERT IGNORE INTO machines (
                                customer_id,
                                unique_machine_no,
                                machine_model,
                                serial_no,
                                customer_name,
                                location_text,
                                meter_date,
                                main_email,
                                invoice_email,
                                cc_email,
                                telephone,
                                status
                            )
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        ");

                        while (($row = fgetcsv($handle)) !== false) {
                            if (count($row) < count($expectedHeader)) {
                                $skipped++;
                                continue;
                            }

                            $row = array_map('trim', $row);
                            $data = array_combine($expectedHeader, array_slice($row, 0, count($expectedHeader)));

                            $customer_id       = trim($data['customer_id'] ?? '');
                            $unique_machine_no = trim($data['unique_machine_no'] ?? '');
                            $machine_model     = trim($data['machine_model'] ?? '');
                            $serial_no         = trim($data['serial_no'] ?? '');
                            $customer_name     = trim($data['customer_name'] ?? '');
                            $location_text     = trim($data['location_text'] ?? '');
                            $meter_date        = trim($data['meter_date'] ?? '');
                            $main_email        = trim($data['main_email'] ?? '');
                            $invoice_email     = trim($data['invoice_email'] ?? '');
                            $cc_email          = trim($data['cc_email'] ?? '');
                            $telephone         = trim($data['telephone'] ?? '');
                            $status            = trim($data['status'] ?? 'active');

                            if ($machine_model === '' || $customer_name === '') {
                                $skipped++;
                                continue;
                            }

                            $customer_id = $customer_id !== '' ? $customer_id : null;
                            $unique_machine_no = $unique_machine_no !== '' ? $unique_machine_no : null;

                            if (!in_array($status, ['active', 'inactive', 'retired'], true)) {
                                $status = 'active';
                            }

                            $stmt->execute([
                                $customer_id,
                                $unique_machine_no,
                                $machine_model,
                                $serial_no,
                                $customer_name,
                                $location_text,
                                $meter_date ?: null,
                                $main_email,
                                $invoice_email,
                                $cc_email,
                                $telephone,
                                $status
                            ]);

                            if ($stmt->rowCount() > 0) {
                                $inserted++;
                            } else {
                                $skipped++;
                            }
                        }

                        $message = "CSV upload completed. Inserted: {$inserted}, Skipped: {$skipped}.";
                    }
                }

                fclose($handle);
            }
        }
    }
}

/*
|--------------------------------------------------------------------------
| Dashboard Counts
|--------------------------------------------------------------------------
*/
$totalMachines  = $pdo->query("SELECT COUNT(*) AS total FROM machines")->fetch()['total'] ?? 0;
$totalJobs      = $pdo->query("SELECT COUNT(*) AS total FROM jobs")->fetch()['total'] ?? 0;
$openJobs       = $pdo->query("SELECT COUNT(*) AS total FROM jobs WHERE status IN ('open','assigned','in_progress')")->fetch()['total'] ?? 0;
$closedJobs     = $pdo->query("SELECT COUNT(*) AS total FROM jobs WHERE status = 'closed'")->fetch()['total'] ?? 0;

/*
|--------------------------------------------------------------------------
| Search values - Active Jobs
|--------------------------------------------------------------------------
*/
$jobSearch = trim($_GET['job_search'] ?? '');
$jobPaymentTypes = $_GET['payment_types'] ?? [];

if (!is_array($jobPaymentTypes)) {
    $jobPaymentTypes = [];
}

$jobPaymentTypes = array_values(array_filter(array_map('trim', $jobPaymentTypes)));

/*
|--------------------------------------------------------------------------
| Search values - Closed Jobs
|--------------------------------------------------------------------------
*/
$closedJobSearch = trim($_GET['closed_job_search'] ?? '');
$closedPaymentTypes = $_GET['closed_payment_types'] ?? [];
$closedJobMonth = (int)($_GET['closed_job_month'] ?? 0);
$currentYear = (int)date('Y');

if (!is_array($closedPaymentTypes)) {
    $closedPaymentTypes = [];
}

$closedPaymentTypes = array_values(array_filter(array_map('trim', $closedPaymentTypes)));

if ($closedJobMonth < 1 || $closedJobMonth > 12) {
    $closedJobMonth = 0;
}

/*
|--------------------------------------------------------------------------
| Recent Active Jobs
|--------------------------------------------------------------------------
*/
$recentJobsSql = "
    SELECT
        j.id,
        j.job_no,
        j.payment_type,
        j.job_type,
        j.issue_title,
        j.status,
        j.created_at,
        j.customer_id,
        m.unique_machine_no,
        m.machine_model,
        m.customer_name AS machine_customer_name,
        c.customer_name AS normal_customer_name
    FROM jobs j
    LEFT JOIN machines m ON j.machine_id = m.id
    LEFT JOIN customers c ON j.customer_id = c.id
    WHERE j.status IN ('open', 'assigned', 'in_progress')
";

$recentJobsParams = [];

if ($jobSearch !== '') {
    $recentJobsSql .= "
        AND (
            j.job_no LIKE ?
            OR j.issue_title LIKE ?
            OR j.payment_type LIKE ?
            OR m.unique_machine_no LIKE ?
            OR m.machine_model LIKE ?
            OR m.customer_name LIKE ?
            OR c.customer_name LIKE ?
        )
    ";

    $searchLike = '%' . $jobSearch . '%';
    $recentJobsParams[] = $searchLike;
    $recentJobsParams[] = $searchLike;
    $recentJobsParams[] = $searchLike;
    $recentJobsParams[] = $searchLike;
    $recentJobsParams[] = $searchLike;
    $recentJobsParams[] = $searchLike;
    $recentJobsParams[] = $searchLike;
}

if (!empty($jobPaymentTypes)) {
    $validSelectedTypes = array_values(array_intersect($jobPaymentTypes, array_keys($paymentTypeMap)));

    if (!empty($validSelectedTypes)) {
        $placeholders = implode(',', array_fill(0, count($validSelectedTypes), '?'));
        $recentJobsSql .= " AND j.payment_type IN ($placeholders)";
        foreach ($validSelectedTypes as $type) {
            $recentJobsParams[] = $type;
        }
        $jobPaymentTypes = $validSelectedTypes;
    } else {
        $jobPaymentTypes = [];
    }
}

$recentJobsSql .= "
    ORDER BY j.id DESC
    LIMIT 50
";

$recentJobsStmt = $pdo->prepare($recentJobsSql);
$recentJobsStmt->execute($recentJobsParams);
$recentJobs = $recentJobsStmt->fetchAll();

/*
|--------------------------------------------------------------------------
| Recent Closed Jobs
|--------------------------------------------------------------------------
*/
$recentClosedJobsSql = "
    SELECT
        j.id,
        j.job_no,
        j.payment_type,
        j.job_type,
        j.issue_title,
        j.status,
        j.created_at,
        j.closed_at,
        j.customer_id,
        m.unique_machine_no,
        m.machine_model,
        m.customer_name AS machine_customer_name,
        c.customer_name AS normal_customer_name
    FROM jobs j
    LEFT JOIN machines m ON j.machine_id = m.id
    LEFT JOIN customers c ON j.customer_id = c.id
    WHERE j.status = 'closed'
";

$recentClosedJobsParams = [];

if ($closedJobSearch !== '') {
    $recentClosedJobsSql .= "
        AND (
            j.job_no LIKE ?
            OR j.issue_title LIKE ?
            OR j.payment_type LIKE ?
            OR m.unique_machine_no LIKE ?
            OR m.machine_model LIKE ?
            OR m.customer_name LIKE ?
            OR c.customer_name LIKE ?
        )
    ";

    $searchLike = '%' . $closedJobSearch . '%';
    $recentClosedJobsParams[] = $searchLike;
    $recentClosedJobsParams[] = $searchLike;
    $recentClosedJobsParams[] = $searchLike;
    $recentClosedJobsParams[] = $searchLike;
    $recentClosedJobsParams[] = $searchLike;
    $recentClosedJobsParams[] = $searchLike;
    $recentClosedJobsParams[] = $searchLike;
}

if (!empty($closedPaymentTypes)) {
    $validClosedTypes = array_values(array_intersect($closedPaymentTypes, array_keys($paymentTypeMap)));

    if (!empty($validClosedTypes)) {
        $placeholders = implode(',', array_fill(0, count($validClosedTypes), '?'));
        $recentClosedJobsSql .= " AND j.payment_type IN ($placeholders)";
        foreach ($validClosedTypes as $type) {
            $recentClosedJobsParams[] = $type;
        }
        $closedPaymentTypes = $validClosedTypes;
    } else {
        $closedPaymentTypes = [];
    }
}

if ($closedJobMonth > 0) {
    $recentClosedJobsSql .= " AND MONTH(j.closed_at) = ? AND YEAR(j.closed_at) = ?";
    $recentClosedJobsParams[] = $closedJobMonth;
    $recentClosedJobsParams[] = $currentYear;
}

$recentClosedJobsSql .= "
    ORDER BY j.closed_at DESC, j.id DESC
";

$recentClosedJobsStmt = $pdo->prepare($recentClosedJobsSql);
$recentClosedJobsStmt->execute($recentClosedJobsParams);
$recentClosedJobs = $recentClosedJobsStmt->fetchAll();

/*
|--------------------------------------------------------------------------
| Export active jobs as CSV for Excel
|--------------------------------------------------------------------------
*/
if (($_GET['export'] ?? '') === 'excel') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=recent_jobs_' . date('Ymd_His') . '.csv');

    $output = fopen('php://output', 'w');
    fwrite($output, "\xEF\xBB\xBF");

    fputcsv($output, [
        'Job No',
        'Type',
        'Customer',
        'Machine No',
        'Machine Model',
        'Issue',
        'Status',
        'Created At'
    ]);

    foreach ($recentJobs as $job) {
        $displayCustomer = ($job['job_type'] ?? '') === 'machine'
            ? ($job['machine_customer_name'] ?? '')
            : ($job['normal_customer_name'] ?? '');

        fputcsv($output, [
            strip_tags(formatJobNo($job['job_no'] ?? '')),
            paymentTypeLabel($job['payment_type'] ?? '', $paymentTypeMap),
            $displayCustomer ?: '-',
            $job['unique_machine_no'] ?? '-',
            $job['machine_model'] ?? '-',
            $job['issue_title'] ?? '-',
            ucwords(str_replace('_', ' ', $job['status'] ?? '')),
            $job['created_at'] ?? ''
        ]);
    }

    fclose($output);
    exit;
}

/*
|--------------------------------------------------------------------------
| Export closed jobs as CSV for Excel
|--------------------------------------------------------------------------
*/
if (($_GET['export_closed'] ?? '') === 'excel') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=closed_jobs_' . date('Ymd_His') . '.csv');

    $output = fopen('php://output', 'w');
    fwrite($output, "\xEF\xBB\xBF");

    fputcsv($output, [
        'Job No',
        'Type',
        'Customer',
        'Machine No',
        'Machine Model',
        'Issue',
        'Status',
        'Closed At'
    ]);

    foreach ($recentClosedJobs as $job) {
        $displayCustomer = ($job['job_type'] ?? '') === 'machine'
            ? ($job['machine_customer_name'] ?? '')
            : ($job['normal_customer_name'] ?? '');

        fputcsv($output, [
            strip_tags(formatJobNo($job['job_no'] ?? '')),
            paymentTypeLabel($job['payment_type'] ?? '', $paymentTypeMap),
            $displayCustomer ?: '-',
            $job['unique_machine_no'] ?? '-',
            $job['machine_model'] ?? '-',
            $job['issue_title'] ?? '-',
            ucwords(str_replace('_', ' ', $job['status'] ?? '')),
            $job['closed_at'] ?? ''
        ]);
    }

    fclose($output);
    exit;
}

function formatJobNo($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;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Service Portal</title>

    <link rel="stylesheet" href="css/style.css?v=1">

    <style>
        * {
            box-sizing: border-box;
        }

        html, body {
            max-width: 100%;
            overflow-x: hidden;
        }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f3f6fb;
            color: #111827;
        }

        .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;
        }

        .cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }

        .card {
            background: #fff;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.05);
            min-width: 0;
        }

        .card .label {
            color: #6b7280;
            font-size: 14px;
            margin-bottom: 8px;
        }

        .card .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 h2 {
            margin-top: 0;
            font-size: 20px;
        }

        .status {
            white-space: nowrap;
        }

        .job-no {
            white-space: nowrap;
        }

        @media (min-width: 1100px) {
            .grid-two {
                grid-template-columns: 1fr;
            }

            .table-recent-jobs th:nth-child(6),
            .table-recent-jobs td:nth-child(6) {
                min-width: 140px;
                width: 140px;
            }
        }

        @media (max-width: 1024px) {
            .table-recent-jobs th:nth-child(6),
            .table-recent-jobs td:nth-child(6) {
                min-width: 110px;
                width: 110px;
            }
        }

        @media (max-width: 768px) {
            .table-recent-jobs th:nth-child(6),
            .table-recent-jobs td:nth-child(6) {
                min-width: 90px;
                width: 90px;
            }
        }

        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;
        }

        .status {
            display: inline-block;
            padding: 6px 10px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-active {
            background: #dcfce7;
            color: #166534;
        }

        .status-inactive {
            background: #fee2e2;
            color: #991b1b;
        }

        .table-wrap {
            width: 100%;
            max-width: 100%;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        .table-scroll {
            max-height: 400px;
            overflow-y: auto;
            overflow-x: auto;
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            -webkit-overflow-scrolling: touch;
        }

        .table-scroll thead th {
            position: sticky;
            top: 0;
            background: #f8fafc;
            z-index: 2;
        }

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

        .error {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 14px;
        }

        .upload-box {
            margin-bottom: 20px;
        }

        .upload-form {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            align-items: center;
        }

        .upload-form input[type="file"] {
            padding: 10px;
            background: #fff;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            max-width: 100%;
        }

        .upload-form button {
            background: #2563eb;
            color: #fff;
            border: none;
            padding: 11px 16px;
            border-radius: 10px;
            cursor: pointer;
            font-weight: bold;
        }

        .upload-form button:hover {
            background: #1d4ed8;
        }

        .help {
            font-size: 12px;
            color: #6b7280;
            margin-top: 8px;
            word-break: break-word;
        }

        .job-type-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: bold;
            background: #ede9fe;
            color: #6d28d9;
            margin-bottom: 4px;
        }

        .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;
        }

        .small-link {
            color: #2563eb;
            text-decoration: none;
            font-size: 13px;
            font-weight: bold;
        }

        .small-link:hover {
            text-decoration: underline;
        }

        .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;
        }

        .grid-two {
            display: grid;
            grid-template-columns: 1fr;
            gap: 20px;
        }

        .btn-refresh {
            background: #16a34a;
            color: #fff;
            border: none;
            padding: 8px 14px;
            border-radius: 8px;
            font-weight: bold;
            cursor: pointer;
        }

        .btn-refresh:hover {
            background: #15803d;
        }

        .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: 280px;
        }

        .search-form button,
        .filter-btn,
        .export-btn {
            background: #2563eb;
            color: #fff;
            border: none;
            padding: 9px 14px;
            border-radius: 8px;
            font-weight: bold;
            cursor: pointer;
        }

        .search-form button:hover,
        .filter-btn:hover,
        .export-btn:hover {
            background: #1d4ed8;
        }

        .filter-dropdown {
            position: relative;
        }

        .filter-btn {
            background: #4f46e5;
        }

        .filter-btn:hover {
            background: #4338ca;
        }

        .export-btn {
            background: #059669;
        }

        .export-btn:hover {
            background: #047857;
        }

        .filter-menu {
            position: absolute;
            top: calc(100% + 8px);
            left: 0;
            min-width: 280px;
            max-height: 300px;
            overflow-y: auto;
            background: #fff;
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            box-shadow: 0 12px 30px rgba(15, 23, 42, 0.12);
            padding: 10px;
            z-index: 100;
        }

        .filter-menu.hidden {
            display: none;
        }

        .filter-option {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 7px 4px;
            font-size: 14px;
            cursor: pointer;
        }

        .filter-option input[type="checkbox"] {
            width: auto;
            margin: 0;
        }

        .selected-types {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 4px;
        }

        .selected-type-chip {
            background: #eef2ff;
            color: #4338ca;
            padding: 6px 10px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: bold;
        }

        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;
            transition: background 0.2s ease;
        }

        .action-btn:hover {
            background: #e5e7eb;
        }

        .action-dots {
            display: flex;
            flex-direction: column;
            gap: 3px;
            align-items: center;
            justify-content: 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.delete-link {
            color: #dc2626;
            font-weight: bold;
        }

        .table-scroll {
            overflow-y: visible;
            overflow-x: auto;
        }

        @media (min-width: 1100px) {
            .grid-two {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 1024px) {
            .container {
                padding: 0 12px;
            }

            .section {
                padding: 16px;
            }

            .section-title-row {
                align-items: stretch;
            }

            .section-title-row h2 {
                width: 100%;
            }

            .search-form {
                width: 100%;
            }

            .search-form input[type="text"] {
                flex: 1 1 100%;
                min-width: 0;
                width: 100%;
            }

            .search-form button,
            .filter-btn,
            .export-btn,
            .search-form select {
                flex: 0 0 auto;
            }

            .table-wrap {
                margin: 0;
            }
        }

        @media (max-width: 768px) {
            .container {
                padding: 0 10px;
            }

            .cards {
                grid-template-columns: 1fr 1fr;
                gap: 12px;
            }

            .card {
                padding: 16px;
            }

            .card .value {
                font-size: 24px;
            }

            .section {
                padding: 14px;
            }

            .section h2 {
                font-size: 18px;
            }

            table {
                min-width: 700px;
            }

            th, td {
                padding: 10px 8px;
                font-size: 13px;
            }

            .nav-links a {
                padding: 9px 12px;
                font-size: 14px;
            }
        }

        .job-time {
            display: block;
            margin-top: 2px;
        }

        @media (max-width: 480px) {
            .cards {
                grid-template-columns: 1fr;
            }

            table {
                min-width: 640px;
            }

            th, td {
                font-size: 12px;
                padding: 9px 7px;
            }

            .btn-refresh {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <?php include 'header.php'; ?>

    <div class="container">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;gap:12px;flex-wrap:wrap;">
            <h1 class="page-title" style="margin:0;">Admin Dashboard</h1>

            <button onclick="location.reload()" class="btn-refresh">
                Refresh
            </button>
        </div>

        <?php if ($message): ?>
            <div class="message"><?= esc($message) ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="error"><?= esc($error) ?></div>
        <?php endif; ?>

        <div class="nav-links">
            <a href="machines.php">Machines</a>
            <a href="add_job.php">Open Job</a>
            <a href="manage_staff.php">Staff</a>
            <a href="staff_payments.php">Staff Payment</a>
            <a href="manage_payment_types.php">Payment Types</a>
        </div>

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

        <div class="grid-two">
            <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) ?>"
                        >

                        <?php if ($closedJobSearch !== ''): ?>
                            <input type="hidden" name="closed_job_search" value="<?= esc($closedJobSearch) ?>">
                        <?php endif; ?>

                        <?php foreach ($closedPaymentTypes as $type): ?>
                            <input type="hidden" name="closed_payment_types[]" value="<?= esc($type) ?>">
                        <?php endforeach; ?>

                        <?php if ($closedJobMonth > 0): ?>
                            <input type="hidden" name="closed_job_month" value="<?= esc($closedJobMonth) ?>">
                        <?php endif; ?>

                        <div class="filter-dropdown">
                            <button type="button" class="filter-btn" onclick="toggleTypeFilter()">
                                Filter Type
                            </button>

                            <div id="typeFilterMenu" class="filter-menu hidden">
                                <?php foreach ($paymentTypeRows as $type): ?>
                                    <label class="filter-option">
                                        <input
                                            type="checkbox"
                                            name="payment_types[]"
                                            value="<?= esc($type['code']) ?>"
                                            <?= in_array($type['code'], $jobPaymentTypes, true) ? 'checked' : '' ?>
                                        >
                                        <?= esc($type['label']) ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <button type="submit">Search</button>

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

                        <?php if ($jobSearch !== '' || !empty($jobPaymentTypes)): ?>
                            <a href="admin-dashboard.php" class="small-link">Clear</a>
                        <?php endif; ?>

                        <?php if (!empty($jobPaymentTypes)): ?>
                            <div class="selected-types">
                                <?php foreach ($jobPaymentTypes as $selectedType): ?>
                                    <span class="selected-type-chip">
                                        <?= esc(paymentTypeLabel($selectedType, $paymentTypeMap)) ?>
                                    </span>
                                <?php endforeach; ?>
                            </div>
                        <?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>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($recentJobs): ?>
                                <?php foreach ($recentJobs as $job): ?>
                                    <?php
                                        $displayCustomer = ($job['job_type'] ?? '') === 'machine'
                                            ? ($job['machine_customer_name'] ?? '')
                                            : ($job['normal_customer_name'] ?? '');

                                        $statusClass = 'status-' . ($job['status'] ?? '');
                                    ?>
                                    <tr>
                                        <td class="job-no">
                                            <a href="view-job.php?id=<?= (int)$job['id'] ?>">
                                                <?= formatJobNo($job['job_no']) ?>
                                            </a>
                                        </td>

                                        <td>
                                            <span class="job-type-badge">
                                                <?= esc(paymentTypeLabel($job['payment_type'] ?? '', $paymentTypeMap)) ?>
                                            </span>
                                        </td>

                                        <td><?= esc($displayCustomer ?: '-') ?></td>

                                        <td>
                                            <?= esc($job['unique_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="view-job.php?id=<?= (int)$job['id'] ?>" target="_blank" rel="noopener noreferrer">View</a>
                                                    <a href="edit_job.php?id=<?= (int)$job['id'] ?>">Edit</a>
                                                    <a
                                                        href="delete_job.php?id=<?= (int)$job['id'] ?>"
                                                        class="delete-link"
                                                        onclick="return confirm('Are you sure you want to delete this job?');"
                                                    >
                                                        Delete
                                                    </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>

            <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) ?>"
                        >

                        <?php if ($jobSearch !== ''): ?>
                            <input type="hidden" name="job_search" value="<?= esc($jobSearch) ?>">
                        <?php endif; ?>

                        <?php foreach ($jobPaymentTypes as $type): ?>
                            <input type="hidden" name="payment_types[]" value="<?= esc($type) ?>">
                        <?php endforeach; ?>

                        <div class="filter-dropdown">
                            <button type="button" class="filter-btn" onclick="toggleClosedTypeFilter()">
                                Filter Type
                            </button>

                            <div id="closedTypeFilterMenu" class="filter-menu hidden">
                                <?php foreach ($paymentTypeRows as $type): ?>
                                    <label class="filter-option">
                                        <input
                                            type="checkbox"
                                            name="closed_payment_types[]"
                                            value="<?= esc($type['code']) ?>"
                                            <?= in_array($type['code'], $closedPaymentTypes, true) ? 'checked' : '' ?>
                                        >
                                        <?= esc($type['label']) ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <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" formaction="export_closed_jobs_excel.php" class="export-btn">
                            Export Excel
                        </button>

                        <?php if ($closedJobSearch !== '' || !empty($closedPaymentTypes) || $closedJobMonth > 0): ?>
                            <a href="admin-dashboard.php" class="small-link">Clear</a>
                        <?php endif; ?>

                        <?php if (!empty($closedPaymentTypes)): ?>
                            <div class="selected-types">
                                <?php foreach ($closedPaymentTypes as $selectedType): ?>
                                    <span class="selected-type-chip">
                                        <?= esc(paymentTypeLabel($selectedType, $paymentTypeMap)) ?>
                                    </span>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($closedJobMonth > 0): ?>
                            <div class="selected-types">
                                <span class="selected-type-chip">
                                    Month: <?= esc($monthNames[$closedJobMonth] ?? $closedJobMonth) ?>
                                </span>
                            </div>
                        <?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 ($recentClosedJobs): ?>
                                <?php foreach ($recentClosedJobs as $job): ?>
                                    <?php
                                        $displayCustomer = ($job['job_type'] ?? '') === 'machine'
                                            ? ($job['machine_customer_name'] ?? '')
                                            : ($job['normal_customer_name'] ?? '');
                                    ?>
                                    <tr>
                                        <td class="job-no">
                                            <a href="view-job.php?id=<?= (int)$job['id'] ?>">
                                                <?= formatJobNo($job['job_no']) ?>
                                            </a>
                                        </td>

                                        <td>
                                            <span class="job-type-badge">
                                                <?= esc(paymentTypeLabel($job['payment_type'] ?? '', $paymentTypeMap)) ?>
                                            </span>
                                        </td>

                                        <td><?= esc($displayCustomer ?: '-') ?></td>

                                        <td>
                                            <?= esc($job['unique_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="view-job.php?id=<?= (int)$job['id'] ?>" target="_blank" rel="noopener noreferrer">Open</a>
                                                    <a
                                                        href="delete_job.php?id=<?= (int)$job['id'] ?>"
                                                        class="delete-link"
                                                        onclick="return confirm('Are you sure you want to delete this job?');"
                                                    >
                                                        Delete
                                                    </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;
                const allDropdowns = document.querySelectorAll('.action-dropdown');

                allDropdowns.forEach(menu => {
                    if (menu !== dropdown) {
                        menu.classList.remove('show');
                    }
                });

                dropdown.classList.toggle('show');
            }

            function toggleTypeFilter() {
                const menu = document.getElementById('typeFilterMenu');
                if (menu) {
                    menu.classList.toggle('hidden');
                }
            }

            function toggleClosedTypeFilter() {
                const menu = document.getElementById('closedTypeFilterMenu');
                if (menu) {
                    menu.classList.toggle('hidden');
                }
            }

            document.addEventListener('click', function (event) {
                if (!event.target.closest('.action-menu')) {
                    document.querySelectorAll('.action-dropdown').forEach(menu => {
                        menu.classList.remove('show');
                    });
                }

                const activeFilter = document.getElementById('typeFilterMenu');
                const activeFilterWrap = event.target.closest('#typeFilterMenu, .filter-btn');
                if (activeFilter && !activeFilterWrap) {
                    activeFilter.classList.add('hidden');
                }

                const closedFilter = document.getElementById('closedTypeFilterMenu');
                const closedFilterWrap = event.target.closest('#closedTypeFilterMenu, .filter-btn');
                if (closedFilter && !closedFilterWrap) {
                    closedFilter.classList.add('hidden');
                }
            });

            setInterval(function () {
                window.location.reload();
            }, 30000);
        </script>
    </div>
    <script>
    // Save scroll position before reload
    window.addEventListener('beforeunload', function () {
        localStorage.setItem('scrollPosition', window.scrollY);
    });

    // Restore scroll position after reload
    window.addEventListener('load', function () {
        const scrollPosition = localStorage.getItem('scrollPosition');
        if (scrollPosition !== null) {
            window.scrollTo(0, parseInt(scrollPosition));
            localStorage.removeItem('scrollPosition');
        }
    });
</script>
</body>
</html>