<?php
declare(strict_types=1);

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

require_permission($conn, 'sale_report');

ensure_order_branch_column($conn);
ensure_order_return_column($conn);
ensure_order_deposit_method_column($conn);
ensure_order_split_deposit_columns($conn);
ensure_order_bill_number_column($conn);
ensure_order_source_column($conn);
ensure_order_reopen_column($conn);

function sale_report_month(string $value, string $default): string
{
    if (!preg_match('/^\d{4}-\d{2}$/', $value)) {
        return $default;
    }

    $timestamp = strtotime($value . '-01');

    if ($timestamp === false) {
        return $default;
    }

    return date('Y-m', $timestamp);
}

function sale_report_date_value(string $value, string $default): string
{
    $timestamp = strtotime($value);

    if ($timestamp === false) {
        return $default;
    }

    return date('Y-m-d', $timestamp);
}

function sale_report_year(string $value, string $default): string
{
    if (!preg_match('/^\d{4}$/', $value)) {
        return $default;
    }

    $year = (int) $value;

    if ($year < 2000 || $year > 2100) {
        return $default;
    }

    return (string) $year;
}

function sale_report_money($value): string
{
    return number_format((float) $value, 2);
}

function sale_report_order_source_label(string $orderSource): string
{
    return $orderSource === 'quick_service'
        ? ui_text('ควิกเซอร์วิส', 'Quick Service')
        : ui_text('เปิดบิล', 'Booking');
}

function sale_report_time(?string $value): string
{
    return format_datetime($value);
}

function sale_report_date(string $value): string
{
    $timestamp = strtotime($value);

    if ($timestamp === false) {
        return '-';
    }

    return date('d/m/Y', $timestamp);
}

function sale_report_display_order_source_label(string $orderSource): string
{
    return $orderSource === 'quick_service'
        ? ui_text('ควิกเซอร์วิส', 'Quick Service')
        : ui_text('เปิดบิล', 'Booking');
}

function sale_report_normalize_payment_status(array $row): string
{
    $status = trim((string) ($row['payment_status'] ?? ''));
    if (!in_array($status, array('unpaid', 'partial', 'paid'), true)) {
        $status = 'unpaid';
    }

    $saleAmount = (float) ($row['sale_amount'] ?? $row['total_price'] ?? 0);
    $paidAmount = (float) ($row['paid_amount'] ?? 0);
    $adminDepositAmount = (float) ($row['admin_deposit_total'] ?? 0);
    $branchDepositAmount = (float) ($row['branch_deposit_total'] ?? 0);
    $receivedAmount = $paidAmount + $adminDepositAmount + $branchDepositAmount;
    $outstandingAmount = max(0.0, $saleAmount - $receivedAmount);
    $epsilon = 0.009;

    if ($saleAmount <= $epsilon || $outstandingAmount <= $epsilon) {
        return 'paid';
    }

    if ($receivedAmount > $epsilon) {
        return 'partial';
    }

    return $status === 'paid' ? 'unpaid' : $status;
}

function sale_report_add_totals(array &$totals, array $row): void
{
    $fields = array(
        'sale_amount',
        'paid_amount',
        'cash_amount',
        'transfer_amount',
        'card_amount',
        'unknown_amount',
        'admin_deposit_cash',
        'admin_deposit_transfer',
        'admin_deposit_card',
        'branch_deposit_cash',
        'branch_deposit_transfer',
        'branch_deposit_card',
        'previous_deposit_amount',
        'advance_deposit_amount',
        'outstanding_amount',
    );

    foreach ($fields as $field) {
        $totals[$field] = (float) ($totals[$field] ?? 0) + (float) ($row[$field] ?? 0);
    }
}

function sale_report_empty_totals(): array
{
    return array(
        'sale_amount' => 0.0,
        'paid_amount' => 0.0,
        'cash_amount' => 0.0,
        'transfer_amount' => 0.0,
        'card_amount' => 0.0,
        'unknown_amount' => 0.0,
        'admin_deposit_cash' => 0.0,
        'admin_deposit_transfer' => 0.0,
        'admin_deposit_card' => 0.0,
        'branch_deposit_cash' => 0.0,
        'branch_deposit_transfer' => 0.0,
        'branch_deposit_card' => 0.0,
        'previous_deposit_amount' => 0.0,
        'advance_deposit_amount' => 0.0,
        'outstanding_amount' => 0.0,
    );
}

$period = (string) ($_GET['period'] ?? 'monthly');
$allowedPeriods = array('daily', 'monthly', 'yearly');
if (!in_array($period, $allowedPeriods, true)) {
    $period = 'monthly';
}

$today = date('Y-m-d');
$currentMonth = date('Y-m');
$currentYear = date('Y');
$shouldLoadReport = isset($_GET['load']) && (string) $_GET['load'] === '1';
$dateValue = sale_report_date_value((string) ($_GET['date'] ?? $today), $today);
$monthValue = sale_report_month((string) ($_GET['month'] ?? $currentMonth), $currentMonth);
$yearValue = sale_report_year((string) ($_GET['year'] ?? $currentYear), $currentYear);
$paymentStatusFilter = trim((string) ($_GET['payment_status'] ?? ''));
$allowedPaymentStatusFilters = array('', 'unpaid', 'partial', 'paid');
if (!in_array($paymentStatusFilter, $allowedPaymentStatusFilters, true)) {
    $paymentStatusFilter = '';
}
$orderSourceFilter = trim((string) ($_GET['order_source'] ?? ''));
$allowedOrderSourceFilters = array('', 'booking', 'quick_service');
if (!in_array($orderSourceFilter, $allowedOrderSourceFilters, true)) {
    $orderSourceFilter = '';
}

