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

$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
    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
    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();

$recentRows = array();
$recentTypes = '';
$recentParams = array();
$recentWhere = array('1 = 1');
$branchCondition = auth_branch_condition($conn, 'o', $recentTypes, $recentParams);
if ($branchCondition !== '') {
    $recentWhere[] = $branchCondition;
}
$recentStmt = db_prepare($conn, "
    SELECT
        o.order_id,
        o.bill_number,
        o.branch_name,
        o.order_source,
        o.order_date,
        o.status,
        o.payment_status,
        o.total_price,
        c.name AS customer_name,
        car.plate_number
    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 ', $recentWhere) . "
    ORDER BY o.order_date DESC, o.order_id DESC
    LIMIT 10
");
if ($recentTypes !== '') {
    $recentStmt->bind_param($recentTypes, ...$recentParams);
}
$recentStmt->execute();
$recentResult = $recentStmt->get_result();
if ($recentResult instanceof mysqli_result) {
    while ($row = $recentResult->fetch_assoc()) {
        $recentRows[] = $row;
    }
}
$recentStmt->close();

$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);
$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'),
);

$canOpenBooking = can_access($conn, 'booking');
$canOpenManageSystem = can_access_manage_system($conn);

$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_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');

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_report_group('dashboard') ?>
        </nav>

        <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">
    <section class="dashboard-hero-panel">
        <div class="dashboard-hero-copy">
            <span class="dashboard-eyebrow"><?= e($pageTitle) ?></span>
            <span class="dashboard-month-chip"><?= e($monthLabel) ?></span>
            <h1><?= e($dashboardHeadline) ?></h1>
            <p><?= e($dashboardDescription) ?></p>
        </div>
        <div class="dashboard-hero-actions">
            <?php if ($canOpenQueueDetails): ?>
                <a class="button button-secondary" href="queue.php"><?= e($openQueueLabel) ?></a>
            <?php endif; ?>
            <?php if ($canOpenQuickService): ?>
                <a class="button button-secondary" href="quick_service.php"><?= e($quickServiceLabel) ?></a>
            <?php endif; ?>
            <?php if ($canOpenBooking): ?>
                <a class="button button-accent" href="booking.php"><?= e($newBookingLabel) ?></a>
            <?php endif; ?>
        </div>
        <?php if (!empty($topBranchRows)): ?>
            <div class="dashboard-hero-branches">
                <?php foreach ($topBranchRows as $row): ?>
                    <span class="dashboard-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; ?>
            </div>
        <?php endif; ?>
    </section>

    <section class="dashboard-kpi-grid">
        <article class="dashboard-kpi-card is-emerald">
            <span class="dashboard-kpi-label"><?= e($totalBillsTodayLabel) ?></span>
            <div class="dashboard-kpi-main">
                <strong><?= (int) ($todaySummary['total_bills'] ?? 0) ?></strong>
                <span><?= e(strtr($completionLabel, array('{percent}' => (string) $todayCompletionRate))) ?></span>
            </div>
            <p class="dashboard-kpi-helper"><?= e(strtr($averageBillLabel, array('{amount}' => format_money($todayAverageBill)))) ?></p>
        </article>
        <article class="dashboard-kpi-card is-blue">
            <span class="dashboard-kpi-label"><?= e($bookingTodayLabel) ?></span>
            <div class="dashboard-kpi-main">
                <strong><?= (int) ($todaySummary['booking_bills'] ?? 0) ?></strong>
                <span><?= e(strtr($waitingCountLabel, array('{count}' => (string) (int) ($todaySummary['waiting_total'] ?? 0)))) ?></span>
            </div>
            <p class="dashboard-kpi-helper"><?= e(strtr($depositAdminLabel, array('{amount}' => format_money((float) ($todaySummary['deposit_admin_total'] ?? 0))))) ?></p>
        </article>
        <article class="dashboard-kpi-card is-slate">
            <span class="dashboard-kpi-label"><?= e($quickServiceTodayLabel) ?></span>
            <div class="dashboard-kpi-main">
                <strong><?= (int) ($todaySummary['quick_service_bills'] ?? 0) ?></strong>
                <span><?= e(strtr($paidRowsLabel, array('{count}' => (string) (int) ($paymentToday['payment_rows'] ?? 0)))) ?></span>
            </div>
            <p class="dashboard-kpi-helper"><?= e(strtr($depositBranchLabel, array('{amount}' => format_money((float) ($todaySummary['deposit_branch_total'] ?? 0))))) ?></p>
        </article>
        <article class="dashboard-kpi-card is-green">
            <span class="dashboard-kpi-label"><?= e($paymentsTodayLabel) ?></span>
            <div class="dashboard-kpi-main">
                <strong><?= format_money((float) ($paymentToday['payment_total'] ?? 0)) ?></strong>
                <span><?= e(strtr($needPaymentCountLabel, array('{count}' => (string) $todayNeedsPayment))) ?></span>
            </div>
            <p class="dashboard-kpi-helper"><?= e(strtr($openedTodayLabel, array('{amount}' => format_money((float) ($todaySummary['opened_total'] ?? 0))))) ?></p>
        </article>
    </section>

    <section class="dashboard-status-grid">
        <article class="dashboard-status-card">
            <span class="dashboard-status-icon is-waiting"><?= dashboard_icon_svg('waiting') ?></span>
            <div class="dashboard-status-copy">
                <span class="dashboard-status-label"><?= e($waitingStatusLabel) ?></span>
                <strong><?= (int) ($todaySummary['waiting_total'] ?? 0) ?></strong>
                <small><?= e($readyToStartLabel) ?></small>
            </div>
        </article>
        <article class="dashboard-status-card">
            <span class="dashboard-status-icon is-service"><?= dashboard_icon_svg('service') ?></span>
            <div class="dashboard-status-copy">
                <span class="dashboard-status-label"><?= e($inServiceLabel) ?></span>
                <strong><?= (int) ($todaySummary['washing_total'] ?? 0) ?></strong>
                <small><?= e($carsInProgressLabel) ?></small>
            </div>
        </article>
        <article class="dashboard-status-card">
            <span class="dashboard-status-icon is-done"><?= dashboard_icon_svg('done') ?></span>
            <div class="dashboard-status-copy">
                <span class="dashboard-status-label"><?= e($doneTodayLabel) ?></span>
                <strong><?= (int) ($todaySummary['done_total'] ?? 0) ?></strong>
                <small><?= e($completedJobsLabel) ?></small>
            </div>
        </article>
        <article class="dashboard-status-card">
            <span class="dashboard-status-icon is-payment"><?= dashboard_icon_svg('payment') ?></span>
            <div class="dashboard-status-copy">
                <span class="dashboard-status-label"><?= e($needPaymentLabel) ?></span>
                <strong><?= $todayNeedsPayment ?></strong>
                <small><?= e($unpaidAndPartialLabel) ?></small>
            </div>
        </article>
    </section>

    <section class="dashboard-main-grid">
        <div class="dashboard-main-column">
            <article class="card dashboard-focus-card">
                <div class="section-head">
                    <div>
                        <h2 class="section-title"><?= e($todayBusinessTotalsTitle) ?></h2>
                        <p class="helper"><?= e($todayAllOrderSourcesLabel) ?></p>
                    </div>
                </div>
                <div class="dashboard-summary-grid">
                    <div class="dashboard-summary-item">
                        <span><?= e(trim(str_replace('{amount}', '', $openedTodayLabel))) ?></span>
                        <strong><?= format_money((float) ($todaySummary['opened_total'] ?? 0)) ?></strong>
                    </div>
                    <div class="dashboard-summary-item">
                        <span><?= e(str_replace('{amount}', '', $depositAdminLabel)) ?></span>
                        <strong><?= format_money((float) ($todaySummary['deposit_admin_total'] ?? 0)) ?></strong>
                    </div>
                    <div class="dashboard-summary-item">
                        <span><?= e(str_replace('{amount}', '', $depositBranchLabel)) ?></span>
                        <strong><?= format_money((float) ($todaySummary['deposit_branch_total'] ?? 0)) ?></strong>
                    </div>
                    <div class="dashboard-summary-item is-danger">
                        <span><?= e($outstandingLabel) ?></span>
                        <strong><?= format_money($revenueOutstandingTotal) ?></strong>
                    </div>
                </div>
                <div class="dashboard-progress-card">
                    <div class="dashboard-progress-head">
                        <strong><?= e($openedRevenueVsPaidLabel) ?></strong>
                        <span><?= e($monthLabel) ?></span>
                    </div>
                    <div class="dashboard-progress-track" aria-hidden="true">
                        <span style="width: <?= e((string) max(0, min(100, $monthlyCollectedPercent))) ?>%;"></span>
                    </div>
                    <div class="dashboard-progress-foot">
                        <span><?= e(strtr($collectedLabel, array('{percent}' => (string) $monthlyCollectedPercent, '{amount}' => format_money($branchRevenuePaidTotal)))) ?></span>
                        <span><?= e(strtr($openedLabel, array('{amount}' => format_money($branchRevenueTotal)))) ?></span>
                    </div>
                </div>
            </article>

            <section class="table-card dashboard-table-section">
                <div class="section-head dashboard-table-section-head">
                    <div>
                        <h2 class="section-title"><?= e($recentOrdersTitle) ?></h2>
                        <p class="helper"><?= e($recentOrdersHelper) ?></p>
                    </div>
                </div>
                <?php if (empty($recentRows)): ?>
                    <div class="empty-state dashboard-table-empty"><?= e($noRecentOrdersLabel) ?></div>
                <?php else: ?>
                    <table class="dashboard-table">
                        <thead>
                        <tr>
                            <th><?= e($dateLabel) ?></th>
                            <th><?= e($billNumberLabel) ?></th>
                            <th><?= e($customerLabel) ?></th>
                            <th><?= e($branchLabel) ?></th>
                            <th><?= e($sourceLabel) ?></th>
                            <th><?= e($statusLabel) ?></th>
                            <th><?= e($paymentLabel) ?></th>
                            <th><?= e($totalPriceLabel) ?></th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($recentRows as $row): ?>
                            <?php
                            $billLabel = dashboard_order_bill_label($row);
                            $sourceLabel = dashboard_order_source_label((string) ($row['order_source'] ?? ''));
                            $billHref = dashboard_order_href($conn, $row);
                            ?>
                            <tr>
                                <td><?= e(format_datetime((string) ($row['order_date'] ?? ''))) ?></td>
                                <td>
                                    <?php if ($billHref !== ''): ?>
                                        <a class="bill-link" href="<?= e($billHref) ?>"><?= e($billLabel) ?></a>
                                    <?php else: ?>
                                        <?= e($billLabel) ?>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong><?= e((string) ($row['customer_name'] ?? '')) ?></strong>
                                    <span class="muted" style="display:block;"><?= e((string) ($row['plate_number'] ?? '')) ?></span>
                                </td>
                                <td><?= e(dashboard_branch_label((string) ($row['branch_name'] ?? ''))) ?></td>
                                <td><?= e($sourceLabel) ?></td>
                                <td><span class="<?= e(status_class((string) ($row['status'] ?? ''))) ?>"><?= e(status_label((string) ($row['status'] ?? ''))) ?></span></td>
                                <td><span class="<?= e(payment_status_class((string) ($row['payment_status'] ?? ''))) ?>"><?= e(payment_status_label((string) ($row['payment_status'] ?? ''))) ?></span></td>
                                <td><?= format_money((float) ($row['total_price'] ?? 0)) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </section>
        </div>

        <aside class="dashboard-side-column">
            <article class="card dashboard-payment-mix-card">
                <div class="section-head">
                    <div>
                        <h2 class="section-title"><?= e($paymentMixTodayTitle) ?></h2>
                        <p class="helper"><?= e($recognizedPaymentsTodayLabel) ?></p>
                    </div>
                </div>
                <div class="dashboard-payment-mix-list">
                    <?php foreach ($paymentMixRows as $paymentMixRow): ?>
                        <?php
                        $paymentLabel = dashboard_payment_method_label((string) $paymentMixRow[0]);
                        $paymentAmount = (float) $paymentMixRow[1];
                        $paymentClass = (string) $paymentMixRow[2];
                        $paymentIcon = (string) ($paymentMixRow[3] ?? 'cash');
                        $paymentPercent = (float) ($paymentToday['payment_total'] ?? 0) > 0
                            ? ($paymentAmount / (float) $paymentToday['payment_total']) * 100
                            : 0;
                        ?>
                        <div class="dashboard-payment-mix-row">
                            <div class="dashboard-payment-mix-top">
                                <span class="dashboard-payment-icon <?= e($paymentClass) ?>"><?= dashboard_icon_svg($paymentIcon) ?></span>
                                <div class="dashboard-payment-mix-meta">
                                    <strong><?= e($paymentLabel) ?></strong>
                                    <span><?= format_money($paymentAmount) ?></span>
                                </div>
                            </div>
                            <div class="dashboard-payment-mix-track <?= e($paymentClass) ?>" aria-hidden="true">
                                <span style="width: <?= e(number_format(max(0, min(100, $paymentPercent)), 2, '.', '')) ?>%;"></span>
                            </div>
                            <small><?= (int) round($paymentPercent) ?>%</small>
                        </div>
                    <?php endforeach; ?>
                </div>
            </article>

            <article class="card dashboard-branch-list-card">
                <div class="section-head">
                    <div>
                        <h2 class="section-title"><?= e($todayBranchSnapshotTitle) ?></h2>
                        <p class="helper"><?= e($todayBranchSnapshotHelper) ?></p>
                    </div>
                </div>
                <?php if (empty($branchTodayRows)): ?>
                    <div class="empty-state"><?= e($noBranchActivityTodayLabel) ?></div>
                <?php else: ?>
                    <div class="dashboard-branch-list">
                        <?php foreach ($branchTodayRows as $row): ?>
                            <div class="dashboard-branch-list-item">
                                <div>
                                    <strong><?= e(dashboard_branch_label((string) ($row['branch_name'] ?? 'No branch'))) ?></strong>
                                    <span><?= e(strtr($branchWaitingSummaryLabel, array('{count}' => (string) (int) ($row['total_bills'] ?? 0), '{waiting}' => (string) (int) ($row['waiting_total'] ?? 0)))) ?></span>
                                </div>
                                <strong><?= format_money((float) ($row['paid_today'] ?? 0)) ?></strong>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </article>

            <article class="card dashboard-branch-list-card">
                <div class="section-head">
                    <div>
                        <h2 class="section-title"><?= e($branchRevenueTitle) ?></h2>
                        <p class="helper"><?= e(strtr($branchRevenueHelper, array('{month}' => $monthLabel))) ?></p>
                    </div>
                </div>
                <?php if (empty($branchRevenueRows)): ?>
                    <div class="empty-state"><?= e($noBranchRevenueLabel) ?></div>
                <?php else: ?>
                    <div class="dashboard-branch-revenue-list">
                        <?php foreach ($branchRevenueRows as $row): ?>
                            <?php
                            $branchRevenue = (float) ($row['revenue'] ?? 0);
                                $barPercent = $branchRevenueMax > 0 ? max(3, ($branchRevenue / $branchRevenueMax) * 100) : 0;
                            ?>
                            <div class="dashboard-branch-revenue-item">
                                <div class="dashboard-branch-revenue-meta">
                                    <strong><?= e(dashboard_branch_label((string) ($row['branch_name'] ?? 'No branch'))) ?></strong>
                                    <span><?= e(strtr($branchBillCountLabel, array('{count}' => (string) (int) ($row['bill_count'] ?? 0)))) ?></span>
                                </div>
                                <div class="dashboard-branch-revenue-bar" aria-hidden="true">
                                    <span style="width: <?= e(number_format($barPercent, 2, '.', '')) ?>%;"></span>
                                </div>
                                <strong><?= format_money($branchRevenue) ?></strong>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </article>
        </aside>
    </section>

    <section class="dashboard-detail-grid">
        <section class="table-card dashboard-table-section">
            <div class="section-head dashboard-table-section-head">
                <div>
                    <h2 class="section-title"><?= e($pickupDueTitle) ?></h2>
                    <p class="helper"><?= e($pickupDueHelper) ?></p>
                </div>
            </div>
            <?php if (empty($pickupRows)): ?>
                <div class="empty-state dashboard-table-empty"><?= e($noPickupDueLabel) ?></div>
            <?php else: ?>
                <table class="dashboard-table">
                    <thead>
                    <tr>
                        <th><?= e($billNumberLabel) ?></th>
                        <th><?= e($customerLabel) ?></th>
                        <th><?= e($pickupDueLabel) ?></th>
                        <th><?= e($statusLabel) ?></th>
                        <th><?= e($paymentLabel) ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($pickupRows as $row): ?>
                        <?php $billLabel = dashboard_order_bill_label($row); ?>
                        <tr>
                            <td>
                                <?php if ($canOpenQueueDetails): ?>
                                    <a class="bill-link" href="job_details.php?id=<?= (int) ($row['order_id'] ?? 0) ?>"><?= e($billLabel) ?></a>
                                <?php else: ?>
                                    <?= e($billLabel) ?>
                                <?php endif; ?>
                            </td>
                            <td>
                                <strong><?= e((string) ($row['customer_name'] ?? '')) ?></strong>
                                <span class="muted" style="display:block;"><?= e((string) ($row['plate_number'] ?? '')) ?></span>
                            </td>
                            <td><?= e(format_datetime((string) ($row['return_at'] ?? ''))) ?></td>
                            <td><span class="<?= e(status_class((string) ($row['status'] ?? ''))) ?>"><?= e(status_label((string) ($row['status'] ?? ''))) ?></span></td>
                            <td><span class="<?= e(payment_status_class((string) ($row['payment_status'] ?? ''))) ?>"><?= e(payment_status_label((string) ($row['payment_status'] ?? ''))) ?></span></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>

        <section class="table-card dashboard-table-section">
            <div class="section-head dashboard-table-section-head">
                <div>
                    <h2 class="section-title"><?= e($followUpPaymentTitle) ?></h2>
                    <p class="helper"><?= e($followUpPaymentHelper) ?></p>
                </div>
            </div>
            <?php if (empty($followUpRows)): ?>
                <div class="empty-state dashboard-table-empty"><?= e($noPaymentFollowUpLabel) ?></div>
            <?php else: ?>
                <table class="dashboard-table">
                    <thead>
                    <tr>
                        <th><?= e($billNumberLabel) ?></th>
                        <th><?= e($customerLabel) ?></th>
                        <th><?= e($sourceLabel) ?></th>
                        <th><?= e($balanceLabel) ?></th>
                        <th><?= e($statusLabel) ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($followUpRows as $row): ?>
                        <?php
                        $billLabel = dashboard_order_bill_label($row);
                        $balanceAmount = max(0.0, (float) ($row['total_price'] ?? 0) - (float) ($row['paid_amount'] ?? 0));
                        $sourceLabel = dashboard_order_source_label((string) ($row['order_source'] ?? ''));
                        $billHref = dashboard_order_href($conn, $row, '#payment-section');
                        ?>
                        <tr>
                            <td>
                                <?php if ($billHref !== ''): ?>
                                    <a class="bill-link" href="<?= e($billHref) ?>"><?= e($billLabel) ?></a>
                                <?php else: ?>
                                    <?= e($billLabel) ?>
                                <?php endif; ?>
                            </td>
                            <td>
                                <strong><?= e((string) ($row['customer_name'] ?? '')) ?></strong>
                                <span class="muted" style="display:block;"><?= e((string) ($row['plate_number'] ?? '')) ?></span>
                            </td>
                            <td><?= e($sourceLabel) ?></td>
                            <td><?= format_money($balanceAmount) ?></td>
                            <td><span class="<?= e(payment_status_class((string) ($row['payment_status'] ?? ''))) ?>"><?= e(payment_status_label((string) ($row['payment_status'] ?? ''))) ?></span></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>
    </section>
        </section>
    </div>
</section>

<?php render_page_end(); ?>
