<?php
declare(strict_types=1);

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

require_login($conn);

$canViewMemberInfo = can_access($conn, 'member');
$canManageMemberList = can_access($conn, 'member_manage');
$canEditMembers = can_access($conn, 'member_edit');
$canDeleteMembers = can_access($conn, 'member_delete');

if (!$canViewMemberInfo && !$canManageMemberList) {
    redirect_with_flash(
        auth_page_path(auth_preferred_landing_page($conn)),
        'error',
        localized_flash_message('คุณไม่มีสิทธิ์ใช้งานฟังก์ชันนี้', 'You do not have permission to access that function.')
    );
}

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

$oldInput = pull_old_input();

$search = trim((string) ($_GET['q'] ?? ''));
if (strlen($search) > 80) {
    $search = substr($search, 0, 80);
}

$searchDigits = normalize_phone($search);
$searchPlate = normalize_plate($search);
$hasSearch = $search !== '';
$customerSearchReady = !$hasSearch || $searchDigits !== '' || $searchPlate !== '';
$searchMessage = '';

$selectedGroup = customer_group_filter_value((string) ($_GET['group'] ?? 'all'));
$memberViewInput = strtolower(trim((string) ($_GET['view'] ?? ($canViewMemberInfo ? 'profile' : 'list'))));
$memberView = $memberViewInput === 'list' && $canManageMemberList ? 'list' : 'profile';
 $editRequested = (string) ($_GET['edit'] ?? '') === '1';

if ($memberView === 'profile' && !$canViewMemberInfo && $canManageMemberList) {
    $memberView = 'list';
}

$isProfileView = $memberView === 'profile';
$isListView = $memberView === 'list';
$isEditMode = $isListView && $canEditMembers && $editRequested;

if ($isProfileView) {
    $selectedGroup = 'all';
}

$loadMemberProfileSearch = $isProfileView && $hasSearch;
$loadMemberListSearch = $isListView && ($hasSearch || $selectedGroup !== 'all' || $isEditMode);
$loadCustomerRows = $customerSearchReady && ($loadMemberProfileSearch || $loadMemberListSearch);

if ($hasSearch && !$customerSearchReady) {
    $searchMessage = localized_text_value(
        'กรอกเบอร์โทรลูกค้าหรือทะเบียนรถแบบตรงตัวเพื่อค้นหาประวัติสมาชิก',
        'Enter the exact customer phone number or plate number to search member history.'
    );
}

$customers = array();
$customerTypes = '';
$customerParams = array();
$selectedCustomerId = (int) (filter_input(INPUT_GET, 'customer_id', FILTER_VALIDATE_INT) ?: 0);
$selectedCarId = (int) (filter_input(INPUT_GET, 'car_id', FILTER_VALIDATE_INT) ?: 0);