if ($period === 'daily') {
    $startAt = $dateValue . ' 00:00:00';
    $endAt = date('Y-m-d 00:00:00', strtotime($startAt . ' +1 day'));
    $periodLabel = date('d/m/Y', strtotime($startAt));
    $totalLabel = ui_text('รวมรายวัน', 'Daily total');
} elseif ($period === 'yearly') {
    $startAt = $yearValue . '-01-01 00:00:00';
    $endAt = ((int) $yearValue + 1) . '-01-01 00:00:00';
    $periodLabel = $yearValue;
    $totalLabel = ui_text('รวมรายปี', 'Yearly total');
} else {
    $startAt = date('Y-m-01 00:00:00', strtotime($monthValue . '-01'));
    $endAt = date('Y-m-d 00:00:00', strtotime($startAt . ' +1 month'));
    $periodLabel = localized_year_month_label($startAt);
    $totalLabel = ui_text('รวมรายเดือน', 'Monthly total');
}

$branchNames = authorized_order_branch_options($conn);

$branchFilter = trim((string) ($_GET['branch_name'] ?? ''));
if ($branchFilter !== '' && !in_array($branchFilter, $branchNames, true)) {
    $branchFilter = '';
}

$where = array(
    'o.order_date >= ?',
    'o.order_date < ?',
);
$types = 'ss';
$params = array($startAt, $endAt);

$branchAccessCondition = auth_branch_condition($conn, 'o', $types, $params);
if ($branchAccessCondition !== '') {
    $where[] = $branchAccessCondition;
}

if ($branchFilter !== '') {
    $where[] = 'o.branch_name = ?';
    $types .= 's';
    $params[] = $branchFilter;
}

if ($orderSourceFilter !== '') {
    $where[] = 'o.order_source = ?';
    $types .= 's';
    $params[] = $orderSourceFilter;
}

$whereSql = implode(' AND ', $where);
$rows = array();
if ($shouldLoadReport) {
    $baseRows = array();
    $stmt = db_prepare($conn, "
        SELECT
            o.order_id,
            o.bill_number,
            o.order_date,
            o.order_source,
            o.return_at,
            o.branch_name,
            o.status,
            o.payment_status,
            o.total_price,
            o.deposit_amount,
            o.deposit_method,
            o.admin_deposit_amount,
            o.admin_deposit_method,
            o.branch_deposit_amount,
            o.branch_deposit_method,
            o.reopened_from_order_id,
            reopened.bill_number AS reopened_from_bill_number,
            o.notes,
            c.name AS customer_name,
            car.plate_number,
            car.brand,
            car.model
        FROM orders o FORCE INDEX (idx_orders_report_period)
        STRAIGHT_JOIN customers c ON c.customer_id = o.customer_id
        STRAIGHT_JOIN cars car ON car.car_id = o.car_id
        LEFT JOIN orders reopened ON reopened.order_id = o.reopened_from_order_id
        WHERE {$whereSql}
        ORDER BY o.order_date ASC, o.order_id ASC
    ");
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $baseRows[] = $row;
    }

    $stmt->close();

    $orderIds = array_column($baseRows, 'order_id');
    $serviceSummaryMap = order_service_summary_map($conn, $orderIds);
    $paymentSummaryMap = order_payment_summary_map($conn, $orderIds);

    foreach ($baseRows as $row) {
        $orderId = (int) ($row['order_id'] ?? 0);
        $serviceSummary = $serviceSummaryMap[$orderId] ?? array();
        $paymentSummary = $paymentSummaryMap[$orderId] ?? order_payment_summary_defaults();

        $row['service_names'] = (string) ($serviceSummary['service_names'] ?? '');
        $row['paid_amount'] = (float) ($paymentSummary['paid_amount'] ?? 0);
        $row['cash_amount'] = (float) ($paymentSummary['cash_amount'] ?? 0);
        $row['transfer_amount'] = (float) ($paymentSummary['transfer_amount'] ?? 0);
        $row['card_amount'] = (float) ($paymentSummary['card_amount'] ?? 0);
        $row['unknown_amount'] = (float) ($paymentSummary['unknown_amount'] ?? 0);
        $row['admin_deposit_count'] = (int) ($paymentSummary['admin_deposit_count'] ?? 0);
        $row['admin_deposit_amount_paid'] = (float) ($paymentSummary['admin_deposit_amount'] ?? 0);
        $row['paid_admin_deposit_method'] = (string) ($paymentSummary['admin_deposit_method'] ?? '');
        $row['admin_deposit_date'] = $paymentSummary['admin_deposit_date'] ?? null;
        $row['branch_deposit_count'] = (int) ($paymentSummary['branch_deposit_count'] ?? 0);
        $row['branch_deposit_amount_paid'] = (float) ($paymentSummary['branch_deposit_amount'] ?? 0);
        $row['paid_branch_deposit_method'] = (string) ($paymentSummary['branch_deposit_method'] ?? '');
        $row['branch_deposit_date'] = $paymentSummary['branch_deposit_date'] ?? null;

        $isCancelled = (string) ($row['status'] ?? '') === 'cancelled';
        $saleAmount = (float) $row['total_price'];
        $paidAmount = (float) $row['paid_amount'];
        $hasAdminDepositPayment = (int) ($row['admin_deposit_count'] ?? 0) > 0;
        $hasBranchDepositPayment = (int) ($row['branch_deposit_count'] ?? 0) > 0;
        $adminDepositAmount = $hasAdminDepositPayment
            ? (float) ($row['admin_deposit_amount_paid'] ?? 0)
            : (float) ($row['admin_deposit_amount'] ?? 0);
        $adminDepositMethod = $hasAdminDepositPayment
            ? (string) ($row['paid_admin_deposit_method'] ?? '')
            : (string) ($row['admin_deposit_method'] ?? '');
        $adminDepositDate = $hasAdminDepositPayment
            ? (string) ($row['admin_deposit_date'] ?? '')
            : (string) ($row['order_date'] ?? '');
        $branchDepositAmount = $hasBranchDepositPayment
            ? (float) ($row['branch_deposit_amount_paid'] ?? 0)
            : (float) ($row['branch_deposit_amount'] ?? 0);
        $branchDepositMethod = $hasBranchDepositPayment
            ? (string) ($row['paid_branch_deposit_method'] ?? '')
            : (string) ($row['branch_deposit_method'] ?? '');
        $branchDepositDate = $hasBranchDepositPayment
            ? (string) ($row['branch_deposit_date'] ?? '')
            : (string) ($row['order_date'] ?? '');
        $depositAmount = $adminDepositAmount + $branchDepositAmount;
        $pickupDueAt = (string) ($row['return_at'] ?? '');
        $depositDateCandidates = array();

        if ($adminDepositAmount > 0.0 && $adminDepositDate !== '' && strtotime($adminDepositDate) !== false) {
            $depositDateCandidates[] = $adminDepositDate;
        }

        if ($branchDepositAmount > 0.0 && $branchDepositDate !== '' && strtotime($branchDepositDate) !== false) {
            $depositDateCandidates[] = $branchDepositDate;
        }

        $depositDate = '';
        if (!empty($depositDateCandidates)) {
            usort($depositDateCandidates, static function (string $left, string $right): int {
                return strtotime($left) <=> strtotime($right);
            });
            $depositDate = $depositDateCandidates[0];
        }

        $row['sale_amount'] = $saleAmount;
        $row['admin_deposit_total'] = $adminDepositAmount;
        $row['branch_deposit_total'] = $branchDepositAmount;
        $row['admin_deposit_cash'] = $adminDepositMethod === 'cash' ? $adminDepositAmount : 0.0;
        $row['admin_deposit_transfer'] = in_array($adminDepositMethod, array('transfer', 'qr'), true) ? $adminDepositAmount : 0.0;
        $row['admin_deposit_card'] = $adminDepositMethod === 'card' ? $adminDepositAmount : 0.0;
        $row['branch_deposit_cash'] = $branchDepositMethod === 'cash' ? $branchDepositAmount : 0.0;
        $row['branch_deposit_transfer'] = in_array($branchDepositMethod, array('transfer', 'qr'), true) ? $branchDepositAmount : 0.0;
        $row['branch_deposit_card'] = $branchDepositMethod === 'card' ? $branchDepositAmount : 0.0;
        $row['previous_deposit_amount'] = ($depositAmount > 0 && $depositDate !== '' && strtotime($depositDate) !== false && strtotime($depositDate) < strtotime($startAt))
            ? $depositAmount
            : 0.0;
        $row['advance_deposit_amount'] = ($pickupDueAt !== '' && strtotime($pickupDueAt) !== false && strtotime($pickupDueAt) >= strtotime($endAt))
            ? $depositAmount
            : 0.0;
        $row['outstanding_amount'] = max(0.0, $saleAmount - $paidAmount - $depositAmount);
        $row['payment_status'] = sale_report_normalize_payment_status($row);
        $row['is_cancelled'] = $isCancelled;

        if ($paymentStatusFilter !== '' && (string) $row['payment_status'] !== $paymentStatusFilter) {
            continue;
        }

        $rows[] = $row;
    }
}

