<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/layout.php';

require_permission($conn, 'dashboard');

ensure_order_branch_column($conn);
ensure_order_return_column($conn);
ensure_order_bill_number_column($conn);
ensure_order_source_column($conn);
ensure_car_profile_columns($conn);

$canOpenQueueDetails = can_access($conn, 'queue');
$canOpenQuickService = can_access($conn, 'quick_service');

$todayStart = date('Y-m-d 00:00:00');
$tomorrowStart = date('Y-m-d 00:00:00', strtotime('+1 day'));
$monthStart = date('Y-m-01 00:00:00');
$nextMonthStart = date('Y-m-01 00:00:00', strtotime('first day of next month'));
$monthLabel = date('M Y');

$todaySummary = array(
    'total_bills' => 0,
    'booking_bills' => 0,
    'quick_service_bills' => 0,
    'waiting_total' => 0,
    'washing_total' => 0,
    'done_total' => 0,
    'cancelled_total' => 0,
    'unpaid_total' => 0,
    'partial_total' => 0,
    'paid_total' => 0,
    'opened_total' => 0.0,
    'deposit_admin_total' => 0.0,
    'deposit_branch_total' => 0.0,
);

$todaySummaryTypes = 'ss';
$todaySummaryParams = array($todayStart, $tomorrowStart);
$todaySummaryWhere = array(
    'o.order_date >= ?',
    'o.order_date < ?',
);
$branchCondition = auth_branch_condition($conn, 'o', $todaySummaryTypes, $todaySummaryParams);
if ($branchCondition !== '') {
    $todaySummaryWhere[] = $branchCondition;
}
$todaySummaryStmt = db_prepare($conn, "
    SELECT
        COUNT(*) AS total_bills,
        SUM(CASE WHEN o.order_source = 'booking' THEN 1 ELSE 0 END) AS booking_bills,
        SUM(CASE WHEN o.order_source = 'quick_service' THEN 1 ELSE 0 END) AS quick_service_bills,
        SUM(CASE WHEN o.status = 'waiting' THEN 1 ELSE 0 END) AS waiting_total,
        SUM(CASE WHEN o.status = 'washing' THEN 1 ELSE 0 END) AS washing_total,
        SUM(CASE WHEN o.status = 'done' THEN 1 ELSE 0 END) AS done_total,
        SUM(CASE WHEN o.status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled_total,
        SUM(CASE WHEN o.payment_status = 'unpaid' THEN 1 ELSE 0 END) AS unpaid_total,
        SUM(CASE WHEN o.payment_status = 'partial' THEN 1 ELSE 0 END) AS partial_total,
        SUM(CASE WHEN o.payment_status = 'paid' THEN 1 ELSE 0 END) AS paid_total,
        COALESCE(SUM(CASE WHEN o.status <> 'cancelled' THEN o.total_price ELSE 0 END), 0) AS opened_total,
        COALESCE(SUM(o.admin_deposit_amount), 0) AS deposit_admin_total,
        COALESCE(SUM(o.branch_deposit_amount), 0) AS deposit_branch_total
    FROM orders o
    WHERE " . implode(' AND ', $todaySummaryWhere) . "
");
$todaySummaryStmt->bind_param($todaySummaryTypes, ...$todaySummaryParams);
$todaySummaryStmt->execute();
$todaySummaryResult = $todaySummaryStmt->get_result()->fetch_assoc();
$todaySummaryStmt->close();
if (is_array($todaySummaryResult)) {
    $todaySummary = array_merge($todaySummary, $todaySummaryResult);
}

$paymentToday = array(
    'payment_total' => 0.0,
    'payment_rows' => 0,
    'cash_total' => 0.0,
    'transfer_total' => 0.0,
    'qr_total' => 0.0,
    'card_total' => 0.0,
);

$branchTodayRows = array();
$branchTodayPayments = array();
$branchTodayTypes = 'ss';
$branchTodayParams = array($todayStart, $tomorrowStart);
$branchTodayWhere = array(
    'o.order_date >= ?',
    'o.order_date < ?',
);
$branchCondition = auth_branch_condition($conn, 'o', $branchTodayTypes, $branchTodayParams);
if ($branchCondition !== '') {
    $branchTodayWhere[] = $branchCondition;
}
$branchTodayStmt = db_prepare($conn, "
    SELECT
        COALESCE(NULLIF(o.branch_name, ''), 'No branch') AS branch_name,
        COUNT(*) AS total_bills,
        SUM(CASE WHEN o.order_source = 'booking' THEN 1 ELSE 0 END) AS booking_bills,
        SUM(CASE WHEN o.order_source = 'quick_service' THEN 1 ELSE 0 END) AS quick_service_bills,
        SUM(CASE WHEN o.status = 'waiting' THEN 1 ELSE 0 END) AS waiting_total,
        SUM(CASE WHEN o.status = 'washing' THEN 1 ELSE 0 END) AS washing_total,
        SUM(CASE WHEN o.status = 'done' THEN 1 ELSE 0 END) AS done_total
    FROM orders o
    WHERE " . implode(' AND ', $branchTodayWhere) . "
    GROUP BY COALESCE(NULLIF(o.branch_name, ''), 'No branch')
    ORDER BY total_bills DESC, branch_name ASC
");
$branchTodayStmt->bind_param($branchTodayTypes, ...$branchTodayParams);
$branchTodayStmt->execute();
$branchTodayResult = $branchTodayStmt->get_result();
if ($branchTodayResult instanceof mysqli_result) {
    while ($row = $branchTodayResult->fetch_assoc()) {
        $branchTodayRows[] = $row;
    }
}
$branchTodayStmt->close();

$paymentTypes = 'ss';
$paymentParams = array($todayStart, $tomorrowStart);
$paymentWhere = array(
    'p.payment_date >= ?',
    'p.payment_date < ?',
);
$branchCondition = auth_branch_condition($conn, 'o', $paymentTypes, $paymentParams);
if ($branchCondition !== '') {
    $paymentWhere[] = $branchCondition;
}
$paymentBreakdownStmt = db_prepare($conn, "
    SELECT
        COALESCE(NULLIF(o.branch_name, ''), 'No branch') AS branch_name,
        p.payment_method,
        COUNT(*) AS payment_rows,
        COALESCE(SUM(p.amount), 0) AS payment_total
    FROM payments p
    INNER JOIN orders o ON o.order_id = p.order_id
    WHERE " . implode(' AND ', $paymentWhere) . "
    GROUP BY COALESCE(NULLIF(o.branch_name, ''), 'No branch'), p.payment_method
");
$paymentBreakdownStmt->bind_param($paymentTypes, ...$paymentParams);
$paymentBreakdownStmt->execute();
$paymentBreakdownResult = $paymentBreakdownStmt->get_result();
if ($paymentBreakdownResult instanceof mysqli_result) {
    while ($row = $paymentBreakdownResult->fetch_assoc()) {
        $branchName = (string) ($row['branch_name'] ?? 'No branch');
        $paymentMethod = (string) ($row['payment_method'] ?? '');
        $paymentRows = (int) ($row['payment_rows'] ?? 0);
        $paymentTotal = (float) ($row['payment_total'] ?? 0);

        $paymentToday['payment_rows'] += $paymentRows;
        $paymentToday['payment_total'] += $paymentTotal;
        $branchTodayPayments[$branchName] = (float) ($branchTodayPayments[$branchName] ?? 0) + $paymentTotal;

        if ($paymentMethod === 'cash') {
            $paymentToday['cash_total'] += $paymentTotal;
        } elseif ($paymentMethod === 'transfer') {
            $paymentToday['transfer_total'] += $paymentTotal;
        } elseif ($paymentMethod === 'qr') {
            $paymentToday['qr_total'] += $paymentTotal;
        } elseif ($paymentMethod === 'card') {
            $paymentToday['card_total'] += $paymentTotal;
        }
    }
}
$paymentBreakdownStmt->close();

foreach ($branchTodayRows as &$branchTodayRow) {
    $branchName = (string) ($branchTodayRow['branch_name'] ?? 'No branch');
    $branchTodayRow['paid_today'] = (float) ($branchTodayPayments[$branchName] ?? 0);
}
unset($branchTodayRow);

$followUpRows = array();
$followUpTypes = '';
$followUpParams = array();
$followUpWhere = array(
    "o.status = 'done'",
    "o.payment_status <> 'paid'",
);
$branchCondition = auth_branch_condition($conn, 'o', $followUpTypes, $followUpParams);
if ($branchCondition !== '') {
    $followUpWhere[] = $branchCondition;
}
$followUpStmt = db_prepare($conn, "
    SELECT
        o.order_id,
        o.bill_number,
        o.branch_name,
        o.order_source,
        o.order_date,
        o.total_price,
        o.payment_status,
        c.name AS customer_name,
        car.plate_number,
        car.profile_image_path,
        car.profile_image_name
    FROM orders o
    INNER JOIN customers c ON c.customer_id = o.customer_id
    INNER JOIN cars car ON car.car_id = o.car_id
    WHERE " . implode(' AND ', $followUpWhere) . "
    ORDER BY o.order_date DESC, o.order_id DESC
    LIMIT 8
");
if ($followUpTypes !== '') {
    $followUpStmt->bind_param($followUpTypes, ...$followUpParams);
}
$followUpStmt->execute();
$followUpResult = $followUpStmt->get_result();
if ($followUpResult instanceof mysqli_result) {
    while ($row = $followUpResult->fetch_assoc()) {
        $followUpRows[] = $row;
    }
}
$followUpStmt->close();

$followUpPaymentMap = order_payment_summary_map($conn, array_column($followUpRows, 'order_id'));
foreach ($followUpRows as &$followUpRow) {
    $orderId = (int) ($followUpRow['order_id'] ?? 0);
    $paymentSummary = $followUpPaymentMap[$orderId] ?? order_payment_summary_defaults();
    $followUpRow['paid_amount'] = (float) ($paymentSummary['total_amount'] ?? 0);
}
unset($followUpRow);

$pickupRows = array();
$pickupTypes = 's';
$pickupParams = array($tomorrowStart);
$pickupWhere = array(
    "o.order_source = 'booking'",
    "o.status <> 'cancelled'",
    'o.return_at IS NOT NULL',
    'o.return_at < ?',
);
$branchCondition = auth_branch_condition($conn, 'o', $pickupTypes, $pickupParams);
if ($branchCondition !== '') {
    $pickupWhere[] = $branchCondition;
}
$pickupStmt = db_prepare($conn, "
    SELECT
        o.order_id,
        o.bill_number,
        o.branch_name,
        o.status,
        o.payment_status,
        o.return_at,
        c.name AS customer_name,
        car.plate_number,
        car.profile_image_path,
        car.profile_image_name
    FROM orders o
    INNER JOIN customers c ON c.customer_id = o.customer_id
    INNER JOIN cars car ON car.car_id = o.car_id
    WHERE " . implode(' AND ', $pickupWhere) . "
    ORDER BY o.return_at ASC, o.order_id ASC
    LIMIT 8
");
$pickupStmt->bind_param($pickupTypes, ...$pickupParams);
$pickupStmt->execute();
$pickupResult = $pickupStmt->get_result();
if ($pickupResult instanceof mysqli_result) {
    while ($row = $pickupResult->fetch_assoc()) {
        $pickupRows[] = $row;
    }
}
$pickupStmt->close();

$dashboardQueueRows = array();
$dashboardQueueStatusCounts = array(
    'waiting' => 0,
    'washing' => 0,
    'done' => 0,
    'cancelled' => 0,
);
$dashboardQueueTypes = '';
$dashboardQueueParams = array();
$dashboardQueueWhere = array(
    "o.order_source = 'booking'",
    "(
        o.status IN ('waiting', 'washing')
        OR (o.status = 'done' AND (o.payment_status <> 'paid' OR DATE(COALESCE(payment_summary.last_payment_at, o.finished_at, o.order_date)) = CURDATE()))
    )",
);
$branchCondition = auth_branch_condition($conn, 'o', $dashboardQueueTypes, $dashboardQueueParams);
if ($branchCondition !== '') {
    $dashboardQueueWhere[] = $branchCondition;
}
$dashboardQueueWhereSql = implode(' AND ', $dashboardQueueWhere);
$dashboardQueueStmt = db_prepare($conn, "
    SELECT
        o.order_id,
        o.bill_number,
        o.order_date,
        o.branch_name,
        o.status,
        o.payment_status,
        c.name AS customer_name,
        car.plate_number,
        q.queue_number,
        q.created_at AS queued_at
    FROM orders o
    INNER JOIN customers c ON c.customer_id = o.customer_id
    INNER JOIN cars car ON car.car_id = o.car_id
    LEFT JOIN queue q ON q.order_id = o.order_id
    LEFT JOIN (
        SELECT order_id, MAX(payment_date) AS last_payment_at
        FROM payments
        GROUP BY order_id
    ) payment_summary ON payment_summary.order_id = o.order_id
    WHERE {$dashboardQueueWhereSql}
    ORDER BY FIELD(o.status, 'waiting', 'washing', 'done'), COALESCE(q.queue_number, 999999), COALESCE(q.created_at, o.order_date), o.order_id
    LIMIT 4
");
if ($dashboardQueueTypes !== '') {
    $dashboardQueueStmt->bind_param($dashboardQueueTypes, ...$dashboardQueueParams);
}
$dashboardQueueStmt->execute();
$dashboardQueueResult = $dashboardQueueStmt->get_result();
if ($dashboardQueueResult instanceof mysqli_result) {
    while ($row = $dashboardQueueResult->fetch_assoc()) {
        $dashboardQueueRows[] = $row;
    }
}
$dashboardQueueStmt->close();

$dashboardQueueCountTypes = '';
$dashboardQueueCountParams = array();
$dashboardQueueCountWhere = array(
    "o.order_source = 'booking'",
    "(
        o.status IN ('waiting', 'washing')
        OR (o.status = 'done' AND (o.payment_status <> 'paid' OR DATE(COALESCE(payment_summary.last_payment_at, o.finished_at, o.order_date)) = CURDATE()))
        OR (o.status = 'cancelled' AND DATE(COALESCE(o.cancelled_at, o.order_date)) = CURDATE())
    )",
);
$branchCondition = auth_branch_condition($conn, 'o', $dashboardQueueCountTypes, $dashboardQueueCountParams);
if ($branchCondition !== '') {
    $dashboardQueueCountWhere[] = $branchCondition;
}
$dashboardQueueCountWhereSql = implode(' AND ', $dashboardQueueCountWhere);
$dashboardQueueCountStmt = db_prepare($conn, "
    SELECT o.status, COUNT(*) AS total
    FROM orders o
    LEFT JOIN (
        SELECT order_id, MAX(payment_date) AS last_payment_at
        FROM payments
        GROUP BY order_id
    ) payment_summary ON payment_summary.order_id = o.order_id
    WHERE {$dashboardQueueCountWhereSql}
    GROUP BY o.status
");
if ($dashboardQueueCountTypes !== '') {
    $dashboardQueueCountStmt->bind_param($dashboardQueueCountTypes, ...$dashboardQueueCountParams);
}
$dashboardQueueCountStmt->execute();
$dashboardQueueCountResult = $dashboardQueueCountStmt->get_result();
if ($dashboardQueueCountResult instanceof mysqli_result) {
    while ($row = $dashboardQueueCountResult->fetch_assoc()) {
        $statusKey = (string) ($row['status'] ?? '');
        if (array_key_exists($statusKey, $dashboardQueueStatusCounts)) {
            $dashboardQueueStatusCounts[$statusKey] = (int) ($row['total'] ?? 0);
        }
    }
}
$dashboardQueueCountStmt->close();
$dashboardQueueTotal = (int) ($dashboardQueueStatusCounts['waiting'] ?? 0)
    + (int) ($dashboardQueueStatusCounts['washing'] ?? 0)
    + (int) ($dashboardQueueStatusCounts['done'] ?? 0);

$branchRevenueRows = array();
$branchRevenueTotal = 0.0;
$branchRevenuePaidTotal = 0.0;
$branchRevenueMax = 0.0;
$branchRevenueTypes = 'ss';
$branchRevenueParams = array($monthStart, $nextMonthStart);
$branchRevenueWhere = array(
    'o.order_date >= ?',
    'o.order_date < ?',
    "o.status <> 'cancelled'",
);
$branchCondition = auth_branch_condition($conn, 'o', $branchRevenueTypes, $branchRevenueParams);
if ($branchCondition !== '') {
    $branchRevenueWhere[] = $branchCondition;
}
$branchRevenueStmt = db_prepare($conn, "
    SELECT
        COALESCE(NULLIF(o.branch_name, ''), 'No branch') AS branch_name,
        COUNT(*) AS bill_count,
        COALESCE(SUM(o.total_price), 0) AS revenue
    FROM orders o
    WHERE " . implode(' AND ', $branchRevenueWhere) . "
    GROUP BY COALESCE(NULLIF(o.branch_name, ''), 'No branch')
    ORDER BY revenue DESC, branch_name ASC
");
$branchRevenueStmt->bind_param($branchRevenueTypes, ...$branchRevenueParams);
$branchRevenueStmt->execute();
$branchRevenueResult = $branchRevenueStmt->get_result();
if ($branchRevenueResult instanceof mysqli_result) {
    while ($row = $branchRevenueResult->fetch_assoc()) {
        $row['revenue'] = (float) ($row['revenue'] ?? 0);
        $row['paid_amount'] = 0.0;
        $row['bill_count'] = (int) ($row['bill_count'] ?? 0);
        $branchRevenueRows[] = $row;
    }
}
$branchRevenueStmt->close();

$branchRevenuePayments = array();
$branchRevenuePaymentTypes = $branchRevenueTypes;
$branchRevenuePaymentParams = $branchRevenueParams;
$branchRevenuePaymentWhere = $branchRevenueWhere;
$branchRevenuePaymentStmt = db_prepare($conn, "
    SELECT
        COALESCE(NULLIF(o.branch_name, ''), 'No branch') AS branch_name,
        COALESCE(SUM(p.amount), 0) AS paid_amount
    FROM orders o
    LEFT JOIN payments p ON p.order_id = o.order_id
    WHERE " . implode(' AND ', $branchRevenuePaymentWhere) . "
    GROUP BY COALESCE(NULLIF(o.branch_name, ''), 'No branch')
");
$branchRevenuePaymentStmt->bind_param($branchRevenuePaymentTypes, ...$branchRevenuePaymentParams);
$branchRevenuePaymentStmt->execute();
$branchRevenuePaymentResult = $branchRevenuePaymentStmt->get_result();
if ($branchRevenuePaymentResult instanceof mysqli_result) {
    while ($row = $branchRevenuePaymentResult->fetch_assoc()) {
        $branchRevenuePayments[(string) ($row['branch_name'] ?? 'No branch')] = (float) ($row['paid_amount'] ?? 0);
    }
}
$branchRevenuePaymentStmt->close();

foreach ($branchRevenueRows as &$branchRevenueRow) {
    $branchName = (string) ($branchRevenueRow['branch_name'] ?? 'No branch');
    $branchRevenueRow['paid_amount'] = (float) ($branchRevenuePayments[$branchName] ?? 0);
    $branchRevenueTotal += (float) ($branchRevenueRow['revenue'] ?? 0);
    $branchRevenuePaidTotal += (float) ($branchRevenueRow['paid_amount'] ?? 0);
    $branchRevenueMax = max($branchRevenueMax, (float) ($branchRevenueRow['revenue'] ?? 0));
}
unset($branchRevenueRow);

$todayNeedsPayment = (int) ($todaySummary['unpaid_total'] ?? 0) + (int) ($todaySummary['partial_total'] ?? 0);
$dashboardTodayRevenueAmount = (float) ($todaySummary['opened_total'] ?? 0);
$revenueComparisonMax = max($branchRevenueTotal, $branchRevenuePaidTotal);
$revenueOutstandingTotal = max(0.0, $branchRevenueTotal - $branchRevenuePaidTotal);
$todayCompletionRate = (int) round(((int) ($todaySummary['done_total'] ?? 0) / max(1, (int) ($todaySummary['total_bills'] ?? 0))) * 100);
$todayAverageBill = (float) ($todaySummary['opened_total'] ?? 0) / max(1, (int) ($todaySummary['total_bills'] ?? 0));
$monthlyCollectedPercent = $branchRevenueTotal > 0 ? (int) round(($branchRevenuePaidTotal / $branchRevenueTotal) * 100) : 0;
$topBranchRows = array_slice($branchTodayRows, 0, 4);
$paymentMixRows = array(
    array('cash', (float) ($paymentToday['cash_total'] ?? 0), 'is-cash', 'cash'),
    array('transfer', (float) ($paymentToday['transfer_total'] ?? 0), 'is-transfer', 'transfer'),
    array('qr', (float) ($paymentToday['qr_total'] ?? 0), 'is-qr', 'qr'),
    array('card', (float) ($paymentToday['card_total'] ?? 0), 'is-card', 'card'),
);

$dashboardRange = (string) ($_GET['range'] ?? '7d');
$allowedDashboardRanges = array('today', 'yesterday', '7d', 'month');
if (!in_array($dashboardRange, $allowedDashboardRanges, true)) {
    $dashboardRange = '7d';
}

$trendStart = date('Y-m-d 00:00:00', strtotime('-6 days'));
$trendEnd = $tomorrowStart;
$trendDates = array();
if ($dashboardRange === 'today') {
    $trendStart = $todayStart;
    $trendEnd = $tomorrowStart;
    $trendDates[] = date('Y-m-d');
} elseif ($dashboardRange === 'yesterday') {
    $trendStart = date('Y-m-d 00:00:00', strtotime('-1 day'));
    $trendEnd = $todayStart;
    $trendDates[] = date('Y-m-d', strtotime('-1 day'));
} elseif ($dashboardRange === 'month') {
    $trendStart = $monthStart;
    $trendEnd = $tomorrowStart;
    $cursorDay = strtotime(date('Y-m-d', strtotime($monthStart)));
    $lastDay = strtotime(date('Y-m-d'));
    while ($cursorDay !== false && $cursorDay <= $lastDay) {
        $trendDates[] = date('Y-m-d', $cursorDay);
        $cursorDay = strtotime('+1 day', $cursorDay);
    }
} else {
    for ($i = 6; $i >= 0; $i--) {
        $trendDates[] = date('Y-m-d', strtotime('-' . $i . ' days'));
    }
}
$trendRevenueMap = array_fill_keys($trendDates, 0.0);
$trendTypes = 'ss';
$trendParams = array($trendStart, $trendEnd);
$trendWhere = array(
    'o.order_date >= ?',
    'o.order_date < ?',
    "o.status <> 'cancelled'",
);
$branchCondition = auth_branch_condition($conn, 'o', $trendTypes, $trendParams);
if ($branchCondition !== '') {
    $trendWhere[] = $branchCondition;
}
$trendStmt = db_prepare($conn, "
    SELECT DATE(o.order_date) AS day_key, COALESCE(SUM(o.total_price), 0) AS day_total
    FROM orders o
    WHERE " . implode(' AND ', $trendWhere) . "
    GROUP BY DATE(o.order_date)
");
$trendStmt->bind_param($trendTypes, ...$trendParams);
$trendStmt->execute();
$trendResult = $trendStmt->get_result();
if ($trendResult instanceof mysqli_result) {
    while ($row = $trendResult->fetch_assoc()) {
        $dayKey = (string) ($row['day_key'] ?? '');
        if (isset($trendRevenueMap[$dayKey])) {
            $trendRevenueMap[$dayKey] = (float) ($row['day_total'] ?? 0);
        }
    }
}
$trendStmt->close();

$trendLabels = array();
$trendValues = array();
foreach ($trendDates as $dayKey) {
    $trendLabels[] = date('d/m', strtotime($dayKey));
    $trendValues[] = (float) ($trendRevenueMap[$dayKey] ?? 0);
}
$trendMaxValue = 1.0;
foreach ($trendValues as $trendValue) {
    $trendMaxValue = max($trendMaxValue, $trendValue);
}

$trendChartWidth = 640;
$trendChartHeight = 228;
$trendPaddingX = 30;
$trendPaddingTop = 22;
$trendPaddingBottom = 32;
$trendPlotWidth = $trendChartWidth - ($trendPaddingX * 2);
$trendPlotHeight = $trendChartHeight - $trendPaddingTop - $trendPaddingBottom;
$trendPoints = array();
$trendCount = count($trendValues);
$trendDivisor = max(1, $trendCount - 1);

for ($i = 0; $i < $trendCount; $i++) {
    $value = (float) ($trendValues[$i] ?? 0);
    $x = $trendPaddingX + (($trendPlotWidth / $trendDivisor) * $i);
    $y = $trendPaddingTop + (($trendMaxValue - $value) / $trendMaxValue) * $trendPlotHeight;
    $xRounded = round($x, 2);
    $yRounded = round($y, 2);

    $trendPoints[] = array(
        'x' => $xRounded,
        'y' => $yRounded,
        'value' => $value,
        'label' => (string) ($trendLabels[$i] ?? ''),
    );
}

$trendLinePath = '';
$trendSmoothPath = '';
$trendSmoothBody = '';
$trendPointCount = count($trendPoints);
if ($trendPointCount === 1) {
    $trendLinePath = 'M' . $trendPoints[0]['x'] . ' ' . $trendPoints[0]['y'];
    $trendSmoothPath = $trendLinePath;
} elseif ($trendPointCount > 1) {
    $lineParts = array('M' . $trendPoints[0]['x'] . ' ' . $trendPoints[0]['y']);
    $smoothParts = array('M' . $trendPoints[0]['x'] . ' ' . $trendPoints[0]['y']);

    for ($i = 1; $i < $trendPointCount; $i++) {
        $lineParts[] = 'L' . $trendPoints[$i]['x'] . ' ' . $trendPoints[$i]['y'];
    }

    for ($i = 0; $i < $trendPointCount - 1; $i++) {
        $p0 = $trendPoints[max(0, $i - 1)];
        $p1 = $trendPoints[$i];
        $p2 = $trendPoints[$i + 1];
        $p3 = $trendPoints[min($trendPointCount - 1, $i + 2)];

        $cp1x = round((float) $p1['x'] + ((float) $p2['x'] - (float) $p0['x']) / 6, 2);
        $cp1y = round((float) $p1['y'] + ((float) $p2['y'] - (float) $p0['y']) / 6, 2);
        $cp2x = round((float) $p2['x'] - ((float) $p3['x'] - (float) $p1['x']) / 6, 2);
        $cp2y = round((float) $p2['y'] - ((float) $p3['y'] - (float) $p1['y']) / 6, 2);
        $smoothParts[] = 'C' . $cp1x . ' ' . $cp1y . ' ' . $cp2x . ' ' . $cp2y . ' ' . $p2['x'] . ' ' . $p2['y'];
    }

    $trendLinePath = implode(' ', $lineParts);
    $trendSmoothPath = implode(' ', $smoothParts);
    $trendSmoothBody = implode(' ', array_slice($smoothParts, 1));
}

$trendAreaPath = '';
if (!empty($trendPoints) && $trendSmoothPath !== '') {
    $firstX = (float) ($trendPoints[0]['x'] ?? $trendPaddingX);
    $lastX = (float) ($trendPoints[$trendCount - 1]['x'] ?? ($trendChartWidth - $trendPaddingX));
    $baseY = $trendPaddingTop + $trendPlotHeight;
    if ($trendSmoothBody === '') {
        $trendAreaPath = 'M' . $firstX . ' ' . $baseY . ' L' . $firstX . ' ' . $trendPoints[0]['y'] . ' L' . $lastX . ' ' . ($trendPoints[$trendCount - 1]['y'] ?? $baseY) . ' L' . $lastX . ' ' . $baseY . ' Z';
    } else {
        $trendAreaPath = 'M' . $firstX . ' ' . $baseY . ' L' . $firstX . ' ' . $trendPoints[0]['y'] . ' ' . $trendSmoothBody . ' L' . $lastX . ' ' . $baseY . ' Z';
    }
}

$canOpenBooking = can_access($conn, 'booking');
$canOpenOpenBill = can_access_open_bill($conn);
$canOpenMember = can_access($conn, 'member');
$canOpenBillManagement = can_access($conn, 'bill_management');
$canOpenSaleReport = can_access($conn, 'sale_report');
$canOpenManageSystem = can_access_manage_system($conn);
$dashboardTodayDate = date('Y-m-d');
$dashboardMonthValue = date('Y-m');
$dashboardTodaySalesUrl = $canOpenSaleReport ? 'sale_report.php?load=1&period=daily&date=' . urlencode($dashboardTodayDate) : '';
$dashboardMonthSalesUrl = $canOpenSaleReport ? 'sale_report.php?load=1&period=monthly&month=' . urlencode($dashboardMonthValue) : '';
$dashboardTodayBillsUrl = $canOpenBillManagement
    ? 'bill_management.php?load=1&period=day&date=' . urlencode($dashboardTodayDate)
    : ($canOpenQueueDetails ? 'queue.php?status=waiting' : '');
$dashboardWaitingQueueUrl = $canOpenQueueDetails ? 'queue.php?status=waiting' : $dashboardTodayBillsUrl;
$dashboardInProgressUrl = $canOpenQueueDetails ? 'queue.php?status=washing' : $dashboardTodayBillsUrl;
$dashboardCompletedQueueUrl = $canOpenQueueDetails ? 'queue.php?status=done' : $dashboardTodayBillsUrl;
$dashboardWaitingPaymentUrl = $canOpenQueueDetails
    ? 'queue.php?status=done'
    : ($canOpenSaleReport ? 'sale_report.php?load=1&period=monthly&month=' . urlencode($dashboardMonthValue) . '&payment_status=unpaid' : '');
$dashboardFollowupUrl = $canOpenSaleReport
    ? 'sale_report.php?load=1&period=monthly&month=' . urlencode($dashboardMonthValue) . '&payment_status=partial'
    : $dashboardWaitingPaymentUrl;
$dashboardPickupUrl = $dashboardWaitingQueueUrl;
$dashboardTodayRevenueUrl = $dashboardTodaySalesUrl !== '' ? $dashboardTodaySalesUrl : $dashboardTodayBillsUrl;

$currentUser = auth_current_user($conn);
$dashboardLanguageReturnTo = current_page_return('dashboard.php');
$scopeLabel = console_scope_label($conn);

function dashboard_order_href(mysqli $conn, array $row, string $bookingAnchor = ''): string
{
    $href = notification_center_order_href($conn, $row);
    if ($href === '') {
        return '';
    }

    if ($bookingAnchor !== '' && (string) ($row['order_source'] ?? 'booking') === 'booking') {
        return $href . $bookingAnchor;
    }

    return $href;
}

if (!function_exists('dashboard_branch_label')) {
    function dashboard_branch_label(string $branchName): string
    {
        $normalized = trim($branchName);
        if ($normalized === '' || $normalized === 'No branch') {
            return localized_text_value('ไม่มีสาขา', 'No branch');
        }

        return $branchName;
    }
}

if (!function_exists('dashboard_order_source_label')) {
    function dashboard_order_source_label(string $orderSource): string
    {
        if ($orderSource === 'quick_service') {
            return localized_text_value('ควิกเซอร์วิส', 'Quick Service');
        }

        return localized_text_value('งานจอง', 'Booking');
    }
}

if (!function_exists('dashboard_payment_method_label')) {
    function dashboard_payment_method_label(string $paymentMethod): string
    {
        switch ($paymentMethod) {
            case 'transfer':
                return localized_text_value('โอนเงิน', 'Transfer');
            case 'qr':
                return localized_text_value('คิวอาร์', 'QR');
            case 'card':
                return localized_text_value('บัตร', 'Card');
            case 'cash':
            default:
                return localized_text_value('เงินสด', 'Cash');
        }
    }
}

if (!function_exists('dashboard_compact_amount')) {
    function dashboard_compact_amount(float $amount): string
    {
        if ($amount >= 1000000) {
            return rtrim(rtrim(number_format($amount / 1000000, 1), '0'), '.') . 'M';
        }

        if ($amount >= 1000) {
            return rtrim(rtrim(number_format($amount / 1000, 1), '0'), '.') . 'K';
        }

        return number_format($amount, 0);
    }
}

if (!function_exists('dashboard_order_bill_label')) {
    function dashboard_order_bill_label(array $row): string
    {
        $billLabel = trim((string) ($row['bill_number'] ?? ''));
        if ($billLabel !== '') {
            return $billLabel;
        }

        return localized_text_value('งาน #', 'Job #') . (int) ($row['order_id'] ?? 0);
    }
}

if (!function_exists('dashboard_icon_svg')) {
    function dashboard_icon_svg(string $icon): string
    {
        $common = 'viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"';

        switch ($icon) {
            case 'dashboard':
                return '<svg ' . $common . '><rect x="4" y="4" width="7" height="7" rx="1.4"></rect><rect x="13" y="4" width="7" height="5" rx="1.4"></rect><rect x="13" y="11" width="7" height="9" rx="1.4"></rect><rect x="4" y="13" width="7" height="7" rx="1.4"></rect></svg>';
            case 'booking':
                return '<svg ' . $common . '><path d="M8 3v3"></path><path d="M16 3v3"></path><rect x="5" y="5.5" width="14" height="15" rx="2"></rect><path d="M8 10h8"></path><path d="M10 14h4"></path></svg>';
            case 'quick':
                return '<svg ' . $common . '><path d="M13 2L4 14h6l-1 8 9-12h-6l1-8z"></path></svg>';
            case 'queue':
                return '<svg ' . $common . '><path d="M6 7h12"></path><path d="M6 12h12"></path><path d="M6 17h8"></path></svg>';
            case 'member':
                return '<svg ' . $common . '><path d="M20 21a7 7 0 0 0-16 0"></path><circle cx="12" cy="8" r="4"></circle></svg>';
            case 'report':
                return '<svg ' . $common . '><path d="M7 3h8l4 4v14H7z"></path><path d="M15 3v5h5"></path><path d="M10 14l2 2 4-5"></path></svg>';
            case 'manage':
                return '<svg ' . $common . '><circle cx="12" cy="12" r="3.2"></circle><path d="M19.4 15a1 1 0 0 0 .2 1.1l.1.1a2 2 0 0 1-2.8 2.8l-.1-.1a1 1 0 0 0-1.1-.2 1 1 0 0 0-.6.9V20a2 2 0 0 1-4 0v-.2a1 1 0 0 0-.6-.9 1 1 0 0 0-1.1.2l-.1.1a2 2 0 0 1-2.8-2.8l.1-.1a1 1 0 0 0 .2-1.1 1 1 0 0 0-.9-.6H4a2 2 0 0 1 0-4h.2a1 1 0 0 0 .9-.6 1 1 0 0 0-.2-1.1l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1 1 0 0 0 1.1.2 1 1 0 0 0 .6-.9V4a2 2 0 0 1 4 0v.2a1 1 0 0 0 .6.9 1 1 0 0 0 1.1-.2l.1-.1a2 2 0 0 1 2.8 2.8l-.1.1a1 1 0 0 0-.2 1.1 1 1 0 0 0 .9.6H20a2 2 0 0 1 0 4h-.2a1 1 0 0 0-.9.6z"></path></svg>';
            case 'cash':
                return '<svg ' . $common . '><rect x="3.5" y="6.5" width="17" height="11" rx="2"></rect><path d="M6.5 12h11"></path><circle cx="12" cy="12" r="2.2"></circle></svg>';
            case 'transfer':
                return '<svg ' . $common . '><path d="M4 20h16"></path><path d="M6 20V9l6-4 6 4v11"></path><path d="M9 12h.01"></path><path d="M12 12h.01"></path><path d="M15 12h.01"></path></svg>';
            case 'qr':
                return '<svg ' . $common . '><path d="M4 4h6v6H4z"></path><path d="M14 4h6v6h-6z"></path><path d="M4 14h6v6H4z"></path><path d="M16 14v2"></path><path d="M20 14v6"></path><path d="M14 16h2"></path><path d="M16 20h4"></path></svg>';
            case 'card':
                return '<svg ' . $common . '><rect x="3.5" y="5.5" width="17" height="13" rx="2"></rect><path d="M3.5 10h17"></path></svg>';
            case 'waiting':
                return '<svg ' . $common . '><path d="M12 7v5l3 2"></path><circle cx="12" cy="12" r="8"></circle></svg>';
            case 'service':
                return '<svg ' . $common . '><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l2.3-2.3a4 4 0 0 1-5.6-5.6l-2.3 2.3a1 1 0 0 0 0 1.4z"></path><path d="M12 8L4 16v4h4l8-8"></path></svg>';
            case 'done':
                return '<svg ' . $common . '><circle cx="12" cy="12" r="8"></circle><path d="M8.5 12.5l2.3 2.3 4.7-5.1"></path></svg>';
            case 'payment':
                return '<svg ' . $common . '><rect x="3.5" y="6.5" width="17" height="11" rx="2"></rect><path d="M16 10.5c-.8.9-2.1 1.5-4 1.5s-3.2-.6-4-1.5"></path><path d="M7 14.5h10"></path></svg>';
            case 'bell':
                return '<svg ' . $common . '><path d="M15 17H5l1.4-1.4A2 2 0 0 0 7 14.2V11a5 5 0 0 1 10 0v3.2a2 2 0 0 0 .6 1.4L19 17h-4"></path><path d="M10 20a2 2 0 0 0 4 0"></path></svg>';
            case 'logout':
                return '<svg ' . $common . '><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path><path d="M16 17l5-5-5-5"></path><path d="M21 12H9"></path></svg>';
            case 'menu':
                return '<svg ' . $common . '><path d="M4 7h16"></path><path d="M4 12h16"></path><path d="M4 17h16"></path></svg>';
            case 'close':
                return '<svg ' . $common . '><path d="M6 6l12 12"></path><path d="M18 6L6 18"></path></svg>';
        }

        return '<svg ' . $common . '><circle cx="12" cy="12" r="8"></circle></svg>';
    }
}

$dashboardNavItems = console_nav_items($conn);

$pageTitle = localized_text_value('แดชบอร์ด', 'Dashboard');
$dashboardHeadline = localized_text_value('ภาพรวมงานคาร์แคร์', 'Car care operations');
$dashboardDescription = localized_text_value(
    'ติดตามคิวงาน ยอดจอง สถานะบริการ และการชำระเงินจากฐานข้อมูล CCW แบบเรียลไทม์',
    'Live work queue, booking totals, service status and payment tracking from the CCW database.'
);
$closeMenuLabel = localized_text_value('ปิดเมนู', 'Close menu');
$dashboardMenuLabel = localized_text_value('เมนูแดชบอร์ด', 'Dashboard menu');
$manageSystemLabel = localized_text_value('จัดการระบบ', 'Manage System');
$logoutLabel = localized_text_value('ออกจากระบบ', 'Logout');
$menuLabel = localized_text_value('เมนู', 'Menu');
$userFallbackLabel = localized_text_value('ผู้ใช้', 'User');
$staffFallbackLabel = localized_text_value('พนักงาน', 'Staff');
$openQueueLabel = localized_text_value('เปิดคิวงาน', 'Open queue');
$quickServiceLabel = localized_text_value('ควิกเซอร์วิส', 'Quick service');
$newBookingLabel = localized_text_value('เปิดงานใหม่', 'New booking');
$branchBillCountLabel = localized_text_value('{count} บิล', '{count} bill(s)');
$completionLabel = localized_text_value('เสร็จแล้ว {percent}%', 'Completion {percent}%');
$averageBillLabel = localized_text_value('ค่าเฉลี่ยต่อบิล {amount}', 'Average bill {amount}');
$totalBillsTodayLabel = localized_text_value('บิลทั้งหมดวันนี้', 'Total bills today');
$bookingTodayLabel = localized_text_value('งานจองวันนี้', 'Booking today');
$waitingCountLabel = localized_text_value('รอดำเนินการ {count}', 'Waiting {count}');
$depositAdminLabel = localized_text_value('มัดจำ @Admin {amount}', 'Deposit @Admin {amount}');
$quickServiceTodayLabel = localized_text_value('ควิกเซอร์วิสวันนี้', 'Quick Service today');
$paidRowsLabel = localized_text_value('รายการรับชำระ {count}', 'Paid rows {count}');
$depositBranchLabel = localized_text_value('มัดจำ @Branch {amount}', 'Deposit @Branch {amount}');
$paymentsTodayLabel = localized_text_value('รับชำระวันนี้', 'Payments today');
$needPaymentCountLabel = localized_text_value('รอรับชำระ {count}', 'Need payment {count}');
$openedTodayLabel = localized_text_value('ยอดเปิดบิลวันนี้ {amount}', 'Opened today {amount}');
$waitingStatusLabel = localized_text_value('รอดำเนินการ', 'Waiting');
$readyToStartLabel = localized_text_value('พร้อมเริ่มงาน', 'Ready to start');
$inServiceLabel = localized_text_value('กำลังให้บริการ', 'In service');
$carsInProgressLabel = localized_text_value('รถที่กำลังทำงาน', 'Cars in progress');
$doneTodayLabel = localized_text_value('เสร็จแล้ววันนี้', 'Done today');
$completedJobsLabel = localized_text_value('งานที่เสร็จแล้ว', 'Completed jobs');
$needPaymentLabel = localized_text_value('รอรับชำระ', 'Need payment');
$unpaidAndPartialLabel = localized_text_value('ค้างชำระและชำระบางส่วน', 'Unpaid and partial');
$todayBusinessTotalsTitle = localized_text_value('สรุปยอดธุรกิจวันนี้', 'Today business totals');
$todayAllOrderSourcesLabel = localized_text_value('วันนี้ / ทุกแหล่งที่มาของงาน', 'Today / all order sources');
$outstandingLabel = localized_text_value('ยอดค้างชำระ', 'Outstanding');
$openedRevenueVsPaidLabel = localized_text_value('ยอดเปิดบิลเทียบกับยอดรับชำระ', 'Opened revenue vs paid');
$collectedLabel = localized_text_value('เก็บเงินแล้ว {percent}% ({amount})', 'Collected {percent}% ({amount})');
$openedLabel = localized_text_value('ยอดเปิดบิล {amount}', 'Opened {amount}');
$recentOrdersTitle = localized_text_value('บิลล่าสุด', 'Recent orders');
$recentOrdersHelper = localized_text_value('บิลใหม่ล่าสุดจากงานจองและควิกเซอร์วิส', 'Newest bills across booking and quick service');
$noRecentOrdersLabel = localized_text_value('ไม่พบบิลล่าสุด', 'No recent orders found.');
$dateLabel = localized_text_value('วันที่', 'Date');
$billNumberLabel = localized_text_value('เลขที่บิล', 'Bill no.');
$customerLabel = localized_text_value('ลูกค้า', 'Customer');
$branchLabel = localized_text_value('สาขา', 'Branch');
$sourceLabel = localized_text_value('แหล่งที่มา', 'Source');
$statusLabel = localized_text_value('สถานะ', 'Status');
$paymentLabel = localized_text_value('การชำระเงิน', 'Payment');
$totalPriceLabel = localized_text_value('ราคารวม', 'Total price');
$paymentMixTodayTitle = localized_text_value('สัดส่วนการรับชำระวันนี้', 'Payment mix today');
$recognizedPaymentsTodayLabel = localized_text_value('รายการรับชำระที่บันทึกวันนี้', 'Recognized payments recorded today');
$todayBranchSnapshotTitle = localized_text_value('ภาพรวมสาขาวันนี้', 'Today branch snapshot');
$todayBranchSnapshotHelper = localized_text_value('กิจกรรมวันนี้แยกตามสาขา', 'Live activity grouped by branch for today');
$noBranchActivityTodayLabel = localized_text_value('ไม่พบความเคลื่อนไหวของสาขาในวันนี้', 'No branch activity found for today.');
$branchWaitingSummaryLabel = localized_text_value('{count} บิล / รอดำเนินการ {waiting}', '{count} bill(s) / {waiting} waiting');
$branchRevenueTitle = localized_text_value('รายได้รายสาขา', 'Branch revenue');
$branchRevenueHelper = localized_text_value('{month} / ไม่รวมบิลที่ยกเลิก', '{month} / excludes cancelled bills');
$noBranchRevenueLabel = localized_text_value('ไม่พบข้อมูลรายได้ของสาขาในเดือนนี้', 'No branch revenue found this month.');
$pickupDueTitle = localized_text_value('งานรับรถวันนี้และเกินกำหนด', 'Pickup due today and overdue');
$pickupDueHelper = localized_text_value('บิลงานจองที่ควรคืนรถวันนี้หรือเกินกำหนดแล้ว', 'Booking bills that should be returned today or are already overdue');
$noPickupDueLabel = localized_text_value('ไม่มีงานรับรถที่ถึงกำหนดวันนี้', 'No pickup due today.');
$pickupDueLabel = localized_text_value('กำหนดรับรถ', 'Pickup due');
$followUpPaymentTitle = localized_text_value('ติดตามการรับชำระ', 'Follow-up payment');
$followUpPaymentHelper = localized_text_value('บิลที่เสร็จแล้วแต่ยังชำระไม่ครบ', 'Done bills that are still not fully paid');
$noPaymentFollowUpLabel = localized_text_value('ไม่พบบิลที่ต้องติดตามการรับชำระ', 'No payment follow-up found.');
$balanceLabel = localized_text_value('ยอดคงค้าง', 'Balance');

$dashboardGreetingLabel = localized_text_value('สวัสดีครับ', 'Welcome');
$dashboardSnapshotLabel = localized_text_value('ภาพรวมธุรกิจของคุณวันนี้', 'Today business snapshot');
$dashboardTodayRevenueLabel = localized_text_value('รายได้วันนี้', 'Revenue today');
$dashboardCarsTodayLabel = localized_text_value('รถเข้าใช้บริการ', 'Cars served');
$dashboardInProgressLabel = localized_text_value('กำลังดำเนินการ', 'In progress');
$dashboardNeedPaymentLabel = localized_text_value('รอชำระเงิน', 'Waiting payment');
$dashboardOpenQueueLabel = localized_text_value('ดูทั้งหมด', 'View all');
$dashboardQuickActionsLabel = localized_text_value('ทางลัดงานประจำ', 'Quick actions');
$dashboardSevenDaysRevenueLabel = localized_text_value('รายได้ 7 วันย้อนหลัง', '7-day revenue');
$dashboardLineYAxisLabel = localized_text_value('จำนวนเงิน', 'Amount');
$dashboardQueueNowLabel = localized_text_value('คิวปัจจุบัน', 'Current queue');
$dashboardServiceStatusTodayLabel = localized_text_value('สถานะงานวันนี้', 'Today service status');
$dashboardLatestJobsLabel = localized_text_value('รายการล่าสุด', 'Latest jobs');
$dashboardTotalJobsLabel = localized_text_value('รวมทั้งหมด', 'Total');
$dashboardTimeLabel = localized_text_value('เวลา', 'Time');
$dashboardDateHeaderLabel = localized_text_value('วันที่/เวลา', 'Date/Time');
$dashboardBillHeaderLabel = localized_text_value('เลขที่บิล', 'Bill No.');
$dashboardCustomerHeaderLabel = localized_text_value('ลูกค้า/ทะเบียน', 'Customer / Plate');
$dashboardSourceHeaderLabel = localized_text_value('ช่องทาง', 'Source');
$dashboardStatusHeaderLabel = localized_text_value('สถานะ', 'Status');
$dashboardPaymentHeaderLabel = localized_text_value('ชำระเงิน', 'Payment');
$dashboardTotalHeaderLabel = localized_text_value('ยอดรวม', 'Total');
$dashboardTodayOverviewLabel = localized_text_value('ภาพรวมวันนี้', 'Today overview');
$dashboardRevenueGoalLabel = localized_text_value('เป้าหมายรายได้วันนี้', 'Revenue goal');
$dashboardAlertsLabel = localized_text_value('แจ้งเตือน', 'Alerts');
$dashboardNeedsPaymentAlertLabel = localized_text_value('รอชำระเงิน', 'Waiting payments');
$dashboardPickupAlertLabel = localized_text_value('งานถึงกำหนดรับรถ', 'Pickup due');
$dashboardFollowupAlertLabel = localized_text_value('ติดตามการชำระ', 'Payment follow-up');
$dashboardAsOfLabel = localized_text_value('อัปเดตล่าสุด', 'Updated');
$dashboardCountSuffixLabel = localized_text_value('รายการ', 'item(s)');

$dashboardTrendTitle = $dashboardSevenDaysRevenueLabel;
if ($dashboardRange === 'today') {
    $dashboardTrendTitle = localized_text_value('รายได้วันนี้', 'Today revenue');
} elseif ($dashboardRange === 'yesterday') {
    $dashboardTrendTitle = localized_text_value('รายได้เมื่อวาน', 'Yesterday revenue');
} elseif ($dashboardRange === 'month') {
    $dashboardTrendTitle = localized_text_value('รายได้เดือนนี้', 'This month revenue');
}
$dashboardTrendFilters = array(
    array('range' => 'today', 'label' => localized_text_value('วันนี้', 'Today')),
    array('range' => 'yesterday', 'label' => localized_text_value('เมื่อวาน', 'Yesterday')),
    array('range' => '7d', 'label' => localized_text_value('7 วัน', '7 days')),
    array('range' => 'month', 'label' => localized_text_value('เดือนนี้', 'This month')),
);

$dashboardQuickActions = array();
if ($canOpenOpenBill) {
    $dashboardQuickActions[] = array(
        'href' => 'open_bill.php',
        'icon' => dashboard_icon_svg('booking'),
        'title' => localized_text_value('เปิดบิลใหม่', 'Create bill'),
        'subtitle' => 'Open Bill',
    );
}
if ($canOpenBooking) {
    $dashboardQuickActions[] = array(
        'href' => 'booking.php',
        'icon' => dashboard_icon_svg('booking'),
        'title' => localized_text_value('จองคิว', 'Booking'),
        'subtitle' => 'Booking',
    );
}
if ($canOpenQueueDetails) {
    $dashboardQuickActions[] = array(
        'href' => $dashboardWaitingPaymentUrl !== '' ? $dashboardWaitingPaymentUrl : 'queue.php?status=done',
        'icon' => dashboard_icon_svg('payment'),
        'title' => localized_text_value('รับชำระเงิน', 'Receive payment'),
        'subtitle' => 'Receive Payment',
    );
}
if ($canOpenMember) {
    $dashboardQuickActions[] = array(
        'href' => 'member.php',
        'icon' => dashboard_icon_svg('member'),
        'title' => localized_text_value('สมาชิก / ลูกค้า', 'Members'),
        'subtitle' => 'Members',
    );
}

$serviceStatusRows = array(
    array(
        'label' => localized_text_value('กำลังให้บริการ', 'In service'),
        'count' => (int) ($dashboardQueueStatusCounts['washing'] ?? 0),
        'tone' => 'is-cyan',
        'icon' => dashboard_icon_svg('service'),
        'href' => $dashboardInProgressUrl,
    ),
    array(
        'label' => localized_text_value('รอคิว', 'Waiting'),
        'count' => (int) ($dashboardQueueStatusCounts['waiting'] ?? 0),
        'tone' => 'is-blue',
        'icon' => dashboard_icon_svg('waiting'),
        'href' => $dashboardWaitingQueueUrl,
    ),
    array(
        'label' => localized_text_value('เสร็จสิ้น', 'Completed'),
        'count' => (int) ($dashboardQueueStatusCounts['done'] ?? 0),
        'tone' => 'is-green',
        'icon' => dashboard_icon_svg('done'),
        'href' => $dashboardCompletedQueueUrl,
    ),
);
$serviceStatusMax = 1;
foreach ($serviceStatusRows as $serviceStatusRow) {
    $serviceStatusMax = max($serviceStatusMax, (int) ($serviceStatusRow['count'] ?? 0));
}

$paymentPalette = array(
    'cash' => '#27c9bf',
    'qr' => '#5d8dff',
    'transfer' => '#f5bf55',
    'card' => '#f45d72',
);
$paymentLegendRows = array();
$paymentGradientParts = array();
$paymentRangeStart = 0.0;
foreach ($paymentMixRows as $paymentMixRow) {
    $paymentKey = (string) ($paymentMixRow[0] ?? '');
    $paymentAmount = (float) ($paymentMixRow[1] ?? 0);
    $paymentPercent = (float) ($paymentToday['payment_total'] ?? 0) > 0
        ? ($paymentAmount / (float) $paymentToday['payment_total']) * 100
        : 0.0;
    $paymentColor = (string) ($paymentPalette[$paymentKey] ?? '#5d8dff');
    $paymentRangeEnd = min(100.0, $paymentRangeStart + $paymentPercent);
    if ($paymentPercent > 0) {
        $paymentGradientParts[] = $paymentColor . ' ' . number_format($paymentRangeStart, 2, '.', '') . '% ' . number_format($paymentRangeEnd, 2, '.', '') . '%';
    }
    $paymentRangeStart = $paymentRangeEnd;

    $paymentLegendRows[] = array(
        'label' => dashboard_payment_method_label($paymentKey),
        'amount' => $paymentAmount,
        'percent' => (int) round($paymentPercent),
        'color' => $paymentColor,
        'href' => $dashboardTodayRevenueUrl,
    );
}
$paymentMixGradient = empty($paymentGradientParts)
    ? 'conic-gradient(#29405f 0% 100%)'
    : 'conic-gradient(' . implode(', ', $paymentGradientParts) . ')';

$queueRows = $dashboardQueueRows;
$queueBoardRows = array();
foreach ($queueRows as $queueIndex => $row) {
    $statusValue = (string) ($row['status'] ?? 'waiting');
    $queueTone = 'is-waiting';
    if ($statusValue === 'washing') {
        $queueTone = 'is-working';
    } elseif ($statusValue === 'done') {
        $queueTone = 'is-done';
    } elseif ($statusValue === 'cancelled') {
        $queueTone = 'is-cancelled';
    }

    $queueBoardRows[] = array(
        'code' => 'A' . str_pad((string) ($queueIndex + 1), 3, '0', STR_PAD_LEFT),
        'plate' => (string) ($row['plate_number'] ?? '-'),
        'customer' => (string) ($row['customer_name'] ?? ''),
        'status_label' => status_label($statusValue),
        'status_tone' => $queueTone,
        'time' => !empty($row['queued_at'] ?? '') ? date('H:i', strtotime((string) $row['queued_at'])) : date('H:i', strtotime((string) ($row['order_date'] ?? 'now'))),
        'href' => $canOpenQueueDetails ? 'job_details.php?id=' . (int) ($row['order_id'] ?? 0) : '',
    );
}
$dashboardGoalTarget = max(1.0, $branchRevenueTotal > 0 ? $branchRevenueTotal : ($dashboardTodayRevenueAmount * 1.2));
$dashboardGoalProgress = max(0, min(100, (int) round(($dashboardTodayRevenueAmount / $dashboardGoalTarget) * 100)));
$dashboardNowDateLabel = date('d/m/Y H:i');
$dashboardAlerts = array(
    array(
        'label' => $dashboardNeedsPaymentAlertLabel,
        'count' => $todayNeedsPayment,
        'href' => $dashboardWaitingPaymentUrl,
    ),
    array(
        'label' => $dashboardPickupAlertLabel,
        'count' => count($pickupRows),
        'href' => $dashboardPickupUrl,
    ),
    array(
        'label' => $dashboardFollowupAlertLabel,
        'count' => count($followUpRows),
        'href' => $dashboardFollowupUrl,
    ),
);

render_page_start($pageTitle, 'dashboard', array('translation_buffer' => false));
?>

<section class="dashboard-console" data-dashboard-console>
    <aside class="dashboard-console-sidebar">
        <div class="dashboard-console-brand">
            <span class="dashboard-console-logo">CCW</span>
            <div>
                <strong>CCW Car Care</strong>
                <small><?= e($scopeLabel) ?></small>
            </div>
            <button class="dashboard-console-sidebar-close" type="button" aria-label="<?= e($closeMenuLabel) ?>" data-dashboard-sidebar-close>
                <?= nav_icon('close') ?>
            </button>
        </div>

        <nav class="dashboard-console-nav" aria-label="<?= e($dashboardMenuLabel) ?>">
            <?php foreach ($dashboardNavItems as $item): ?>
                <?php $isActive = ((string) ($item['key'] ?? '')) === 'dashboard'; ?>
                <a class="dashboard-console-link<?= $isActive ? ' is-active' : '' ?>" href="<?= e((string) ($item['href'] ?? '#')) ?>" title="<?= e((string) ($item['label'] ?? '')) ?>">
                    <span class="dashboard-console-link-icon"><?= nav_icon((string) ($item['icon'] ?? 'dashboard')) ?></span>
                    <span><?= e((string) ($item['label'] ?? '')) ?></span>
                </a>
            <?php endforeach; ?>
            <?= dashboard_console_service_group('dashboard') ?>
            <?= dashboard_console_employee_group('dashboard') ?>
            <?= dashboard_console_report_group('dashboard') ?>
        </nav>

        <article class="dashboard-console-help-card">
            <span class="dashboard-console-help-icon"><?= dashboard_icon_svg('bell') ?></span>
            <div>
                <strong><?= e(localized_text_value('ศูนย์ช่วยเหลือ', 'Need help?')) ?></strong>
                <small>02-123-4567</small>
            </div>
        </article>

        <div class="dashboard-console-footer">
            <?php if ($canOpenManageSystem): ?>
                <a class="dashboard-console-footer-link" href="manage_system.php" title="<?= e($manageSystemLabel) ?>">
                    <span class="dashboard-console-link-icon"><?= nav_icon('manage') ?></span>
                    <span><?= e($manageSystemLabel) ?></span>
                </a>
            <?php endif; ?>
            <a class="dashboard-console-footer-link" href="../process/logout.php" title="<?= e($logoutLabel) ?>">
                <span class="dashboard-console-link-icon"><?= nav_icon('logout') ?></span>
                <span><?= e($logoutLabel) ?></span>
            </a>
        </div>
    </aside>
    <button class="dashboard-console-backdrop" type="button" hidden aria-label="<?= e($closeMenuLabel) ?>" data-dashboard-sidebar-backdrop></button>

    <div class="dashboard-console-main">
        <section class="dashboard-console-toolbar">
            <div class="dashboard-console-toolbar-copy">
                <h2><?= e($dashboardHeadline) ?></h2>
                <p><?= e($dashboardDescription) ?></p>
            </div>
            <div class="dashboard-console-toolbar-side">
                <button class="dashboard-console-toggle" type="button" aria-label="<?= e($menuLabel) ?>" aria-expanded="true" data-dashboard-sidebar-toggle>
                    <?= dashboard_icon_svg('menu') ?>
                </button>
                <?= render_notification_center($conn, 'dashboard-console-bell', 'notification-center-toolbar') ?>
                <?= render_language_switcher('../process/set_language.php', $dashboardLanguageReturnTo) ?>
                <div class="dashboard-console-user">
                    <span class="dashboard-console-avatar"><?= e(substr((string) ($currentUser['name'] ?? 'U'), 0, 1)) ?></span>
                    <div>
                        <strong><?= e((string) ($currentUser['name'] ?? $userFallbackLabel)) ?></strong>
                        <small><?= e((string) ($currentUser['position_name'] ?? $currentUser['position'] ?? $staffFallbackLabel)) ?></small>
                    </div>
                </div>
            </div>
        </section>

        <section class="dashboard-stage dashboard-stage-neo">
            <section class="dashneo-hero">
                <div class="dashneo-hero-copy">
                    <h1><?= e($dashboardGreetingLabel) ?>, <?= e((string) ($currentUser['name'] ?? $userFallbackLabel)) ?></h1>
                    <p><?= e($dashboardSnapshotLabel) ?></p>
                </div>
                <div class="dashneo-hero-meta">
                    <div class="dashneo-hero-actions">
                        <?php if ($canOpenQueueDetails): ?>
                            <a class="dashneo-hero-btn" href="queue.php"><?= e($openQueueLabel) ?></a>
                        <?php endif; ?>
                        <?php if ($canOpenQuickService): ?>
                            <a class="dashneo-hero-btn" href="quick_service.php"><?= e($quickServiceLabel) ?></a>
                        <?php endif; ?>
                        <?php if ($canOpenBooking): ?>
                            <a class="dashneo-hero-btn is-primary" href="booking.php"><?= e($newBookingLabel) ?></a>
                        <?php endif; ?>
                    </div>
                    <span><?= e($scopeLabel) ?></span>
                    <small><?= e($dashboardAsOfLabel) ?>: <?= e($dashboardNowDateLabel) ?></small>
                </div>
            </section>

            <?php if (!empty($topBranchRows)): ?>
                <section class="dashneo-branch-row">
                    <?php foreach ($topBranchRows as $row): ?>
                        <span class="dashneo-branch-chip">
                            <strong><?= e(dashboard_branch_label((string) ($row['branch_name'] ?? 'No branch'))) ?></strong>
                            <small><?= e(strtr($branchBillCountLabel, array('{count}' => (string) (int) ($row['total_bills'] ?? 0)))) ?></small>
                        </span>
                    <?php endforeach; ?>
                </section>
            <?php endif; ?>

            <section class="dashneo-metric-grid">
                <a class="dashneo-metric-card is-income" href="<?= e($dashboardTodayRevenueUrl !== '' ? $dashboardTodayRevenueUrl : '#') ?>">
                    <div class="dashneo-metric-icon"><?= dashboard_icon_svg('cash') ?></div>
                    <div class="dashneo-metric-copy">
                        <span><?= e($dashboardTodayRevenueLabel) ?></span>
                        <strong><?= format_money($dashboardTodayRevenueAmount) ?></strong>
                        <small><?= e(strtr($completionLabel, array('{percent}' => (string) $todayCompletionRate))) ?></small>
                    </div>
                </a>
                <a class="dashneo-metric-card is-cars" href="<?= e($dashboardTodayBillsUrl !== '' ? $dashboardTodayBillsUrl : '#') ?>">
                    <div class="dashneo-metric-icon"><?= dashboard_icon_svg('queue') ?></div>
                    <div class="dashneo-metric-copy">
                        <span><?= e($dashboardCarsTodayLabel) ?></span>
                        <strong><?= (int) ($todaySummary['total_bills'] ?? 0) ?> <?= e(localized_text_value('คัน', 'cars')) ?></strong>
                        <small><?= e(strtr(localized_text_value('งานจอง {count}', 'Booking {count}'), array('{count}' => (string) (int) ($todaySummary['booking_bills'] ?? 0)))) ?></small>
                    </div>
                </a>
                <a class="dashneo-metric-card is-progress" href="<?= e($dashboardInProgressUrl !== '' ? $dashboardInProgressUrl : '#') ?>">
                    <div class="dashneo-metric-icon"><?= dashboard_icon_svg('service') ?></div>
                    <div class="dashneo-metric-copy">
                        <span><?= e($dashboardInProgressLabel) ?></span>
                        <strong><?= (int) ($todaySummary['washing_total'] ?? 0) ?> <?= e(localized_text_value('คัน', 'cars')) ?></strong>
                        <small><?= e(strtr(localized_text_value('รอคิว {count}', 'Waiting {count}'), array('{count}' => (string) (int) ($todaySummary['waiting_total'] ?? 0)))) ?></small>
                    </div>
                </a>
                <a class="dashneo-metric-card is-payment" href="<?= e($dashboardWaitingPaymentUrl !== '' ? $dashboardWaitingPaymentUrl : '#') ?>">
                    <div class="dashneo-metric-icon"><?= dashboard_icon_svg('payment') ?></div>
                    <div class="dashneo-metric-copy">
                        <span><?= e($dashboardNeedPaymentLabel) ?></span>
                        <strong><?= $todayNeedsPayment ?> <?= e($dashboardCountSuffixLabel) ?></strong>
                        <small><?= format_money($revenueOutstandingTotal) ?></small>
                    </div>
                </a>
            </section>

            <?php if (!empty($dashboardQuickActions)): ?>
                <section class="dashneo-quick-grid" aria-label="<?= e($dashboardQuickActionsLabel) ?>">
                    <?php foreach ($dashboardQuickActions as $dashboardQuickAction): ?>
                        <a class="dashneo-quick-card" href="<?= e((string) ($dashboardQuickAction['href'] ?? '#')) ?>">
                            <span class="dashneo-quick-icon"><?= $dashboardQuickAction['icon'] ?></span>
                            <div>
                                <strong><?= e((string) ($dashboardQuickAction['title'] ?? '')) ?></strong>
                                <small><?= e((string) ($dashboardQuickAction['subtitle'] ?? '')) ?></small>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </section>
            <?php endif; ?>

            <section class="dashneo-main-grid">
                <article class="dashneo-panel dashneo-trend-panel">
                    <div class="dashneo-panel-head">
                        <h2><?= e($dashboardTrendTitle) ?></h2>
                        <div class="dashneo-chart-filters dashneo-chart-filters-live" aria-label="<?= e(localized_text_value('ช่วงเวลา', 'Time range')) ?>">
                            <?php foreach ($dashboardTrendFilters as $dashboardTrendFilter): ?>
                                <?php
                                $trendFilterRange = (string) ($dashboardTrendFilter['range'] ?? '7d');
                                $trendFilterHref = 'dashboard.php?range=' . urlencode($trendFilterRange);
                                ?>
                                <a class="<?= $dashboardRange === $trendFilterRange ? 'is-active' : '' ?>" href="<?= e($trendFilterHref) ?>">
                                    <?= e((string) ($dashboardTrendFilter['label'] ?? '')) ?>
                                </a>
                            <?php endforeach; ?>
                        </div>
                        <div class="dashneo-chart-filters" aria-label="<?= e(localized_text_value('ช่วงเวลา', 'Time range')) ?>">
                            <span><?= e(localized_text_value('วันนี้', 'Today')) ?></span>
                            <span><?= e(localized_text_value('เมื่อวาน', 'Yesterday')) ?></span>
                            <span class="is-active"><?= e(localized_text_value('7 วัน', '7 days')) ?></span>
                            <span><?= e(localized_text_value('เดือนนี้', 'This month')) ?></span>
                        </div>
                    </div>
                    <div class="dashneo-line-wrap">
                        <span class="dashneo-y-label"><?= e($dashboardLineYAxisLabel) ?></span>
                        <div class="dashneo-y-ticks" aria-hidden="true">
                            <?php for ($gridIndex = 0; $gridIndex <= 4; $gridIndex++): ?>
                                <?php
                                $gridY = $trendPaddingTop + (($trendPlotHeight / 4) * $gridIndex);
                                $tickValue = $trendMaxValue - (($trendMaxValue / 4) * $gridIndex);
                                ?>
                                <span style="top: <?= e((string) round($gridY, 2)) ?>px;"><?= e(dashboard_compact_amount((float) $tickValue)) ?></span>
                            <?php endfor; ?>
                        </div>
                        <svg viewBox="0 0 <?= e((string) $trendChartWidth) ?> <?= e((string) $trendChartHeight) ?>" aria-hidden="true">
                            <?php for ($gridIndex = 0; $gridIndex <= 4; $gridIndex++): ?>
                                <?php $gridY = $trendPaddingTop + (($trendPlotHeight / 4) * $gridIndex); ?>
                                <line x1="<?= e((string) $trendPaddingX) ?>" y1="<?= e((string) round($gridY, 2)) ?>" x2="<?= e((string) ($trendChartWidth - $trendPaddingX)) ?>" y2="<?= e((string) round($gridY, 2)) ?>"></line>
                            <?php endfor; ?>
                            <?php if ($trendAreaPath !== ''): ?>
                                <path class="dashneo-area-path" d="<?= e($trendAreaPath) ?>"></path>
                                <path class="dashneo-line-glow" d="<?= e($trendSmoothPath !== '' ? $trendSmoothPath : $trendLinePath) ?>"></path>
                                <path class="dashneo-line-path" d="<?= e($trendSmoothPath !== '' ? $trendSmoothPath : $trendLinePath) ?>"></path>
                                <?php foreach ($trendPoints as $trendPoint): ?>
                                    <circle cx="<?= e((string) ($trendPoint['x'] ?? 0)) ?>" cy="<?= e((string) ($trendPoint['y'] ?? 0)) ?>" r="4.5"></circle>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </svg>
                        <?php if (!empty($trendPoints)): ?>
                            <?php
                            $lastTrendPoint = $trendPoints[count($trendPoints) - 1];
                            $lastTrendLeft = (float) (($lastTrendPoint['x'] ?? 0) - $trendPaddingX) / max(1, $trendPlotWidth) * 100;
                            $lastTrendTop = max(10, min($trendChartHeight - 70, (float) ($lastTrendPoint['y'] ?? 0) - 14));
                            ?>
                            <div class="dashneo-chart-tip" style="left: calc(<?= e(number_format($lastTrendLeft, 2, '.', '')) ?>% - 56px); top: <?= e((string) round($lastTrendTop, 2)) ?>px;">
                                <strong><?= e((string) ($lastTrendPoint['label'] ?? '')) ?></strong>
                                <span><?= format_money((float) ($lastTrendPoint['value'] ?? 0)) ?></span>
                            </div>
                        <?php endif; ?>
                        <div class="dashneo-line-labels">
                            <?php foreach ($trendPoints as $trendPoint): ?>
                                <span><?= e((string) ($trendPoint['label'] ?? '')) ?></span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </article>

                <aside class="dashneo-side-panels">
                    <article class="dashneo-panel dashneo-overview-panel">
                        <div class="dashneo-panel-head">
                            <h2><?= e($dashboardTodayOverviewLabel) ?></h2>
                            <span><?= e($monthLabel) ?></span>
                        </div>
                        <div class="dashneo-overview-grid">
                            <div class="dashneo-donut" style="--dashneo-donut: <?= e($paymentMixGradient) ?>;">
                                <div>
                                    <strong><?= format_money((float) ($paymentToday['payment_total'] ?? 0)) ?></strong>
                                    <small><?= e(localized_text_value('รับชำระรวม', 'Total paid')) ?></small>
                                </div>
                            </div>
                            <div class="dashneo-payment-list">
                                <?php foreach ($paymentLegendRows as $paymentLegendRow): ?>
                                    <a class="dashneo-payment-row" href="<?= e((string) ($paymentLegendRow['href'] ?? '#')) ?>">
                                        <div>
                                            <span class="dashneo-payment-dot" style="background: <?= e((string) ($paymentLegendRow['color'] ?? '#5d8dff')) ?>;"></span>
                                            <strong><?= e((string) ($paymentLegendRow['label'] ?? '')) ?></strong>
                                        </div>
                                        <span><?= (int) ($paymentLegendRow['percent'] ?? 0) ?>% | <?= format_money((float) ($paymentLegendRow['amount'] ?? 0)) ?></span>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </article>

                </aside>
            </section>

            <section class="dashneo-lower-grid">
                <div class="dashneo-lower-left">
                <article class="dashneo-panel dashneo-queue-panel">
                    <div class="dashneo-panel-head">
                        <h2><?= e($dashboardQueueNowLabel) ?></h2>
                        <?php if ($canOpenQueueDetails): ?>
                            <a href="<?= e($dashboardWaitingQueueUrl) ?>"><?= e($dashboardOpenQueueLabel) ?></a>
                        <?php endif; ?>
                    </div>
                    <?php if (empty($queueBoardRows)): ?>
                        <div class="empty-state"><?= e(localized_text_value('ยังไม่มีข้อมูลคิวล่าสุด', 'No recent queue data')) ?></div>
                    <?php else: ?>
                        <div class="dashneo-queue-list">
                            <?php foreach ($queueBoardRows as $queueBoardRow): ?>
                                <a class="dashneo-queue-item" href="<?= e((string) ($queueBoardRow['href'] ?? '#')) ?>">
                                    <span class="dashneo-queue-code"><?= e((string) ($queueBoardRow['code'] ?? '-')) ?></span>
                                    <div class="dashneo-queue-meta">
                                        <strong><?= e((string) ($queueBoardRow['plate'] ?? '-')) ?></strong>
                                        <small><?= e((string) ($queueBoardRow['customer'] ?? '-')) ?></small>
                                    </div>
                                    <span class="dashneo-queue-state <?= e((string) ($queueBoardRow['status_tone'] ?? 'is-waiting')) ?>"><?= e((string) ($queueBoardRow['status_label'] ?? '-')) ?></span>
                                    <time><?= e((string) ($queueBoardRow['time'] ?? '-')) ?></time>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </article>

                <article class="dashneo-panel dashneo-service-panel">
                    <div class="dashneo-panel-head">
                        <h2><?= e($dashboardServiceStatusTodayLabel) ?></h2>
                        <?php if ($canOpenQueueDetails): ?>
                            <a href="<?= e($dashboardInProgressUrl) ?>"><?= e($dashboardOpenQueueLabel) ?></a>
                        <?php endif; ?>
                    </div>
                    <div class="dashneo-service-list">
                        <?php foreach ($serviceStatusRows as $serviceStatusRow): ?>
                            <?php
                            $serviceCount = (int) ($serviceStatusRow['count'] ?? 0);
                            $servicePercent = (int) round(($serviceCount / max(1, $serviceStatusMax)) * 100);
                            ?>
                            <a class="dashneo-service-row" href="<?= e((string) ($serviceStatusRow['href'] ?? '#')) ?>">
                                <div class="dashneo-service-row-top">
                                    <div class="dashneo-service-label">
                                        <span class="dashneo-service-icon"><?= (string) ($serviceStatusRow['icon'] ?? dashboard_icon_svg('service')) ?></span>
                                        <strong><?= e((string) ($serviceStatusRow['label'] ?? '')) ?></strong>
                                    </div>
                                    <span><?= $serviceCount ?> <?= e(localized_text_value('คัน', 'cars')) ?></span>
                                </div>
                                <div class="dashneo-service-track <?= e((string) ($serviceStatusRow['tone'] ?? '')) ?>" aria-hidden="true">
                                    <span style="width: <?= e((string) $servicePercent) ?>%;"></span>
                                </div>
                            </a>
                        <?php endforeach; ?>
                        <div class="dashneo-service-total">
                            <strong><?= e($dashboardTotalJobsLabel) ?></strong>
                            <span><?= (int) $dashboardQueueTotal ?> <?= e($dashboardCountSuffixLabel) ?></span>
                        </div>
                    </div>
                </article>
                </div>

                <aside class="dashneo-lower-side">
                    <a class="dashneo-panel dashneo-goal-panel" href="<?= e($dashboardTodayRevenueUrl !== '' ? $dashboardTodayRevenueUrl : '#') ?>">
                        <div class="dashneo-panel-head">
                            <h2><?= e($dashboardRevenueGoalLabel) ?></h2>
                            <span><?= $dashboardGoalProgress ?>%</span>
                        </div>
                        <div class="dashneo-goal-amount">
                            <strong><?= format_money($dashboardTodayRevenueAmount) ?></strong>
                            <span>/ <?= format_money($dashboardGoalTarget) ?></span>
                        </div>
                        <div class="dashneo-goal-track" aria-hidden="true">
                            <span style="width: <?= e((string) $dashboardGoalProgress) ?>%;"></span>
                        </div>
                    </a>

                    <article class="dashneo-panel dashneo-alert-panel">
                        <div class="dashneo-panel-head">
                            <h2><?= e($dashboardAlertsLabel) ?></h2>
                        </div>
                        <div class="dashneo-alert-list">
                            <?php foreach ($dashboardAlerts as $dashboardAlert): ?>
                                <a class="dashneo-alert-row" href="<?= e((string) ($dashboardAlert['href'] ?? '#')) ?>">
                                    <strong><?= e((string) ($dashboardAlert['label'] ?? '')) ?></strong>
                                    <span><?= (int) ($dashboardAlert['count'] ?? 0) ?> <?= e($dashboardCountSuffixLabel) ?></span>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </article>
                </aside>
            </section>

        </section>
    </div>
</section>

<?php render_page_end(); ?>