if ($loadCustomerRows) {
    $matchedCustomerIds = array();
    if ($hasSearch) {
        $matchedCustomers = find_customer_matches($conn, $search, $search, 100);
        $matchedCustomerIds = array_values(array_unique(array_filter(array_map(static function (array $match): int {
            return (int) ($match['customerId'] ?? 0);
        }, $matchedCustomers))));
    }

    if (!$hasSearch || !empty($matchedCustomerIds)) {
        $customerOrderJoin = "INNER JOIN orders o ON o.customer_id = c.customer_id AND o.status <> 'cancelled'";
        $branchCondition = auth_branch_condition($conn, 'o', $customerTypes, $customerParams);
        if ($branchCondition !== '') {
            $customerOrderJoin .= " AND {$branchCondition}";
        }

        $customerWhere = array();
        if (!empty($matchedCustomerIds)) {
            $customerWhere[] = 'c.customer_id IN (' . implode(',', array_fill(0, count($matchedCustomerIds), '?')) . ')';
            $customerTypes .= str_repeat('i', count($matchedCustomerIds));
            foreach ($matchedCustomerIds as $matchedCustomerId) {
                $customerParams[] = $matchedCustomerId;
            }
        }

        if ($isListView && $selectedGroup !== 'all') {
            $customerWhere[] = 'c.customer_group = ?';
            $customerTypes .= 's';
            $customerParams[] = $selectedGroup;
        }

        $customerWhereSql = empty($customerWhere)
            ? ''
            : 'WHERE ' . implode(' AND ', $customerWhere);
        $customerOrderSql = !empty($matchedCustomerIds)
            ? ' ORDER BY FIELD(c.customer_id, ' . implode(',', array_map('intval', $matchedCustomerIds)) . ')'
            : ' ORDER BY latest_visit DESC, c.updated_at DESC, c.customer_id DESC';

        $customersStmt = db_prepare($conn, "
            SELECT
                c.customer_id,
                c.name,
                c.phone,
                c.email,
                c.loyalty_points,
                c.customer_group,
                COUNT(DISTINCT o.order_id) AS visit_count,
                COALESCE(SUM(o.total_price), 0) AS lifetime_value,
                MAX(o.order_date) AS latest_visit
            FROM customers c
            {$customerOrderJoin}
            {$customerWhereSql}
            GROUP BY
                c.customer_id,
                c.name,
                c.phone,
                c.email,
                c.loyalty_points,
                c.customer_group
            {$customerOrderSql}
            LIMIT 100
        ");
        if ($customerTypes !== '') {
            $customersStmt->bind_param($customerTypes, ...$customerParams);
        }
        $customersStmt->execute();
        $customersResult = $customersStmt->get_result();

        if ($customersResult instanceof mysqli_result) {
            while ($row = $customersResult->fetch_assoc()) {
                $customers[] = $row;
            }
        }
        $customersStmt->close();

        $customerCarSummaryMap = customer_car_summary_map($conn, array_column($customers, 'customer_id'));
        foreach ($customers as &$customerRow) {
            $customerId = (int) ($customerRow['customer_id'] ?? 0);
            $carSummary = $customerCarSummaryMap[$customerId] ?? array();
            $customerRow['car_count'] = (int) ($carSummary['car_count'] ?? 0);
            $customerRow['plate_numbers'] = (string) ($carSummary['plate_numbers'] ?? '');
        }
        unset($customerRow);
    }
}

if ($loadMemberProfileSearch && $selectedCustomerId <= 0 && !empty($customers)) {
    $selectedCustomerId = (int) $customers[0]['customer_id'];
}

$selectedCustomer = null;
$vehicles = array();
$historyRows = array();
$vehiclePackageServices = array();
$selectedVehiclePackageUsage = array();
$canOpenJobDetails = can_access($conn, 'queue');
$selectedVehicle = null;

if (($loadMemberProfileSearch || $isEditMode) && $selectedCustomerId > 0) {
    $selectedTypes = '';
    $selectedParams = array();
    $selectedOrderJoin = "INNER JOIN orders o ON o.customer_id = c.customer_id AND o.status <> 'cancelled'";
    $branchCondition = auth_branch_condition($conn, 'o', $selectedTypes, $selectedParams);
    if ($branchCondition !== '') {
        $selectedOrderJoin .= " AND {$branchCondition}";
    }
    $selectedTypes .= 'i';
    $selectedParams[] = $selectedCustomerId;

    $selectedStmt = db_prepare($conn, "
        SELECT
            c.customer_id,
            c.name,
            c.phone,
            c.email,
            c.loyalty_points,
            c.customer_group,
            c.created_at,
            c.updated_at,
            COUNT(DISTINCT o.order_id) AS visit_count,
            COUNT(DISTINCT o.car_id) AS vehicle_count,
            COALESCE(SUM(o.total_price), 0) AS lifetime_value,
            MIN(o.order_date) AS first_visit,
            MAX(o.order_date) AS latest_visit
        FROM customers c
        {$selectedOrderJoin}
        WHERE c.customer_id = ?
        GROUP BY
            c.customer_id,
            c.name,
            c.phone,
            c.email,
            c.loyalty_points,
            c.customer_group,
            c.created_at,
            c.updated_at
        LIMIT 1
    ");
    $selectedStmt->bind_param($selectedTypes, ...$selectedParams);
    $selectedStmt->execute();
    $selectedResult = $selectedStmt->get_result();
    if ($selectedResult instanceof mysqli_result) {
        $selectedCustomer = $selectedResult->fetch_assoc() ?: null;
    }
    $selectedStmt->close();

    if ($selectedCustomer) {
        $selectedOrderIdTypes = '';
        $selectedOrderIdParams = array();
        $selectedOrderIdWhere = array();
        $branchCondition = auth_branch_condition($conn, 'o', $selectedOrderIdTypes, $selectedOrderIdParams);
        if ($branchCondition !== '') {
            $selectedOrderIdWhere[] = $branchCondition;
        }
        $selectedOrderIdWhere[] = 'o.customer_id = ?';
        $selectedOrderIdWhere[] = "o.status <> 'cancelled'";
        $selectedOrderIdTypes .= 'i';
        $selectedOrderIdParams[] = $selectedCustomerId;
        $selectedOrderIdStmt = db_prepare($conn, "
            SELECT o.order_id
            FROM orders o
            WHERE " . implode(' AND ', $selectedOrderIdWhere) . "
        ");
        $selectedOrderIdStmt->bind_param($selectedOrderIdTypes, ...$selectedOrderIdParams);
        $selectedOrderIdStmt->execute();
        $selectedOrderIdResult = $selectedOrderIdStmt->get_result();
        $selectedOrderIds = array();
        if ($selectedOrderIdResult instanceof mysqli_result) {
            while ($selectedOrderIdRow = $selectedOrderIdResult->fetch_assoc()) {
                $selectedOrderIds[] = (int) ($selectedOrderIdRow['order_id'] ?? 0);
            }
        }
        $selectedOrderIdStmt->close();

        $selectedPaymentSummaryMap = order_payment_summary_map($conn, $selectedOrderIds);
        $selectedPaidAmount = 0.0;
        foreach ($selectedPaymentSummaryMap as $paymentSummary) {
            $selectedPaidAmount += (float) ($paymentSummary['total_amount'] ?? 0);
        }
        $selectedCustomer['paid_amount'] = $selectedPaidAmount;

        $vehicleTypes = '';
        $vehicleParams = array();
        $vehicleOrderJoin = "LEFT JOIN orders o ON o.car_id = car.car_id AND o.status <> 'cancelled'";
        $branchCondition = auth_branch_condition($conn, 'o', $vehicleTypes, $vehicleParams);
        if ($branchCondition !== '') {
            $vehicleOrderJoin .= " AND {$branchCondition}";
        }
        $vehicleTypes .= 'i';
        $vehicleParams[] = $selectedCustomerId;

        $vehiclesStmt = db_prepare($conn, "
            SELECT
                car.car_id,
                car.plate_number,
                car.province,
                car.vehicle_type,
                car.brand,
                car.model,
                car.color,
                COUNT(DISTINCT o.order_id) AS visit_count,
                COALESCE(SUM(o.total_price), 0) AS vehicle_value,
                MAX(o.order_date) AS latest_visit
            FROM cars car
            {$vehicleOrderJoin}
            WHERE car.customer_id = ?
            GROUP BY
                car.car_id,
                car.plate_number,
                car.province,
                car.vehicle_type,
                car.brand,
                car.model,
                car.color
            ORDER BY latest_visit DESC, car.updated_at DESC, car.car_id DESC
        ");
        $vehiclesStmt->bind_param($vehicleTypes, ...$vehicleParams);
        $vehiclesStmt->execute();
        $vehiclesResult = $vehiclesStmt->get_result();
        if ($vehiclesResult instanceof mysqli_result) {
            while ($row = $vehiclesResult->fetch_assoc()) {
                if ($selectedCarId > 0 && (int) $row['car_id'] === $selectedCarId) {
                    $selectedVehicle = $row;
                }
                $vehicles[] = $row;
            }
        }
        $vehiclesStmt->close();

        $historyTypes = '';
        $historyParams = array();
        $historyWhere = array();
        $branchCondition = auth_branch_condition($conn, 'o', $historyTypes, $historyParams);
        if ($branchCondition !== '') {
            $historyWhere[] = $branchCondition;
        }
        $historyWhere[] = 'o.customer_id = ?';
        $historyTypes .= 'i';
        $historyParams[] = $selectedCustomerId;
        if ($selectedVehicle) {
            $historyWhere[] = 'o.car_id = ?';
            $historyTypes .= 'i';
            $historyParams[] = $selectedCarId;
        }
        $historyWhereSql = implode(' AND ', $historyWhere);

        $historyStmt = db_prepare($conn, "
            SELECT
                o.order_id,
                o.bill_number,
                o.order_date,
                o.scheduled_at,
                o.return_at,
                o.branch_name,
                o.status,
                o.payment_status,
                o.total_price,
                car.plate_number,
                car.province,
                car.brand,
                car.model,
                q.queue_number
            FROM orders o FORCE INDEX (idx_orders_customer_recent)
            INNER JOIN cars car ON car.car_id = o.car_id
            LEFT JOIN queue q ON q.order_id = o.order_id
            WHERE {$historyWhereSql}
            ORDER BY o.order_date DESC, o.order_id DESC
            LIMIT 100
        ");
        $historyStmt->bind_param($historyTypes, ...$historyParams);
        $historyStmt->execute();
        $historyResult = $historyStmt->get_result();
        if ($historyResult instanceof mysqli_result) {
            while ($row = $historyResult->fetch_assoc()) {
                $historyRows[] = $row;
            }
        }
        $historyStmt->close();

        $historyOrderIds = array_column($historyRows, 'order_id');
        $historyServiceSummaryMap = order_service_summary_map($conn, $historyOrderIds);
        $historyPaymentSummaryMap = order_payment_summary_map($conn, $historyOrderIds);

        foreach ($historyRows as &$historyRow) {
            $orderId = (int) ($historyRow['order_id'] ?? 0);
            $serviceSummary = $historyServiceSummaryMap[$orderId] ?? array();
            $paymentSummary = $historyPaymentSummaryMap[$orderId] ?? order_payment_summary_defaults();
            $historyRow['service_names'] = (string) ($serviceSummary['service_names'] ?? '');
            $historyRow['paid_amount'] = (float) ($paymentSummary['total_amount'] ?? 0);
        }
        unset($historyRow);

        if ($selectedVehicle) {
            $vehiclePackageServices = service_customer_vehicle_package_service_rows($conn, $selectedCustomerId, $selectedCarId);
            $selectedVehiclePackageUsage = service_customer_package_usage_history($conn, $selectedCustomerId, $selectedCarId);
        }
    }
}

$pageTitle = localized_text_value('สมาชิก', 'Member');
$pageDescription = localized_text_value(
    'ค้นหาข้อมูลลูกค้า ดูข้อมูลรถ และตรวจสอบประวัติการใช้บริการในสาขาที่เข้าถึงได้',
    'Search customer records, view vehicles and inspect service history across accessible branches.'
);
$newBookingLabel = localized_text_value('เปิดงานใหม่', 'New booking');
$profileViewLabel = localized_text_value('ข้อมูลสมาชิก', 'Member info');
$listViewLabel = localized_text_value('รายชื่อสมาชิก', 'Member list');
$searchMemberLabel = localized_text_value('ค้นหาสมาชิกด้วยเบอร์โทรหรือทะเบียนรถ', 'Search member by phone or plate');
$searchMemberHelper = localized_text_value(
    'ค้นหาได้เฉพาะเบอร์โทรลูกค้าที่ตรงกันหรือทะเบียนรถที่ตรงเท่านั้น',
    'Search works only with the exact customer phone number or exact plate number.'
);
$searchLabel = localized_text_value('ค้นหา', 'Search');
$searchMembersLabel = localized_text_value('ค้นหาสมาชิก', 'Search members');
$resetLabel = localized_text_value('รีเซ็ต', 'Reset');
$searchProfileFirstLabel = localized_text_value(
    'ค้นหาสมาชิกก่อนเพื่อดูโปรไฟล์ ประวัติการใช้บริการ และข้อมูลแพ็กเกจ',
    'Search a member first to view profile, service history and package data.'
);
$noMatchingMemberLabel = localized_text_value('ไม่พบบันทึกสมาชิกที่ตรงกับการค้นหา', 'No matching member record was found.');
$searchResultsTitle = localized_text_value('ผลการค้นหา', 'Search results');
$customerRecordCountLabel = localized_text_value('{count} รายการลูกค้า', '{count} customer record(s)');
$customerLabel = localized_text_value('ลูกค้า', 'Customer');
$groupLabel = localized_text_value('กลุ่มลูกค้า', 'Group');
$carsLabel = localized_text_value('รถ', 'Cars');
$latestVisitLabel = localized_text_value('ใช้บริการล่าสุด', 'Latest visit');
$actionLabel = localized_text_value('การทำรายการ', 'Action');
$openMemberLabel = localized_text_value('เปิดข้อมูลสมาชิก', 'Open member');
$pointsLabel = localized_text_value('คะแนน', 'Points');
$visitsLabel = localized_text_value('จำนวนครั้ง', 'Visits');
$lifetimeValueLabel = localized_text_value('มูลค่าสะสม', 'Lifetime value');
$customerProfileTitle = localized_text_value('โปรไฟล์ลูกค้า', 'Customer profile');
$firstVisitLabel = localized_text_value('ครั้งแรกที่ใช้บริการ', 'First visit');
$phoneLabel = localized_text_value('เบอร์โทร', 'Phone');
$emailLabel = localized_text_value('อีเมล', 'Email');
$memberLevelLabel = localized_text_value('ระดับสมาชิก', 'Member level');
$vehiclesTitle = localized_text_value('รถของลูกค้า', 'Vehicles');
$vehicleHelper = localized_text_value(
    'เลือกทะเบียนรถเพื่อดูยอดคงเหลือแพ็กเกจและประวัติการใช้งานของรถคันนั้น',
    'Select a plate number to view package balances and usage for that vehicle.'
);
$clearVehicleLabel = localized_text_value('ล้างการเลือกรถ', 'Clear vehicle');
$noVehiclesFoundLabel = localized_text_value('ไม่พบข้อมูลรถ', 'No vehicles found.');
$vehiclePendingLabel = localized_text_value('ยังไม่มีรายละเอียดรถ', 'Vehicle details pending');
$visitCountValueLabel = localized_text_value('{count} ครั้ง / {amount} บาท', '{count} visit(s) / {amount} THB');
$latestShortLabel = localized_text_value('ล่าสุด', 'Latest');
$paymentSummaryTitle = localized_text_value('สรุปการชำระเงิน', 'Payment summary');
$openedRevenueLabel = localized_text_value('ยอดเปิดบิลสะสม', 'Opened revenue');
$paidReceivedLabel = localized_text_value('ยอดรับชำระ', 'Paid received');
$outstandingLabel = localized_text_value('ยอดค้างชำระ', 'Outstanding');
$packageServiceViewTitle = localized_text_value('มุมมองบริการแพ็กเกจ', 'Package service view');
$selectedVehicleLabel = localized_text_value('รถที่เลือก', 'Selected vehicle');
$vehicleDetailsLabel = localized_text_value('รายละเอียดรถ', 'Vehicle details');
$packageServiceRowsLabel = localized_text_value('จำนวนแถวบริการแพ็กเกจ', 'Package service rows');
$remainingUsesLabel = localized_text_value('สิทธิ์คงเหลือ', 'Remaining uses');
$chooseVehicleFirstLabel = localized_text_value(
    'เลือกรถก่อนเพื่อตรวจสอบยอดคงเหลือแพ็กเกจและประวัติการใช้งาน',
    'Choose a vehicle first to inspect package balances and usage history.'
);
$packageServiceTitle = localized_text_value('บริการแพ็กเกจ', 'Package service');
$packageServiceVehicleHelper = localized_text_value(
    'แสดงจำนวนสิทธิ์ที่รวม ใช้ไป และคงเหลือของทุกบริการแพ็กเกจที่รถคันนี้ใช้งานได้',
    'Included, used and remaining totals are shown for every package service this vehicle can use.'
);
$packageServiceSelectHelper = localized_text_value(
    'เลือกรถเพื่อดูยอดคงเหลือแพ็กเกจ สิทธิ์คงเหลือ และรายละเอียดการใช้งาน',
    'Select a vehicle to view package balances, remaining uses and usage details.'
);
$selectVehicleAboveLabel = localized_text_value(
    'เลือกรถจากรายการด้านบนเพื่อโหลดข้อมูลบริการแพ็กเกจ',
    'Select a vehicle from the list above to load package service data.'
);
$noPackageServicesLabel = localized_text_value('ไม่มีบริการแพ็กเกจสำหรับรถคันนี้', 'No package services available for this vehicle.');
$packageLabel = localized_text_value('แพ็กเกจ', 'Package');
$serviceLabel = localized_text_value('บริการ', 'Service');
$accessLabel = localized_text_value('สิทธิ์การใช้', 'Access');
$includedLabel = localized_text_value('รวมสิทธิ์', 'Included');
$usedLabel = localized_text_value('ใช้ไป', 'Used');
$remainingLabel = localized_text_value('คงเหลือ', 'Remaining');
$purchasedLabel = localized_text_value('วันที่ซื้อ', 'Purchased');
$billLabel = localized_text_value('บิล', 'Bill');
$packageUsageHistoryTitle = localized_text_value('ประวัติการใช้แพ็กเกจ', 'Package usage history');
$packageUsageVehicleHelper = localized_text_value(
    '{count} รายการใช้งานสำหรับรถที่เลือก',
    '{count} usage record(s) for the selected vehicle.'
);
$packageUsageSelectHelper = localized_text_value(
    'เลือกรถก่อนเพื่อดูวันที่ใช้แพ็กเกจและทะเบียนรถที่ใช้',
    'Select a vehicle first to view package usage dates and used plates.'
);
$packageUsageAppearsLabel = localized_text_value(
    'ประวัติการใช้แพ็กเกจจะแสดงหลังจากคุณเลือกรถ',
    'Package usage history will appear after you choose a vehicle.'
);
$noPackageUsageLabel = localized_text_value('ไม่พบประวัติการใช้แพ็กเกจสำหรับรถคันนี้', 'No package usage history found for this vehicle.');
$dateLabel = localized_text_value('วันที่', 'Date');
$subServiceLabel = localized_text_value('บริการย่อย', 'Sub service');
$usedPlateLabel = localized_text_value('ทะเบียนที่ใช้', 'Used plate');
$detailsLabel = localized_text_value('รายละเอียด', 'Details');
$serviceHistoryTitle = localized_text_value('ประวัติการใช้บริการ', 'Service history');
$serviceHistoryCountVehicleLabel = localized_text_value('{count} งานสำหรับรถที่เลือก', '{count} job record(s) for selected vehicle');
$serviceHistoryCountAllLabel = localized_text_value('{count} งานสำหรับรถทุกคัน', '{count} job record(s) for all vehicles');
$allVehiclesLabel = localized_text_value('รถทั้งหมด', 'All vehicles');
$noServiceHistoryLabel = localized_text_value('ไม่พบประวัติการใช้บริการ', 'No service history found.');
$branchLabel = localized_text_value('สาขา', 'Branch');
$statusLabel = localized_text_value('สถานะ', 'Status');
$paymentLabel = localized_text_value('การชำระเงิน', 'Payment');
$totalLabel = localized_text_value('รวม', 'Total');
$paidLabel = localized_text_value('ชำระแล้ว', 'Paid');
$customerGroupLabel = localized_text_value('กลุ่มลูกค้า', 'Customer group');
$groupSearchHelper = localized_text_value(
    'ค้นหาสมาชิกด้วยคำค้น หรือเลือกกลุ่มลูกค้าเพื่อแสดงรายการที่ตรงกัน',
    'Search members by keyword, or choose a customer group to list matching records.'
);
$chooseGroupOrSearchLabel = localized_text_value(
    'เลือกกลุ่มลูกค้า หรือค้นหาด้วยเบอร์โทร / ทะเบียน เพื่อโหลดรายชื่อสมาชิก',
    'Choose a customer group or search by phone / plate to load the member list.'
);
$memberListTitle = localized_text_value('รายชื่อสมาชิก', 'Member list');
$noCustomerMatchLabel = localized_text_value('ไม่พบบันทึกลูกค้าที่ตรงกับการค้นหา', 'No customer record matched this search.');
$levelLabel = localized_text_value('ระดับ', 'Level');
$viewInfoLabel = localized_text_value('ดูข้อมูล', 'View info');
$editLabel = localized_text_value('แก้ไข', 'Edit');
$deleteLabel = localized_text_value('ลบ', 'Delete');
$deleteConfirmLabel = localized_text_value('ลบบันทึกสมาชิกนี้หรือไม่', 'Delete this member record?');
$editMemberTitle = localized_text_value('แก้ไขสมาชิก', 'Edit member');
$editMemberHelper = localized_text_value(
    'อัปเดตข้อมูลสมาชิก แล้วบันทึกหรือย้ายลูกค้าไปยังอีกกลุ่มหนึ่ง',
    'Update member information, then save or move the customer to another group.'
);
$closeLabel = localized_text_value('ปิด', 'Close');
$customerNameLabel = localized_text_value('ชื่อลูกค้า', 'Customer name');
$saveMemberLabel = localized_text_value('บันทึกสมาชิก', 'Save member');
$cancelLabel = localized_text_value('ยกเลิก', 'Cancel');
$noEditPermissionLabel = localized_text_value('คุณไม่มีสิทธิ์แก้ไขข้อมูลสมาชิก', 'You do not have permission to edit member data.');
$memberLoadFailedLabel = localized_text_value('ไม่สามารถโหลดสมาชิกที่เลือกเพื่อแก้ไขได้', 'The selected member could not be loaded for editing.');
$memberSearchPlaceholder = '0971234567 / 1234 / 5ขฎ8154';

$vehicleLabel = localized_text_value('รถ', 'Vehicle');
$servicesLabel = localized_text_value('บริการ', 'Services');
$billNumberLabel = localized_text_value('เลขที่บิล', 'Bill no.');

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

<section class="page-hero">
    <div>
        <h1><?= e($pageTitle) ?></h1>
        <p><?= e($pageDescription) ?></p>
    </div>
    <div class="hero-actions">
        <a class="button button-accent" href="booking.php"><?= e($newBookingLabel) ?></a>
    </div>
</section>

<section class="service-management-tabs">
    <?php if ($canViewMemberInfo): ?>
        <a class="<?= e($isProfileView ? 'button button-accent' : 'button button-secondary') ?>" href="member.php?view=profile"><?= e($profileViewLabel) ?></a>
    <?php endif; ?>
    <?php if ($canManageMemberList): ?>
        <a class="<?= e($isListView ? 'button button-accent' : 'button button-secondary') ?>" href="member.php?view=list"><?= e($listViewLabel) ?></a>
    <?php endif; ?>
</section>

<?php if ($isProfileView): ?>
    <section class="card">
        <form method="GET" action="member.php" role="search">
            <input type="hidden" name="view" value="profile">
            <div class="form-grid">
                <div class="field">
                    <label for="q"><?= e($searchMemberLabel) ?></label>
                    <input
                        id="q"
                        name="q"
                        type="text"
                        inputmode="text"
                        autocomplete="off"
                        value="<?= e($search) ?>"
                        placeholder="<?= e($memberSearchPlaceholder) ?>"
                    >
                    <p class="helper"><?= e($searchMemberHelper) ?></p>
                </div>
            </div>
            <div class="actions">
                <button class="button" type="submit"><?= e($searchLabel) ?></button>
                <a class="button button-ghost" href="member.php?view=profile"><?= e($resetLabel) ?></a>
            </div>
        </form>
    </section>

    <?php if ($searchMessage !== ''): ?>
        <section class="empty-state" style="margin-top: 18px;"><?= e($searchMessage) ?></section>
    <?php elseif (!$hasSearch): ?>
        <section class="empty-state" style="margin-top: 18px;"><?= e($searchProfileFirstLabel) ?></section>
    <?php elseif (empty($customers)): ?>
        <section class="empty-state" style="margin-top: 18px;"><?= e($noMatchingMemberLabel) ?></section>
    <?php else: ?>
        <section class="table-card" style="margin-top: 18px;">
            <div class="section-head" style="padding: 18px 18px 0;">
                <div>
                    <h2 class="section-title"><?= e($searchResultsTitle) ?></h2>
                    <p class="helper"><?= e(strtr($customerRecordCountLabel, array('{count}' => (string) count($customers)))) ?></p>
                </div>
            </div>

            <table>
                <thead>
                <tr>
                    <th><?= e($customerLabel) ?></th>
                    <th><?= e($groupLabel) ?></th>
                    <th><?= e($carsLabel) ?></th>
                    <th><?= e($latestVisitLabel) ?></th>
                    <th><?= e($actionLabel) ?></th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($customers as $customer): ?>
                    <?php
                    $customerId = (int) $customer['customer_id'];
                    $profileUrl = 'member.php?' . http_build_query(array(
                        'view' => 'profile',
                        'q' => $search,
                        'customer_id' => $customerId,
                    ));
                    ?>
                    <tr class="<?= $customerId === $selectedCustomerId ? 'member-selected-row' : '' ?>">
                        <td>
                            <div class="stack">
                                <strong><?= e((string) $customer['name']) ?></strong>
                                <span class="muted"><?= e((string) ($customer['phone'] ?? '-')) ?></span>
                                <span class="muted"><?= e((string) ($customer['plate_numbers'] ?? '-')) ?></span>
                            </div>
                        </td>
                        <td><span class="badge badge-secondary"><?= e(customer_group_label((string) ($customer['customer_group'] ?? 'member'))) ?></span></td>
                        <td><?= (int) ($customer['car_count'] ?? 0) ?></td>
                        <td><?= e(format_datetime($customer['latest_visit'] ? (string) $customer['latest_visit'] : null)) ?></td>
                        <td><a class="button button-secondary" href="<?= e($profileUrl) ?>"><?= e($openMemberLabel) ?></a></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </section>
    <?php endif; ?>

    <?php if ($selectedCustomer): ?>
        <?php
        $selectedLifetime = (float) ($selectedCustomer['lifetime_value'] ?? 0);
        $selectedPaid = (float) ($selectedCustomer['paid_amount'] ?? 0);
        $selectedOutstanding = max(0.0, $selectedLifetime - $selectedPaid);
        $selectedGroupLabel = customer_group_label((string) ($selectedCustomer['customer_group'] ?? 'member'));
        $selectedLevelLabel = customer_group_key((string) ($selectedCustomer['customer_group'] ?? 'member')) === 'guest'
            ? '-'
            : member_level((int) ($selectedCustomer['loyalty_points'] ?? 0));
        ?>

        <section class="grid grid-4" style="margin-top: 18px;">
            <article class="stat-card">
                <p class="stat-label"><?= e($customerGroupLabel) ?></p>
                <p class="stat-value"><?= e($selectedGroupLabel) ?></p>
            </article>
            <article class="stat-card">
                <p class="stat-label"><?= e($pointsLabel) ?></p>
                <p class="stat-value"><?= (int) $selectedCustomer['loyalty_points'] ?></p>
            </article>
            <article class="stat-card">
                <p class="stat-label"><?= e($visitsLabel) ?></p>
                <p class="stat-value"><?= (int) $selectedCustomer['visit_count'] ?></p>
            </article>
            <article class="stat-card">
                <p class="stat-label"><?= e($lifetimeValueLabel) ?></p>
                <p class="stat-value"><?= format_money($selectedLifetime) ?></p>
            </article>
        </section>

        <div class="content-grid" style="margin-top: 18px;">
            <section class="card">
                <div class="section-head">
                    <div>
                        <h2 class="section-title"><?= e($customerProfileTitle) ?></h2>
                        <p class="helper"><?= e($firstVisitLabel) ?>: <?= e(format_datetime($selectedCustomer['first_visit'] ? (string) $selectedCustomer['first_visit'] : null)) ?></p>
                    </div>
                </div>

                <div class="member-profile-grid">
                    <div class="stack">
                        <span class="muted"><?= e($customerLabel) ?></span>
                        <strong><?= e((string) $selectedCustomer['name']) ?></strong>
                    </div>
                    <div class="stack">
                        <span class="muted"><?= e($customerGroupLabel) ?></span>
                        <strong><?= e($selectedGroupLabel) ?></strong>
                    </div>
                    <div class="stack">
                        <span class="muted"><?= e($phoneLabel) ?></span>
                        <strong><?= e((string) ($selectedCustomer['phone'] ?? '-')) ?></strong>
                    </div>
                    <div class="stack">
                        <span class="muted"><?= e($emailLabel) ?></span>
                        <strong><?= e((string) ($selectedCustomer['email'] ?? '-')) ?></strong>
                    </div>
                    <div class="stack">
                        <span class="muted"><?= e($memberLevelLabel) ?></span>
                        <strong><?= e($selectedLevelLabel) ?></strong>
                    </div>
                    <div class="stack">
                        <span class="muted"><?= e($latestVisitLabel) ?></span>
                        <strong><?= e(format_datetime($selectedCustomer['latest_visit'] ? (string) $selectedCustomer['latest_visit'] : null)) ?></strong>
                    </div>
                </div>

                <div class="member-vehicle-list">
                    <div class="section-head member-section-head">
                        <div>
                            <h3 class="section-title"><?= e($vehiclesTitle) ?></h3>
                            <p class="helper"><?= e($vehicleHelper) ?></p>
                        </div>
                        <?php if ($selectedVehicle): ?>
                            <a class="button button-ghost" href="<?= e('member.php?' . http_build_query(array(
                                'view' => 'profile',
                                'customer_id' => (int) $selectedCustomer['customer_id'],
                                'q' => $search,
                            )) . '#member-package-services') ?>"><?= e($clearVehicleLabel) ?></a>
                        <?php endif; ?>
                    </div>
                    <?php if (empty($vehicles)): ?>
                        <div class="empty-state"><?= e($noVehiclesFoundLabel) ?></div>
                    <?php else: ?>
                        <?php foreach ($vehicles as $vehicle): ?>
                            <?php
                            $vehicleName = trim((string) (($vehicle['brand'] ?? '') . ' ' . ($vehicle['model'] ?? '')));
                            $vehicleCarId = (int) $vehicle['car_id'];
                            $vehicleUrl = 'member.php?' . http_build_query(array(
                                'view' => 'profile',
                                'customer_id' => (int) $selectedCustomer['customer_id'],
                                'car_id' => $vehicleCarId,
                                'q' => $search,
                            )) . '#member-package-services';
                            $vehicleCardClass = 'member-vehicle-card' . ($selectedCarId > 0 && $vehicleCarId === $selectedCarId ? ' is-selected' : '');
                            ?>
                            <a class="<?= e($vehicleCardClass) ?>" href="<?= e($vehicleUrl) ?>">
                                <span class="plate-card">
                                    <span class="plate"><?= e((string) $vehicle['plate_number']) ?></span>
                                    <?php if (trim((string) ($vehicle['province'] ?? '')) !== ''): ?>
                                        <span class="plate-province"><?= e((string) $vehicle['province']) ?></span>
                                    <?php endif; ?>
                                </span>
                                <div class="stack">
                                    <strong><?= e($vehicleName !== '' ? $vehicleName : $vehiclePendingLabel) ?></strong>
                                    <span><?= e((string) ($vehicle['color'] ?? '')) ?></span>
                                    <span class="muted"><?= e(strtr($visitCountValueLabel, array('{count}' => (string) (int) $vehicle['visit_count'], '{amount}' => format_money($vehicle['vehicle_value'])))) ?></span>
                                    <span class="muted"><?= e($latestShortLabel) ?>: <?= e(format_datetime($vehicle['latest_visit'] ? (string) $vehicle['latest_visit'] : null)) ?></span>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </section>

            <aside class="card">
                <h2 class="section-title"><?= e($paymentSummaryTitle) ?></h2>
                <div class="member-summary-list">
                    <div>
                        <span class="muted"><?= e($openedRevenueLabel) ?></span>
                        <strong><?= format_money($selectedLifetime) ?></strong>
                    </div>
                    <div>
                        <span class="muted"><?= e($paidReceivedLabel) ?></span>
                        <strong><?= format_money($selectedPaid) ?></strong>
                    </div>
                    <div>
                        <span class="muted"><?= e($outstandingLabel) ?></span>
                        <strong><?= format_money($selectedOutstanding) ?></strong>
                    </div>
                    <div>
                        <span class="muted"><?= e($vehiclesTitle) ?></span>
                        <strong><?= (int) $selectedCustomer['vehicle_count'] ?></strong>
                    </div>
                </div>

                <h3 class="section-title" style="margin-top: 18px;"><?= e($packageServiceViewTitle) ?></h3>
                <?php if ($selectedVehicle): ?>
                    <?php
                    $selectedVehicleName = trim((string) (($selectedVehicle['brand'] ?? '') . ' ' . ($selectedVehicle['model'] ?? '')));
                    $remainingPackageUses = 0;
                    foreach ($vehiclePackageServices as $packageServiceRow) {
                        $remainingPackageUses += max(0, (int) ($packageServiceRow['remaining_uses'] ?? 0));
                    }
                    ?>
                    <div class="member-summary-list">
                        <div>
                            <span class="muted"><?= e($selectedVehicleLabel) ?></span>
                            <strong><?= e((string) $selectedVehicle['plate_number']) ?></strong>
                        </div>
                        <div>
                            <span class="muted"><?= e($vehicleDetailsLabel) ?></span>
                            <strong><?= e($selectedVehicleName !== '' ? $selectedVehicleName : $vehiclePendingLabel) ?></strong>
                        </div>
                        <div>
                            <span class="muted"><?= e($packageServiceRowsLabel) ?></span>
                            <strong><?= count($vehiclePackageServices) ?></strong>
                        </div>
                        <div>
                            <span class="muted"><?= e($remainingUsesLabel) ?></span>
                            <strong><?= $remainingPackageUses ?></strong>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="empty-state" style="margin-top: 12px;"><?= e($chooseVehicleFirstLabel) ?></div>
                <?php endif; ?>
            </aside>
        </div>

        <section id="member-package-services" class="table-card" style="margin-top: 18px;">
            <div class="section-head" style="padding: 18px 18px 0;">
                <div>
                    <h2 class="section-title"><?= e($packageServiceTitle) ?><?= $selectedVehicle ? ' / ' . e((string) $selectedVehicle['plate_number']) : '' ?></h2>
                    <p class="helper">
                        <?php if ($selectedVehicle): ?>
                            <?= e($packageServiceVehicleHelper) ?>
                        <?php else: ?>
                            <?= e($packageServiceSelectHelper) ?>
                        <?php endif; ?>
                    </p>
                </div>
            </div>

            <?php if (!$selectedVehicle): ?>
                <div class="empty-state" style="margin: 18px;"><?= e($selectVehicleAboveLabel) ?></div>
            <?php elseif (empty($vehiclePackageServices)): ?>
                <div class="empty-state" style="margin: 18px;"><?= e($noPackageServicesLabel) ?></div>
            <?php else: ?>
                <table style="min-width: 920px;">
                    <thead>
                    <tr>
                        <th><?= e($packageLabel) ?></th>
                        <th><?= e($serviceLabel) ?></th>
                        <th><?= e($accessLabel) ?></th>
                        <th><?= e($includedLabel) ?></th>
                        <th><?= e($usedLabel) ?></th>
                        <th><?= e($remainingLabel) ?></th>
                        <th><?= e($purchasedLabel) ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($vehiclePackageServices as $packageServiceRow): ?>
                        <?php
                        $packageBill = (string) ((string) ($packageServiceRow['order_id'] ?? '') !== '' ? '#' . (int) ($packageServiceRow['order_id'] ?? 0) : '-');
                        $packageScopeNote = package_vehicle_scope_note($packageServiceRow);
                        ?>
                        <tr>
                            <td>
                                <strong><?= e((string) $packageServiceRow['package_name_snapshot']) ?></strong><br>
                                <small class="muted"><?= e($billLabel) ?> <?= e($packageBill) ?></small>
                            </td>
                            <td><?= e((string) $packageServiceRow['service_name_snapshot']) ?></td>
                            <td><?= e($packageScopeNote) ?></td>
                            <td><?= (int) ($packageServiceRow['included_uses'] ?? 0) ?></td>
                            <td><?= (int) ($packageServiceRow['used_uses'] ?? 0) ?></td>
                            <td><?= max(0, (int) ($packageServiceRow['remaining_uses'] ?? 0)) ?></td>
                            <td><?= e(format_datetime((string) ($packageServiceRow['created_at'] ?? ''))) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>

        <section class="table-card" style="margin-top: 18px;">
            <div class="section-head" style="padding: 18px 18px 0;">
                <div>
                    <h2 class="section-title"><?= e($packageUsageHistoryTitle) ?><?= $selectedVehicle ? ' / ' . e((string) $selectedVehicle['plate_number']) : '' ?></h2>
                    <p class="helper">
                        <?php if ($selectedVehicle): ?>
                            <?= e(strtr($packageUsageVehicleHelper, array('{count}' => (string) count($selectedVehiclePackageUsage)))) ?>
                        <?php else: ?>
                            <?= e($packageUsageSelectHelper) ?>
                        <?php endif; ?>
                    </p>
                </div>
            </div>

            <?php if (!$selectedVehicle): ?>
                <div class="empty-state" style="margin: 18px;"><?= e($packageUsageAppearsLabel) ?></div>
            <?php elseif (empty($selectedVehiclePackageUsage)): ?>
                <div class="empty-state" style="margin: 18px;"><?= e($noPackageUsageLabel) ?></div>
            <?php else: ?>
                <table style="min-width: 920px;">
                    <thead>
                    <tr>
                        <th><?= e($dateLabel) ?></th>
                        <th><?= e($packageLabel) ?></th>
                        <th><?= e($subServiceLabel) ?></th>
                        <th><?= e($usedLabel) ?></th>
                        <th><?= e($usedPlateLabel) ?></th>
                        <th><?= e($billLabel) ?></th>
                        <th><?= e($actionLabel) ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($selectedVehiclePackageUsage as $usageRow): ?>
                        <?php $usageBill = (string) ($usageRow['bill_number'] ?: '#' . (int) $usageRow['order_id']); ?>
                        <tr>
                            <td><?= e(format_datetime((string) ($usageRow['order_date'] ?? ''))) ?></td>
                            <td>
                                <?= e((string) $usageRow['package_name_snapshot']) ?><br>
                                <small class="muted"><?= e(package_vehicle_scope_note($usageRow)) ?></small>
                            </td>
                            <td><?= e((string) $usageRow['service_name_snapshot']) ?></td>
                            <td><?= (int) ($usageRow['used_uses'] ?? 0) ?></td>
                            <td><?= e((string) ($usageRow['used_plate_number'] ?? '-')) ?></td>
                            <td><strong><?= e($usageBill) ?></strong></td>
                            <td>
                                <?php if ($canOpenJobDetails): ?>
                                    <a class="button button-secondary" href="job_details.php?id=<?= (int) $usageRow['order_id'] ?>"><?= e($detailsLabel) ?></a>
                                <?php else: ?>
                                    <span class="muted">-</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>

        <section id="service-history" class="table-card" style="margin-top: 18px;">
            <div class="section-head" style="padding: 18px 18px 0;">
                <div>
                    <h2 class="section-title"><?= e($serviceHistoryTitle) ?><?= $selectedVehicle ? ' / ' . e((string) $selectedVehicle['plate_number']) : '' ?></h2>
                    <p class="helper"><?= e(strtr($selectedVehicle ? $serviceHistoryCountVehicleLabel : $serviceHistoryCountAllLabel, array('{count}' => (string) count($historyRows)))) ?></p>
                </div>
                <?php if ($selectedVehicle): ?>
                    <a class="button button-ghost" href="<?= e('member.php?' . http_build_query(array(
                        'view' => 'profile',
                        'customer_id' => (int) $selectedCustomer['customer_id'],
                        'q' => $search,
                    )) . '#service-history') ?>"><?= e($allVehiclesLabel) ?></a>
                <?php endif; ?>
            </div>

            <?php if (empty($historyRows)): ?>
                <div class="empty-state" style="margin: 18px;"><?= e($noServiceHistoryLabel) ?></div>
            <?php else: ?>
                <table class="member-history-table">
                    <thead>
                    <tr>
                        <th><?= e($dateLabel) ?></th>
                        <th><?= e($billNumberLabel) ?></th>
                        <th><?= e($vehicleLabel) ?></th>
                        <th><?= e($branchLabel) ?></th>
                        <th><?= e($servicesLabel) ?></th>
                        <th><?= e($statusLabel) ?></th>
                        <th><?= e($paymentLabel) ?></th>
                        <th><?= e($totalLabel) ?></th>
                        <th><?= e($paidLabel) ?></th>
                        <th><?= e($actionLabel) ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($historyRows as $history): ?>
                        <?php
                        $historyBrandModel = trim((string) (($history['brand'] ?? '') . ' ' . ($history['model'] ?? '')));
                        $historyBill = (string) ($history['bill_number'] ?: '#' . (int) $history['order_id']);
                        ?>
                        <tr>
                            <td><?= e(format_datetime((string) $history['order_date'])) ?></td>
                            <td><strong><?= e($historyBill) ?></strong></td>
                            <td>
                                <div class="stack">
                                    <strong><?= e((string) $history['plate_number']) ?></strong>
                                    <span class="muted"><?= e($historyBrandModel !== '' ? $historyBrandModel : $vehiclePendingLabel) ?></span>
                                </div>
                            </td>
                            <td><?= e((string) ($history['branch_name'] ?? '-')) ?></td>
                            <td><?= e((string) ($history['service_names'] ?? '-')) ?></td>
                            <td><span class="<?= e(status_class((string) $history['status'])) ?>"><?= e(status_label((string) $history['status'])) ?></span></td>
                            <td><span class="<?= e(payment_status_class((string) $history['payment_status'])) ?>"><?= e(payment_status_label((string) $history['payment_status'])) ?></span></td>
                            <td><?= format_money($history['total_price']) ?></td>
                            <td><?= format_money($history['paid_amount']) ?></td>
                            <td>
                                <?php if ($canOpenJobDetails): ?>
                                    <a class="button button-secondary" href="job_details.php?id=<?= (int) $history['order_id'] ?>"><?= e($detailsLabel) ?></a>
                                <?php else: ?>
                                    <span class="muted">-</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>
    <?php endif; ?>