$rowsByDate = array();
$overallTotals = sale_report_empty_totals();

foreach ($rows as $row) {
    $dateKey = date('Y-m-d', strtotime((string) $row['order_date']));

    if (!isset($rowsByDate[$dateKey])) {
        $rowsByDate[$dateKey] = array();
    }

    $rowsByDate[$dateKey][] = $row;
    if (empty($row['is_cancelled'])) {
        sale_report_add_totals($overallTotals, $row);
    }
}

$saleReportDashboard = array(
    'visible_rows' => count($rows),
    'active_rows' => 0,
    'cancelled_rows' => 0,
    'paid_rows' => 0,
    'partial_rows' => 0,
    'unpaid_rows' => 0,
);

foreach ($rows as $row) {
    if (!empty($row['is_cancelled'])) {
        $saleReportDashboard['cancelled_rows']++;
        continue;
    }

    $saleReportDashboard['active_rows']++;
    $paymentStatus = (string) ($row['payment_status'] ?? 'unpaid');
    if (!isset($saleReportDashboard[$paymentStatus . '_rows'])) {
        $paymentStatus = 'unpaid';
    }

    $saleReportDashboard[$paymentStatus . '_rows']++;
}

$saleReportDashboard['admin_deposit_amount'] = (float) $overallTotals['admin_deposit_cash']
    + (float) $overallTotals['admin_deposit_transfer']
    + (float) $overallTotals['admin_deposit_card'];
$saleReportDashboard['branch_deposit_amount'] = (float) $overallTotals['branch_deposit_cash']
    + (float) $overallTotals['branch_deposit_transfer']
    + (float) $overallTotals['branch_deposit_card'];
$saleReportDashboard['paid_ratio'] = (int) round($saleReportDashboard['active_rows'] > 0
    ? (((int) $saleReportDashboard['paid_rows'] / (int) $saleReportDashboard['active_rows']) * 100)
    : 0);
$saleReportDashboard['partial_ratio'] = (int) round($saleReportDashboard['active_rows'] > 0
    ? (((int) $saleReportDashboard['partial_rows'] / (int) $saleReportDashboard['active_rows']) * 100)
    : 0);
$saleReportDashboard['unpaid_ratio'] = (int) round($saleReportDashboard['active_rows'] > 0
    ? (((int) $saleReportDashboard['unpaid_rows'] / (int) $saleReportDashboard['active_rows']) * 100)
    : 0);

$paymentMixRows = array(
    array(
        'label' => quick_service_payment_method_label('cash'),
        'amount' => (float) $overallTotals['cash_amount'],
        'class' => 'cash',
        'icon' => 'cash',
    ),
    array(
        'label' => ui_text('โอน / QR', 'Transfer / QR'),
        'amount' => (float) $overallTotals['transfer_amount'],
        'class' => 'transfer',
        'icon' => 'bank',
    ),
    array(
        'label' => quick_service_payment_method_label('card'),
        'amount' => (float) $overallTotals['card_amount'],
        'class' => 'card',
        'icon' => 'card',
    ),
    array(
        'label' => ui_text('ไม่ทราบ', 'Unknown'),
        'amount' => (float) $overallTotals['unknown_amount'],
        'class' => 'unknown',
        'icon' => 'wallet',
    ),
);
$paymentMixTotal = (float) $overallTotals['paid_amount'];
foreach ($paymentMixRows as &$paymentMixRow) {
    $paymentMixRow['percent'] = $paymentMixTotal > 0.0
        ? round(((float) $paymentMixRow['amount'] / $paymentMixTotal) * 100, 1)
        : 0.0;
}
unset($paymentMixRow);

$overdueDaysTotal = 0;
$overdueRowsCount = 0;
$todayMidnight = strtotime(date('Y-m-d'));
foreach ($rows as $dashboardRow) {
    if (!empty($dashboardRow['is_cancelled']) || (string) ($dashboardRow['payment_status'] ?? '') === 'paid') {
        continue;
    }

    $pickupDueTimestamp = strtotime((string) ($dashboardRow['return_at'] ?? ''));
    if ($pickupDueTimestamp === false || $pickupDueTimestamp >= $todayMidnight) {
        continue;
    }

    $overdueRowsCount++;
    $overdueDaysTotal += (int) floor(($todayMidnight - $pickupDueTimestamp) / 86400);
}

$saleReportDashboard['avg_overdue_days'] = $overdueRowsCount > 0 ? (int) round($overdueDaysTotal / $overdueRowsCount) : 0;
$saleReportDashboard['collection_health_label'] = $saleReportDashboard['paid_ratio'] >= 70
    ? ui_text('อยู่ในเกณฑ์ดี', 'Healthy')
    : ui_text('เฝ้าระวัง', 'Monitor');
$saleReportDashboard['partial_health_label'] = (int) $saleReportDashboard['partial_rows'] > 0
    ? ui_text('ต้องติดตาม', 'Action required')
    : ui_text('คงที่', 'Stable');
$saleReportDashboard['unpaid_health_label'] = (int) $saleReportDashboard['unpaid_rows'] > 0
    ? ui_text('วิกฤต', 'Critical')
    : ui_text('ปกติ', 'Clear');

$pageTitle = ui_text('รายงานการขาย', 'Sale Report');
$pageDescription = ui_text(
    'รายงานยอดขายรายวัน รายเดือน หรือรายปี ครอบคลุมยอดขาย การชำระเงิน เงินมัดจำ และยอดค้างชำระ',
    'Sales report by day, month or year in the Excel layout: sales, payments, deposits and outstanding balances.'
);
$toolbarTitle = ui_text('รายงานการขาย', 'Sales Report');
$toolbarHelperLabel = ui_text(
    'ติดตามยอดขาย การชำระเงิน เงินมัดจำ และยอดค้างชำระด้วยมุมมองรายงานที่อ่านง่ายขึ้น',
    'Track sales, payments, deposits and outstanding balances with a clearer report console.'
);
$viewByLabel = ui_text('ดูตาม', 'View by');
$dailyLabel = ui_text('รายวัน', 'Daily');
$monthlyLabel = ui_text('รายเดือน', 'Monthly');
$yearlyLabel = ui_text('รายปี', 'Yearly');
$dailyDateLabel = ui_text('วันที่รายวัน', 'Daily date');
$monthlyPeriodLabel = ui_text('รอบเดือน', 'Monthly period');
$yearlyPeriodLabel = ui_text('รอบปี', 'Yearly period');
$branchLabel = ui_text('สาขา', 'Branch');
$allBranchesLabel = ui_text('ทุกสาขา', 'All branches');
$statusLabel = ui_text('สถานะ', 'Status');
$allStatusesLabel = ui_text('ทุกสถานะ', 'All statuses');
$paidLabel = payment_status_label('paid');
$partialLabel = payment_status_label('partial');
$unpaidLabel = payment_status_label('unpaid');
$saleTypeLabel = ui_text('ประเภทการขาย', 'Sale type');
$allSaleTypesLabel = ui_text('ทุกประเภทการขาย', 'All sale types');
$currentPeriodLabel = ui_text('ช่วงเวลาปัจจุบัน', 'Current period');
$printReportLabel = ui_text('พิมพ์รายงาน', 'Print report');
$viewReportLabel = ui_text('ดูรายงาน', 'View report');
$resetLabel = ui_text('รีเซ็ต', 'Reset');
$emptyStateLabel = ui_text('กดดูรายงานเพื่อโหลดข้อมูลการขาย', 'Click View report to load sale data.');
$bookingsLabel = ui_text('บิลทั้งหมด', 'Bookings');
$activeLabel = ui_text('ใช้งานอยู่', 'active');
$cancelledLabel = ui_text('ยกเลิก', 'cancelled');
$paidBillsLabel = ui_text('บิลชำระครบ', 'Paid bills');
$partialBillsLabel = ui_text('บิลชำระบางส่วน', 'Partial bills');
$unpaidBillsLabel = ui_text('บิลค้างชำระ', 'Unpaid bills');
$saleAmountLabel = ui_text('ยอดขาย', 'Sale amount');
$paidReceivedLabel = ui_text('รับชำระแล้ว', 'Paid received');
$depositAdminLabel = ui_text('มัดจำ @Admin', 'Deposit @Admin');
$depositBranchLabel = ui_text('มัดจำ @Branch', 'Deposit @Branch');
$collectionsMixLabel = ui_text('สัดส่วนการรับชำระ', 'Collections mix');
$collectionsMixHelperLabel = ui_text('สัดส่วนยอดรับเงินจริงในช่วงรายงานนี้', 'Received payment share in this report period.');
$viewDetailsLabel = ui_text('ดูรายละเอียด', 'View details');
$outstandingBalanceLabel = ui_text('ยอดค้างชำระ', 'Outstanding balance');
$outstandingBalanceHelperLabel = ui_text('ยอดค้างรวมในขอบเขตรายงานที่เลือก', 'Current exposure across the selected report scope.');
$avgOverdueDaysLabel = ui_text('ค้างเฉลี่ย', 'Days overdue (avg)');
$dayUnitLabel = ui_text('วัน', 'day(s)');
$needFollowUpLabel = ui_text('ต้องติดตาม', 'Need follow-up');
$billUnitLabel = ui_text('บิล', 'bill(s)');
$openBillListLabel = ui_text('เปิดรายการบิล', 'Open bill list');
$reportRowsLabel = ui_text('รายการบิล', 'bill row(s)');
$dateLabel = ui_text('วันที่', 'Date');
$billNoLabel = ui_text('เลขที่บิล', 'Bill no.');
$pickupDueLabel = ui_text('กำหนดรับรถ', 'Pickup due');
$plateNumberLabel = ui_text('ทะเบียนรถ', 'Plate number');
$brandLabel = ui_text('ยี่ห้อ', 'Brand');
$modelLabel = ui_text('รุ่น', 'Model');
$serviceLabel = ui_text('บริการ', 'Service');
$paymentsLabel = ui_text('การชำระเงิน', 'Payments');
$previousMonthDepositLabel = ui_text('มัดจำจากเดือนก่อน', 'Previous month deposit');
$advanceDepositLabel = ui_text('มัดจำล่วงหน้า', 'Advance deposit');
$outstandingLabel = ui_text('ค้างชำระ', 'Outstanding');
$notesLabel = ui_text('หมายเหตุ', 'Notes');
$cashLabel = quick_service_payment_method_label('cash');
$transferLabel = quick_service_payment_method_label('transfer');
$cardLabel = quick_service_payment_method_label('card');
$unknownLabel = ui_text('ไม่ทราบ', 'Unknown');
$reopenedReferenceLabel = ui_text('อ้างอิง', 'Ref.');
$cancelledInlineLabel = ui_text('(ยกเลิก)', '(Cancelled)');
$noSalesFoundLabel = ui_text('ไม่พบข้อมูลการขายในช่วงเวลานี้', 'No sales found for this period.');
$totalSummaryLabel = ui_text('รวม', 'Total');