<?php else: ?>
    <section class="card">
        <form method="GET" action="member.php" role="search">
            <input type="hidden" name="view" value="list">
            <div class="form-grid">
                <div class="field">
                    <label for="q"><?= e($searchMemberLabel) ?></label>
                    <input
                        id="q"
                        name="q"
                        type="text"
                        inputmode="text"
                        autocomplete="off"
                        value="<?= e($search) ?>"
                        placeholder="<?= e($memberSearchPlaceholder) ?>"
                    >
                    <p class="helper"><?= e($searchMemberHelper) ?></p>
                </div>
                <div class="field">
                    <label for="group"><?= e($customerGroupLabel) ?></label>
                    <select id="group" name="group">
                        <?php foreach (customer_group_options(true) as $groupValue => $groupLabel): ?>
                            <option value="<?= e($groupValue) ?>" <?= $selectedGroup === $groupValue ? 'selected' : '' ?>><?= e($groupLabel) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="helper"><?= e($groupSearchHelper) ?></p>
                </div>
            </div>
            <div class="actions">
                <button class="button" type="submit"><?= e($searchMembersLabel) ?></button>
                <a class="button button-ghost" href="member.php?view=list"><?= e($resetLabel) ?></a>
            </div>
        </form>
    </section>

    <?php if ($searchMessage !== ''): ?>
        <section class="empty-state" style="margin-top: 18px;"><?= e($searchMessage) ?></section>
    <?php elseif (!$hasSearch && $selectedGroup === 'all' && !$isEditMode && !$editRequested): ?>
        <section class="empty-state" style="margin-top: 18px;"><?= e($chooseGroupOrSearchLabel) ?></section>
    <?php else: ?>
        <section class="table-card" style="margin-top: 18px;">
            <div class="section-head" style="padding: 18px 18px 0;">
                <div>
                    <h2 class="section-title"><?= e($memberListTitle) ?></h2>
                    <p class="helper"><?= e(strtr($customerRecordCountLabel, array('{count}' => (string) count($customers)))) ?></p>
                </div>
            </div>

            <?php if (empty($customers)): ?>
                <div class="empty-state" style="margin: 18px;"><?= e($noCustomerMatchLabel) ?></div>
            <?php else: ?>
                <table>
                    <thead>
                    <tr>
                        <th><?= e($customerLabel) ?></th>
                        <th><?= e($groupLabel) ?></th>
                        <th><?= e($levelLabel) ?></th>
                        <th><?= e($pointsLabel) ?></th>
                        <th><?= e($carsLabel) ?></th>
                        <th><?= e($visitsLabel) ?></th>
                        <th><?= e($lifetimeValueLabel) ?></th>
                        <th><?= e($latestVisitLabel) ?></th>
                        <th><?= e($actionLabel) ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($customers as $customer): ?>
                        <?php
                        $customerId = (int) $customer['customer_id'];
                        $listParams = array('view' => 'list');
                        if ($search !== '') {
                            $listParams['q'] = $search;
                        }
                        if ($selectedGroup !== 'all') {
                            $listParams['group'] = $selectedGroup;
                        }

                        $editParams = $listParams;
                        $editParams['customer_id'] = $customerId;
                        $editParams['edit'] = 1;

                        $profileLookupValue = trim((string) ($customer['phone'] ?? ''));
                        if ($profileLookupValue === '') {
                            $plateOptions = array_values(array_filter(array_map('trim', explode(',', (string) ($customer['plate_numbers'] ?? '')))));
                            $profileLookupValue = $plateOptions[0] ?? '';
                        }

                        $profileUrl = '';
                        if ($canViewMemberInfo && $profileLookupValue !== '') {
                            $profileUrl = 'member.php?' . http_build_query(array(
                                'view' => 'profile',
                                'q' => $profileLookupValue,
                                'customer_id' => $customerId,
                            ));
                        }
                        ?>
                        <tr class="<?= $customerId === $selectedCustomerId ? 'member-selected-row' : '' ?>">
                            <td>
                                <div class="stack">
                                    <strong><?= e((string) $customer['name']) ?></strong>
                                    <span class="muted"><?= e((string) ($customer['phone'] ?? '-')) ?></span>
                                    <span class="muted"><?= e((string) ($customer['plate_numbers'] ?? '-')) ?></span>
                                </div>
                            </td>
                            <td><span class="badge badge-secondary"><?= e(customer_group_label((string) ($customer['customer_group'] ?? 'member'))) ?></span></td>
                            <td><?= e(customer_group_key((string) ($customer['customer_group'] ?? 'member')) === 'guest' ? '-' : member_level((int) $customer['loyalty_points'])) ?></td>
                            <td><?= (int) $customer['loyalty_points'] ?></td>
                            <td><?= (int) ($customer['car_count'] ?? 0) ?></td>
                            <td><?= (int) $customer['visit_count'] ?></td>
                            <td><?= format_money($customer['lifetime_value']) ?></td>
                            <td><?= e(format_datetime($customer['latest_visit'] ? (string) $customer['latest_visit'] : null)) ?></td>
                            <td>
                                <div class="actions-inline">
                                    <?php if ($profileUrl !== ''): ?>
                                        <a class="button button-secondary" href="<?= e($profileUrl) ?>"><?= e($viewInfoLabel) ?></a>
                                    <?php endif; ?>
                                    <?php if ($canEditMembers): ?>
                                        <a class="button button-ghost" href="<?= e('member.php?' . http_build_query($editParams) . '#member-edit-form') ?>"><?= e($editLabel) ?></a>
                                    <?php endif; ?>
                                    <?php if ($canDeleteMembers): ?>
                                        <form method="POST" action="../process/delete_member.php" onsubmit="return confirm('<?= e($deleteConfirmLabel) ?>');">
                                            <input type="hidden" name="customer_id" value="<?= $customerId ?>">
                                            <input type="hidden" name="view" value="list">
                                            <input type="hidden" name="q" value="<?= e($search) ?>">
                                            <input type="hidden" name="group" value="<?= e($selectedGroup) ?>">
                                            <button class="button button-danger" type="submit"><?= e($deleteLabel) ?></button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>
    <?php endif; ?>

    <?php if ($isEditMode && $selectedCustomer): ?>
        <?php
        $editName = old_value($oldInput, 'name', (string) ($selectedCustomer['name'] ?? ''));
        $editPhone = old_value($oldInput, 'phone', (string) ($selectedCustomer['phone'] ?? ''));
        $editEmail = old_value($oldInput, 'email', (string) ($selectedCustomer['email'] ?? ''));
        $editGroup = customer_group_filter_value(old_value($oldInput, 'customer_group', (string) ($selectedCustomer['customer_group'] ?? 'member')));
        if ($editGroup === 'all') {
            $editGroup = customer_group_key((string) ($selectedCustomer['customer_group'] ?? 'member'));
        }
        $closeParams = array('view' => 'list');
        if ($search !== '') {
            $closeParams['q'] = $search;
        }
        if ($selectedGroup !== 'all') {
            $closeParams['group'] = $selectedGroup;
        }
        ?>
        <section class="form-card" id="member-edit-form" style="margin-top: 18px;">
            <div class="section-head">
                <div>
                    <h2 class="section-title"><?= e($editMemberTitle) ?></h2>
                    <p class="helper"><?= e($editMemberHelper) ?></p>
                </div>
                <a class="button button-ghost" href="<?= e('member.php?' . http_build_query($closeParams)) ?>"><?= e($closeLabel) ?></a>
            </div>

            <form method="POST" action="../process/save_member.php">
                <input type="hidden" name="customer_id" value="<?= (int) $selectedCustomer['customer_id'] ?>">
                <input type="hidden" name="view" value="list">
                <input type="hidden" name="q" value="<?= e($search) ?>">
                <input type="hidden" name="group" value="<?= e($selectedGroup) ?>">

                <div class="form-grid">
                    <div class="field">
                        <label for="member_name"><?= e($customerNameLabel) ?></label>
                        <input id="member_name" name="name" type="text" value="<?= e($editName) ?>" required>
                    </div>

                    <div class="field">
                        <label for="member_phone"><?= e($phoneLabel) ?></label>
                        <input id="member_phone" name="phone" type="text" value="<?= e($editPhone) ?>">
                    </div>

                    <div class="field">
                        <label for="member_email"><?= e($emailLabel) ?></label>
                        <input id="member_email" name="email" type="email" value="<?= e($editEmail) ?>">
                    </div>

                    <div class="field">
                        <label for="member_group"><?= e($customerGroupLabel) ?></label>
                        <select id="member_group" name="customer_group">
                            <?php foreach (customer_group_options(false) as $groupValue => $groupLabel): ?>
                                <option value="<?= e($groupValue) ?>" <?= $editGroup === $groupValue ? 'selected' : '' ?>><?= e($groupLabel) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="actions">
                    <button class="button button-accent" type="submit"><?= e($saveMemberLabel) ?></button>
                    <a class="button button-ghost" href="<?= e('member.php?' . http_build_query($closeParams)) ?>"><?= e($cancelLabel) ?></a>
                </div>
            </form>
        </section>
    <?php elseif ($editRequested && !$canEditMembers): ?>
        <section class="empty-state" style="margin-top: 18px;"><?= e($noEditPermissionLabel) ?></section>
    <?php elseif ($isEditMode): ?>
        <section class="empty-state" style="margin-top: 18px;"><?= e($memberLoadFailedLabel) ?></section>
    <?php endif; ?>
<?php endif; ?>

<?php render_page_end(); ?>