$selectedBranchLabel = $branchFilter !== '' ? $branchFilter : $allBranchesLabel;
$selectedPaymentStatusLabel = $paymentStatusFilter !== '' ? payment_status_label($paymentStatusFilter) : $allStatusesLabel;
$selectedOrderSourceLabel = $orderSourceFilter !== '' ? sale_report_display_order_source_label($orderSourceFilter) : $allSaleTypesLabel;

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

<style>
.sale-report-table .void-label:not(.localized-void-label) {
    display: none;
}
</style>

<section class="page-hero">
    <div>
        <h1><?= e($pageTitle) ?></h1>
        <p><?= e($pageDescription) ?></p>
    </div>
    <div class="hero-actions">
        <button class="button button-secondary" type="button" onclick="window.print()"><?= e($printReportLabel) ?></button>
    </div>
</section>

<section class="form-card sale-report-filters sale-report-toolbar-card">
    <form method="GET" action="sale_report.php" class="sale-report-toolbar-form">
        <input type="hidden" name="load" value="1">

        <div class="sale-report-toolbar-head">
            <div>
                <h2 class="section-title"><?= e($toolbarTitle) ?></h2>
                <p class="helper"><?= e($toolbarHelperLabel) ?></p>
            </div>
        </div>

        <div class="sale-report-filter-strip">
            <label class="sale-report-filter-pill" for="period">
                <span><?= e($viewByLabel) ?></span>
                <select id="period" name="period">
                    <option value="daily" <?= $period === 'daily' ? 'selected' : '' ?>><?= e($dailyLabel) ?></option>
                    <option value="monthly" <?= $period === 'monthly' ? 'selected' : '' ?>><?= e($monthlyLabel) ?></option>
                    <option value="yearly" <?= $period === 'yearly' ? 'selected' : '' ?>><?= e($yearlyLabel) ?></option>
                </select>
            </label>

            <label class="sale-report-filter-pill <?= $period === 'daily' ? 'is-active' : '' ?>" for="date">
                <span><?= e($dailyDateLabel) ?></span>
                <input id="date" name="date" type="date" value="<?= e($dateValue) ?>">
            </label>

            <label class="sale-report-filter-pill <?= $period === 'monthly' ? 'is-active' : '' ?>" for="month">
                <span><?= e($monthlyPeriodLabel) ?></span>
                <?= render_month_picker('month', 'month', $monthValue, $monthlyPeriodLabel) ?>
            </label>

            <label class="sale-report-filter-pill <?= $period === 'yearly' ? 'is-active' : '' ?>" for="year">
                <span><?= e($yearlyPeriodLabel) ?></span>
                <input id="year" name="year" type="number" min="2000" max="2100" value="<?= e($yearValue) ?>">
            </label>

            <label class="sale-report-filter-pill" for="branch_name">
                <span><?= e($branchLabel) ?></span>
                <select id="branch_name" name="branch_name">
                    <option value=""><?= e($allBranchesLabel) ?></option>
                    <?php foreach ($branchNames as $branchName): ?>
                        <option value="<?= e($branchName) ?>" <?= $branchFilter === $branchName ? 'selected' : '' ?>>
                            <?= e($branchName) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>

            <label class="sale-report-filter-pill" for="payment_status">
                <span><?= e($statusLabel) ?></span>
                <select id="payment_status" name="payment_status">
                    <option value=""><?= e($allStatusesLabel) ?></option>
                    <option value="paid" <?= $paymentStatusFilter === 'paid' ? 'selected' : '' ?>><?= e($paidLabel) ?></option>
                    <option value="partial" <?= $paymentStatusFilter === 'partial' ? 'selected' : '' ?>><?= e($partialLabel) ?></option>
                    <option value="unpaid" <?= $paymentStatusFilter === 'unpaid' ? 'selected' : '' ?>><?= e($unpaidLabel) ?></option>
                </select>
            </label>

            <label class="sale-report-filter-pill" for="order_source">
                <span><?= e($saleTypeLabel) ?></span>
                <select id="order_source" name="order_source">
                    <option value=""><?= e($allSaleTypesLabel) ?></option>
                    <option value="booking" <?= $orderSourceFilter === 'booking' ? 'selected' : '' ?>><?= e(sale_report_display_order_source_label('booking')) ?></option>
                    <option value="quick_service" <?= $orderSourceFilter === 'quick_service' ? 'selected' : '' ?>><?= e(sale_report_display_order_source_label('quick_service')) ?></option>
                </select>
            </label>
        </div>

        <div class="sale-report-current-scope">
            <span><strong><?= e($currentPeriodLabel) ?>:</strong> <?= e($periodLabel) ?></span>
            <span><strong><?= e($branchLabel) ?>:</strong> <?= e($selectedBranchLabel) ?></span>
            <span><strong><?= e($statusLabel) ?>:</strong> <?= e($selectedPaymentStatusLabel) ?></span>
            <span><strong><?= e($saleTypeLabel) ?>:</strong> <?= e($selectedOrderSourceLabel) ?></span>
        </div>

        <?php if (false): ?>
        <div class="sale-report-toolbar-actions">
            <button class="button button-secondary app-action-button" type="button" onclick="window.print()"><?= app_button_content('printer', ui_text('พิมพ์รายงาน', 'Print report')) ?></button>
            <button class="button button-accent app-action-button" type="submit"><?= app_button_content('chart', ui_text('ดูรายงาน', 'View report')) ?></button>
            <a class="button button-ghost app-action-button" href="sale_report.php"><?= app_button_content('rotate-ccw', ui_text('รีเซ็ต', 'Reset')) ?></a>
        </div>
        <?php endif; ?>
        <div class="sale-report-toolbar-actions">
            <button class="button button-secondary app-action-button" type="button" onclick="window.print()"><?= app_button_content('printer', $printReportLabel) ?></button>
            <button class="button button-accent app-action-button" type="submit"><?= app_button_content('chart', $viewReportLabel) ?></button>
            <a class="button button-ghost app-action-button" href="sale_report.php"><?= app_button_content('rotate-ccw', $resetLabel) ?></a>
        </div>
    </form>
</section>

<?php if (!$shouldLoadReport): ?>
    <section class="empty-state" style="margin-top: 18px;"><?= e($emptyStateLabel) ?></section>
<?php else: ?>
<section class="sale-report-dashboard sale-report-dashboard-modern" style="margin-top: 18px;">
    <div class="sale-report-kpi-grid">
        <article class="sale-report-kpi-card is-bookings">
            <div class="sale-report-kpi-head">
                <span><?= e($bookingsLabel) ?></span>
                <span class="sale-report-kpi-icon is-bookings">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 3v2H5a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2V3h-2v2H9V3H7zm12 7H5v8h14v-8z" fill="currentColor"/></svg>
                </span>
            </div>
            <strong><?= (int) $saleReportDashboard['visible_rows'] ?></strong>
            <p><?= (int) $saleReportDashboard['active_rows'] ?> <?= e($activeLabel) ?><?= (int) $saleReportDashboard['cancelled_rows'] > 0 ? ' / ' . (int) $saleReportDashboard['cancelled_rows'] . ' ' . e($cancelledLabel) : '' ?></p>
        </article>

        <article class="sale-report-kpi-card is-paid">
            <div class="sale-report-kpi-head">
                <span><?= e($paidBillsLabel) ?></span>
                <span class="sale-report-kpi-icon is-paid">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm-1.2 14.4-3.6-3.6 1.4-1.4 2.2 2.2 4.6-4.6 1.4 1.4z" fill="currentColor"/></svg>
                </span>
            </div>
            <strong><?= (int) $saleReportDashboard['paid_rows'] ?></strong>
            <p><span class="sale-report-pill is-healthy"><?= e($saleReportDashboard['collection_health_label']) ?></span> <?= (int) $saleReportDashboard['paid_ratio'] ?>%</p>
        </article>

        <article class="sale-report-kpi-card is-partial">
            <div class="sale-report-kpi-head">
                <span><?= e($partialBillsLabel) ?></span>
                <span class="sale-report-kpi-icon is-partial">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm1 15h-2v-2h2zm0-4h-2V7h2z" fill="currentColor"/></svg>
                </span>
            </div>
            <strong><?= (int) $saleReportDashboard['partial_rows'] ?></strong>
            <p><span class="sale-report-pill is-warning"><?= e($saleReportDashboard['partial_health_label']) ?></span> <?= (int) $saleReportDashboard['partial_ratio'] ?>%</p>
        </article>

        <article class="sale-report-kpi-card is-unpaid">
            <div class="sale-report-kpi-head">
                <span><?= e($unpaidBillsLabel) ?></span>
                <span class="sale-report-kpi-icon is-unpaid">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2 1 21h22L12 2zm1 14h-2v2h2zm0-6h-2v5h2z" fill="currentColor"/></svg>
                </span>
            </div>
            <strong><?= (int) $saleReportDashboard['unpaid_rows'] ?></strong>
            <p><span class="sale-report-pill is-danger"><?= e($saleReportDashboard['unpaid_health_label']) ?></span> <?= (int) $saleReportDashboard['unpaid_ratio'] ?>%</p>
        </article>
    </div>

    <div class="sale-report-overview-grid">
        <article class="sale-report-overview-card">
            <div class="sale-report-overview-summary">
                <div class="sale-report-overview-primary">
                    <span><?= e($saleAmountLabel) ?></span>
                    <strong><?= sale_report_money($overallTotals['sale_amount']) ?></strong>
                </div>
                <div class="sale-report-overview-secondary">
                    <div>
                        <span><?= e($paidReceivedLabel) ?></span>
                        <strong><?= sale_report_money($overallTotals['paid_amount']) ?></strong>
                    </div>
                    <div>
                        <span><?= e($depositAdminLabel) ?></span>
                        <strong><?= sale_report_money($saleReportDashboard['admin_deposit_amount']) ?></strong>
                    </div>
                    <div>
                        <span><?= e($depositBranchLabel) ?></span>
                        <strong><?= sale_report_money($saleReportDashboard['branch_deposit_amount']) ?></strong>
                    </div>
                </div>
            </div>

            <div class="sale-report-payment-mix-card">
                <div class="sale-report-panel-head">
                    <div>
                        <h3><?= e($collectionsMixLabel) ?></h3>
                        <p><?= e($collectionsMixHelperLabel) ?></p>
                    </div>
                    <a href="#sale-report-results"><?= e($viewDetailsLabel) ?></a>
                </div>

                <div class="sale-report-payment-mix-list">
                    <?php foreach ($paymentMixRows as $paymentMixRow): ?>
                        <div class="sale-report-payment-mix-row">
                            <div class="sale-report-payment-mix-top">
                                <span class="sale-report-payment-icon is-<?= e($paymentMixRow['class']) ?>">
                                    <?php if ($paymentMixRow['icon'] === 'cash'): ?>
                                        <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 6h18v12H3zm2 2v8h14V8zm7 1a3 3 0 1 1-3 3 3 3 0 0 1 3-3z" fill="currentColor"/></svg>
                                    <?php elseif ($paymentMixRow['icon'] === 'bank'): ?>
                                        <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3 2 8v2h20V8zm-7 9h2v6H5zm4 0h2v6H9zm4 0h2v6h-2zm4 0h2v6h-2zM3 20h18v1H3z" fill="currentColor"/></svg>
                                    <?php elseif ($paymentMixRow['icon'] === 'card'): ?>
                                        <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 5h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zm0 3v2h16V8zm3 6h5v2H7z" fill="currentColor"/></svg>
                                    <?php else: ?>
                                        <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6h16a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1zm1 2v8h14V8zM7 11h3v2H7z" fill="currentColor"/></svg>
                                    <?php endif; ?>
                                </span>
                                <div class="sale-report-payment-mix-meta">
                                    <strong><?= e($paymentMixRow['label']) ?></strong>
                                    <span><?= sale_report_money($paymentMixRow['amount']) ?> (<?= rtrim(rtrim(number_format((float) $paymentMixRow['percent'], 1), '0'), '.') ?>%)</span>
                                </div>
                            </div>
                            <div class="sale-report-payment-track">
                                <span class="is-<?= e($paymentMixRow['class']) ?>" style="width: <?= max(0.0, min(100.0, (float) $paymentMixRow['percent'])) ?>%;"></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </article>

        <aside class="sale-report-outstanding-card">
            <div class="sale-report-outstanding-icon">
                <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 6h18v12H3zm2 2v8h14V8zm7 1a3 3 0 1 1-3 3 3 3 0 0 1 3-3z" fill="currentColor"/></svg>
            </div>
            <span class="sale-report-outstanding-label"><?= e($outstandingBalanceLabel) ?></span>
            <p class="sale-report-outstanding-copy"><?= e($outstandingBalanceHelperLabel) ?></p>
            <strong><?= sale_report_money($overallTotals['outstanding_amount']) ?></strong>

            <div class="sale-report-outstanding-meta">
                <span><?= e($avgOverdueDaysLabel) ?></span>
                <strong><?= (int) $saleReportDashboard['avg_overdue_days'] ?> <?= e($dayUnitLabel) ?></strong>
            </div>

            <div class="sale-report-outstanding-meta">
                <span><?= e($needFollowUpLabel) ?></span>
                <strong><?= (int) $saleReportDashboard['partial_rows'] + (int) $saleReportDashboard['unpaid_rows'] ?> <?= e($billUnitLabel) ?></strong>
            </div>

            <a class="button button-accent button-full" href="#sale-report-results"><?= e($openBillListLabel) ?></a>
        </aside>
    </div>
</section>

<section id="sale-report-results" class="table-card sale-report-card" style="margin-top: 18px;">
    <div class="section-head sale-report-title" style="padding: 18px 18px 0;">
        <div>
            <h2 class="section-title"><?= e($pageTitle) ?> <?= e($periodLabel) ?></h2>
            <p class="helper"><?= e($selectedBranchLabel) ?> / <?= e($selectedPaymentStatusLabel) ?> / <?= e($selectedOrderSourceLabel) ?> / <?= count($rows) ?> <?= e($reportRowsLabel) ?></p>
        </div>
    </div>

    <table class="sale-report-table">
        <thead>
        <!--
        <tr>
            <th rowspan="2">วันที่</th>
            <th rowspan="2">Bill no.</th>
            <th rowspan="2">เวลารับ</th>
            <th rowspan="2">ทะเบียน</th>
            <th rowspan="2">ยี่ห้อ</th>
            <th rowspan="2">รุ่น</th>
            <th rowspan="2">บริการ</th>
            <th rowspan="2">ยอดขาย</th>
            <th rowspan="2">ยอดเงินที่ได้รับ</th>
            <th colspan="4">ชำระโดย</th>
            <th colspan="3">Deposit @Admin</th>
            <th rowspan="2">มัดจำมาเดือนที่แล้ว</th>
            <th rowspan="2">เงินมัดจำล่วงหน้า</th>
            <th rowspan="2">ค้างชำระ</th>
            <th rowspan="2">หมายเหตุ</th>
        </tr>
        <tr>
            <th>เงินสด</th>
            <th>โอน</th>
            <th>รูดบัตร</th>
            <th>ไม่ทราบการชำระ</th>
            <th>เงินสด</th>
            <th>โอน</th>
            <th>รูดบัตร</th>
        </tr>
        -->
        <tr>
            <th rowspan="2"><?= e($dateLabel) ?></th>
            <th rowspan="2"><?= e($statusLabel) ?></th>
            <th rowspan="2"><?= e($billNoLabel) ?></th>
            <th rowspan="2"><?= e($saleTypeLabel) ?></th>
            <th rowspan="2"><?= e($pickupDueLabel) ?></th>
            <th rowspan="2"><?= e($plateNumberLabel) ?></th>
            <th rowspan="2"><?= e($brandLabel) ?></th>
            <th rowspan="2"><?= e($modelLabel) ?></th>
            <th rowspan="2"><?= e($serviceLabel) ?></th>
            <th rowspan="2"><?= e($saleAmountLabel) ?></th>
            <th rowspan="2"><?= e($paidReceivedLabel) ?></th>
            <th colspan="4"><?= e($paymentsLabel) ?></th>
            <th colspan="3"><?= e($depositAdminLabel) ?></th>
            <th colspan="3"><?= e($depositBranchLabel) ?></th>
            <th rowspan="2"><?= e($previousMonthDepositLabel) ?></th>
            <th rowspan="2"><?= e($advanceDepositLabel) ?></th>
            <th rowspan="2"><?= e($outstandingLabel) ?></th>
            <th rowspan="2"><?= e($notesLabel) ?></th>
        </tr>
        <tr>
            <th><?= e($cashLabel) ?></th>
            <th><?= e($transferLabel) ?></th>
            <th><?= e($cardLabel) ?></th>
            <th><?= e($unknownLabel) ?></th>
            <th><?= e($cashLabel) ?></th>
            <th><?= e($transferLabel) ?></th>
            <th><?= e($cardLabel) ?></th>
            <th><?= e($cashLabel) ?></th>
            <th><?= e($transferLabel) ?></th>
            <th><?= e($cardLabel) ?></th>
        </tr>
        </thead>
        <tbody>
        <tr class="sale-report-total-row sale-report-month-row">
            <td><?= e($totalLabel) ?></td>
            <td colspan="8"></td>
            <td class="number"><?= sale_report_money($overallTotals['sale_amount']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['paid_amount']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['cash_amount']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['transfer_amount']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['card_amount']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['unknown_amount']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['admin_deposit_cash']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['admin_deposit_transfer']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['admin_deposit_card']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['branch_deposit_cash']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['branch_deposit_transfer']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['branch_deposit_card']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['previous_deposit_amount']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['advance_deposit_amount']) ?></td>
            <td class="number"><?= sale_report_money($overallTotals['outstanding_amount']) ?></td>
            <td></td>
        </tr>

        <?php if (empty($rowsByDate)): ?>
            <tr>
                <td colspan="25" class="empty-report-cell"><?= e($noSalesFoundLabel) ?></td>
            </tr>
        <?php else: ?>
            <?php foreach ($rowsByDate as $dateKey => $dayRows): ?>
                <?php
                $dayTotals = sale_report_empty_totals();
                foreach ($dayRows as $dayRow) {
                    if (empty($dayRow['is_cancelled'])) {
                        sale_report_add_totals($dayTotals, $dayRow);
                    }
                }
                ?>
                <?php foreach ($dayRows as $index => $row): ?>
                    <?php
                    $reopenedFromOrderId = (int) ($row['reopened_from_order_id'] ?? 0);
                    $reopenedFromBillNumber = (string) ($row['reopened_from_bill_number'] ?? '');
                    $reopenedFromLabel = $reopenedFromOrderId > 0 ? ($reopenedFromBillNumber !== '' ? $reopenedFromBillNumber : '#' . $reopenedFromOrderId) : '';
                    ?>
                    <tr class="<?= !empty($row['is_cancelled']) ? 'sale-report-void-row' : '' ?>">
                        <td><?= $index === 0 ? e(sale_report_date($dateKey)) : '' ?></td>
                        <td class="sale-report-status-cell">
                            <span class="<?= e(payment_status_class((string) $row['payment_status'])) ?>">
                                <?= e(payment_status_label((string) $row['payment_status'])) ?>
                            </span>
                        </td>
                        <td>
                            <a class="bill-link" href="job_details.php?id=<?= (int) $row['order_id'] ?>">
                                <?= e((string) ($row['bill_number'] ?: '#' . (int) $row['order_id'])) ?>
                            </a>
                            <?php if ($reopenedFromLabel !== ''): ?>
                                <span class="ref-label"><?= e($reopenedReferenceLabel) ?> <?= e($reopenedFromLabel) ?></span>
                            <?php endif; ?>
                            <?php if (!empty($row['is_cancelled'])): ?>
                                <span class="void-label localized-void-label"><?= e($cancelledInlineLabel) ?></span>
                                <span class="void-label">(ยกเลิก)</span>
                            <?php endif; ?>
                        </td>
                        <td><?= e(sale_report_display_order_source_label((string) ($row['order_source'] ?? 'booking'))) ?></td>
                        <td><?= e(sale_report_time($row['return_at'] ? (string) $row['return_at'] : null)) ?></td>
                        <td>
                            <strong><?= e((string) $row['plate_number']) ?></strong>
                        </td>
                        <td><?= e((string) ($row['brand'] ?? '')) ?></td>
                        <td><?= e((string) ($row['model'] ?? '')) ?></td>
                        <td><?= e((string) ($row['service_names'] ?? '-')) ?></td>
                        <td class="number"><?= sale_report_money($row['sale_amount']) ?></td>
                        <td class="number"><?= sale_report_money($row['paid_amount']) ?></td>
                        <td class="number"><?= sale_report_money($row['cash_amount']) ?></td>
                        <td class="number"><?= sale_report_money($row['transfer_amount']) ?></td>
                        <td class="number"><?= sale_report_money($row['card_amount']) ?></td>
                        <td class="number"><?= sale_report_money($row['unknown_amount']) ?></td>
                        <td class="number"><?= sale_report_money($row['admin_deposit_cash']) ?></td>
                        <td class="number"><?= sale_report_money($row['admin_deposit_transfer']) ?></td>
                        <td class="number"><?= sale_report_money($row['admin_deposit_card']) ?></td>
                        <td class="number"><?= sale_report_money($row['branch_deposit_cash']) ?></td>
                        <td class="number"><?= sale_report_money($row['branch_deposit_transfer']) ?></td>
                        <td class="number"><?= sale_report_money($row['branch_deposit_card']) ?></td>
                        <td class="number"><?= sale_report_money($row['previous_deposit_amount']) ?></td>
                        <td class="number"><?= sale_report_money($row['advance_deposit_amount']) ?></td>
                        <td class="number"><?= sale_report_money($row['outstanding_amount']) ?></td>
                        <td><?= nl2br(e((string) ($row['notes'] ?? ''))) ?></td>
                    </tr>
                <?php endforeach; ?>
                <tr class="sale-report-total-row">
                    <td colspan="8"><?= e($totalSummaryLabel) ?></td>
                    <td></td>
                    <td class="number"><?= sale_report_money($dayTotals['sale_amount']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['paid_amount']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['cash_amount']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['transfer_amount']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['card_amount']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['unknown_amount']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['admin_deposit_cash']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['admin_deposit_transfer']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['admin_deposit_card']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['branch_deposit_cash']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['branch_deposit_transfer']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['branch_deposit_card']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['previous_deposit_amount']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['advance_deposit_amount']) ?></td>
                    <td class="number"><?= sale_report_money($dayTotals['outstanding_amount']) ?></td>
                    <td></td>
                </tr>
                <tr class="sale-report-spacer">
                    <td colspan="25"></td>
                </tr>
            <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
    </table>
</section>
<?php endif; ?>

<?php render_page_end(); ?>
