<?php
declare(strict_types=1);

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

require_login($conn);

if (!can_access_data_maintenance($conn)) {
    redirect_with_flash(
        'dashboard.php',
        'error',
        localized_flash_message(
            'คุณไม่มีสิทธิ์เข้าถึงฟังก์ชันนี้',
            'You do not have permission to access that function.'
        )
    );
}

function data_maintenance_text(string $thaiText, string $englishText): string
{
    return ui_text($thaiText, $englishText);
}

function data_maintenance_output_map(): array
{
    return array(
        'Data Maintenance Functions' => 'ฟังก์ชันดูแลข้อมูล',
        'Data Maintenance' => 'ดูแลข้อมูลระบบ',
        'Preview, export snapshot and clear only selected data ranges. Every action requires typed confirmation before execution.' => 'พรีวิว ส่งออกสแนปช็อต และลบเฉพาะข้อมูลตามช่วงที่เลือก ทุกคำสั่งต้องพิมพ์ยืนยันก่อนดำเนินการ',
        'Manage System' => 'จัดการระบบ',
        'Safety rules' => 'ข้อควรระวัง',
        'Use the smallest date range possible. Snapshot export is created before each clear action. Customer, car and master data are never removed by these tools.' => 'เลือกช่วงวันที่ให้แคบที่สุด ระบบจะสร้างสแนปช็อตก่อนล้างข้อมูลทุกครั้ง และเครื่องมือนี้จะไม่ลบข้อมูลลูกค้า รถ และข้อมูลตั้งต้น',
        'Database backup files are stored inside `storage/database_backups` and restore should only use files created by this system.' => 'ไฟล์สำรองฐานข้อมูลถูกเก็บไว้ใน `storage/database_backups` และควรใช้กู้คืนเฉพาะไฟล์ที่สร้างโดยระบบนี้เท่านั้น',
        'Clear Log does not allow deleting log rows from today and is capped at 50,000 rows per run.' => 'ล้าง Log จะไม่อนุญาตให้ลบรายการของวันนี้ และจำกัดสูงสุด 50,000 แถวต่อครั้ง',
        'Clear Booking / Queue only removes unpaid booking rows that have no payment, loyalty, package purchase or package usage side effects.' => 'ล้าง Booking / Queue จะลบได้เฉพาะรายการที่ยังไม่ชำระและไม่มีผลกระทบกับการชำระเงิน แต้มสะสม การซื้อแพ็กเกจ หรือการใช้แพ็กเกจ',
        'Clear Sale only removes paid and closed sale rows after reversing loyalty/package effects and blocks bills that already affected later package usage.' => 'ล้าง Sale จะลบได้เฉพาะบิลที่ปิดและชำระครบแล้ว หลังย้อนผลกระทบของแต้มสะสมและแพ็กเกจ พร้อมบล็อกบิลที่ไปกระทบการใช้แพ็กเกจในภายหลัง',
        'Reset Operational Data removes customers, cars, bills, queue, payments, package balances and loyalty history across the whole system, but keeps service setup, positions, employees and Quick Service settings.' => 'รีเซ็ตข้อมูลการใช้งานจะลบลูกค้า รถ บิล คิว การชำระเงิน ยอดคงเหลือแพ็กเกจ และประวัติแต้มสะสมทั้งระบบ แต่จะคงค่าตั้งต้นบริการ ตำแหน่ง พนักงาน และการตั้งค่า Quick Service ไว้',
        'Quick Service guest cleanup only clears old default placeholder values from guest vehicle type, brand and model. It does not delete bills, customers or service history.' => 'การล้างข้อมูลลูกค้า Guest ของ Quick Service จะล้างเฉพาะค่าเริ่มต้นเก่าในประเภทรถ ยี่ห้อ และรุ่นเท่านั้น ไม่ได้ลบบิล ลูกค้า หรือประวัติบริการ',
        'Database Structure Sync only applies safe structure additions automatically: create missing tables, add missing columns, indexes and foreign keys. Changed columns or destructive drops stay in manual review.' => 'Database Structure Sync จะอัปเดตอัตโนมัติเฉพาะโครงสร้างที่ปลอดภัย เช่น สร้างตารางที่หาย เพิ่มคอลัมน์ ดัชนี และ foreign key ส่วนคอลัมน์ที่เปลี่ยนหรือการลบที่เสี่ยงจะคงไว้ให้ตรวจเอง',
        'Open a maintenance function from the list below. Each function keeps its own preview, confirm and execute flow.' => 'เลือกฟังก์ชันดูแลข้อมูลจากรายการด้านล่าง แต่ละฟังก์ชันมี flow พรีวิว ยืนยัน และสั่งทำงานแยกกัน',
        'Overview' => 'ภาพรวม',
        'Open function' => 'เปิดฟังก์ชัน',
        'Backup & Restore' => 'สำรองและกู้คืนฐานข้อมูล',
        'Backup the current database or restore from saved SQL files.' => 'สำรองฐานข้อมูลปัจจุบันหรือกู้คืนจากไฟล์ SQL ที่บันทึกไว้',
        'Structure Sync' => 'ซิงก์โครงสร้างฐานข้อมูล',
        'Compare Source DB and Target DB, download SQL patch, and apply reviewed changes.' => 'เปรียบเทียบ Source DB กับ Target DB ดาวน์โหลด SQL patch และอัปเดตเฉพาะรายการที่ตรวจแล้ว',
        'Clear Log' => 'ล้าง Log',
        'Remove selected audit log rows only.' => 'ลบเฉพาะรายการ audit log ที่เลือก',
        'Clear Booking / Queue' => 'ล้าง Booking / Queue',
        'Remove only unpaid booking queue rows that are still safe to clear.' => 'ลบเฉพาะรายการ booking/queue ที่ยังไม่ชำระและปลอดภัยต่อการล้าง',
        'Clear Sale' => 'ล้าง Sale',
        'Remove selected sale rows after validating payment, loyalty and package side effects.' => 'ลบรายการ sale ที่เลือกหลังตรวจสอบผลกระทบด้านการชำระเงิน แต้มสะสม และแพ็กเกจ',
        'Reset Operational Data' => 'รีเซ็ตข้อมูลการใช้งาน',
        'Start fresh by clearing operational usage data while keeping setup and employees.' => 'เริ่มต้นใหม่ด้วยการล้างข้อมูลการใช้งาน โดยคงค่าตั้งต้นและพนักงานไว้',
        'Quick Service Guest Cleanup' => 'ล้างข้อมูล Guest ใน Quick Service',
        'Clear legacy placeholder values from Quick Service guest vehicle data.' => 'ล้างค่า placeholder เก่าจากข้อมูลรถลูกค้า Guest ของ Quick Service',
        'Database Backup and Restore' => 'สำรองและกู้คืนฐานข้อมูล',
        'Backup exports the full database to SQL. Restore always creates an automatic pre-restore backup first.' => 'การสำรองจะส่งออกฐานข้อมูลทั้งหมดเป็น SQL และการกู้คืนจะสร้างไฟล์สำรองก่อนกู้คืนอัตโนมัติทุกครั้ง',
        'Backup directory' => 'โฟลเดอร์สำรอง',
        'Backup method' => 'วิธีสำรอง',
        'Restore method' => 'วิธีกู้คืน',
        'Saved backups' => 'ไฟล์สำรองที่มีอยู่',
        'PHP fallback' => 'PHP fallback',
        'Backup Database' => 'สำรองฐานข้อมูล',
        'Backup directory is not writable. Backup Database cannot run yet.' => 'โฟลเดอร์สำรองยังเขียนไม่ได้ จึงยังไม่สามารถสั่งสำรองฐานข้อมูลได้',
        'Production fallback is active. The system will create SQL backups directly from PHP without using mysqldump.' => 'ระบบกำลังใช้โหมด fallback สำหรับ production โดยจะสร้างไฟล์สำรอง SQL ผ่าน PHP โดยไม่ใช้ mysqldump',
        'Create Database Backup' => 'สร้างไฟล์สำรองฐานข้อมูล',
        'Restore Database' => 'กู้คืนฐานข้อมูล',
        'No SQL backup files were found in the backup directory yet.' => 'ยังไม่พบไฟล์ SQL backup ในโฟลเดอร์สำรอง',
        'Restore Database cannot run yet.' => 'ยังไม่สามารถสั่งกู้คืนฐานข้อมูลได้',
        'Production fallback is active. The system will restore SQL files directly from PHP when mysql client is unavailable.' => 'ระบบกำลังใช้โหมด fallback สำหรับ production โดยจะกู้คืนไฟล์ SQL ผ่าน PHP เมื่อไม่มี mysql client',
        'Select backup file' => 'เลือกไฟล์สำรอง',
        'Select backup' => 'เลือกไฟล์สำรอง',
        'Preview Restore' => 'พรีวิวการกู้คืน',
        'Selected backup file was not found.' => 'ไม่พบไฟล์สำรองที่เลือก',
        'Restore preview' => 'พรีวิวการกู้คืน',
        'The system will create a pre-restore backup automatically before importing this file.' => 'ระบบจะสร้างไฟล์สำรองก่อนกู้คืนอัตโนมัติก่อนนำเข้าไฟล์นี้',
        'Backup file' => 'ไฟล์สำรอง',
        'Size' => 'ขนาด',
        'Modified' => 'แก้ไขล่าสุด',
        'Available backup files' => 'ไฟล์สำรองที่พร้อมใช้งาน',
        'File' => 'ไฟล์',
        'Database Structure Sync' => 'ซิงก์โครงสร้างฐานข้อมูล',
        'Compare structure between Source DB (A) and Target DB (B), generate SQL patch, then apply only safe updates to B after an automatic backup.' => 'เปรียบเทียบโครงสร้างระหว่าง Source DB (A) กับ Target DB (B) สร้าง SQL patch และอัปเดตเฉพาะรายการที่ปลอดภัยไปยัง B หลังสำรองข้อมูลอัตโนมัติ',
        'Source DB (A)' => 'Source DB (A)',
        'Target DB (B)' => 'Target DB (B)',
        'Use current system database connection' => 'ใช้การเชื่อมต่อฐานข้อมูลของระบบปัจจุบัน',
        'Host' => 'โฮสต์',
        'Port' => 'พอร์ต',
        'Username' => 'ชื่อผู้ใช้',
        'Password' => 'รหัสผ่าน',
        'Database' => 'ฐานข้อมูล',
        'Compare structure / Generate SQL' => 'เปรียบเทียบโครงสร้าง / สร้าง SQL',
        'Missing tables' => 'ตารางที่ขาด',
        'Missing columns' => 'คอลัมน์ที่ขาด',
        'Changed columns' => 'คอลัมน์ที่เปลี่ยน',
        'Missing views' => 'วิวที่ขาด',
        'Missing triggers' => 'ทริกเกอร์ที่ขาด',
        'Missing routines' => 'รูทีนที่ขาด',
        'Safe SQL' => 'Safe SQL',
        'Manual review' => 'รายการต้องตรวจเอง',
        'Manual apply items' => 'รายการ manual apply',
        'Warnings' => 'คำเตือน',
        'Source summary' => 'สรุปฝั่ง Source',
        'Target summary' => 'สรุปฝั่ง Target',
        'Missing tables in target' => 'ตารางที่ขาดใน Target',
        'Manual review required' => 'จำเป็นต้องตรวจเอง',
        'These differences were detected but will not be applied automatically because they may be destructive or require manual review.' => 'ระบบพบความแตกต่างเหล่านี้แต่จะยังไม่อัปเดตอัตโนมัติ เพราะอาจมีความเสี่ยงหรือจำเป็นต้องตรวจเอง',
        'Changed indexes' => 'ดัชนีที่เปลี่ยน',
        'Changed foreign keys' => 'foreign key ที่เปลี่ยน',
        'Changed table options' => 'table options ที่เปลี่ยน',
        'Extra tables in target' => 'ตารางส่วนเกินใน Target',
        'Extra columns in target' => 'คอลัมน์ส่วนเกินใน Target',
        'Extra indexes in target' => 'ดัชนีส่วนเกินใน Target',
        'Extra foreign keys in target' => 'foreign key ส่วนเกินใน Target',
        'Changed views' => 'วิวที่เปลี่ยน',
        'Extra views in target' => 'วิวส่วนเกินใน Target',
        'Changed triggers' => 'ทริกเกอร์ที่เปลี่ยน',
        'Extra triggers in target' => 'ทริกเกอร์ส่วนเกินใน Target',
        'Changed routines' => 'รูทีนที่เปลี่ยน',
        'Extra routines in target' => 'รูทีนส่วนเกินใน Target',
        'Download compare JSON' => 'ดาวน์โหลด compare JSON',
        'Download safe SQL' => 'ดาวน์โหลด safe SQL',
        'Download manual-only patch' => 'ดาวน์โหลด manual-only patch',
        'Download full patch' => 'ดาวน์โหลด full patch',
        'Safe SQL patch' => 'Safe SQL patch',
        'Manual SQL / review notes' => 'Manual SQL / review notes',
        'Select manual SQL items to apply' => 'เลือกรายการ manual SQL ที่จะอัปเดต',
        'Choose only the reviewed items you want to apply to Target DB (B). A backup will be created before execution.' => 'เลือกเฉพาะรายการที่ตรวจแล้วและต้องการอัปเดตไปยัง Target DB (B) ระบบจะสร้างไฟล์สำรองก่อนทำงาน',
        'Reset bill and queue counters' => 'รีเซ็ตเลขที่บิลและลำดับคิว',
        'Rows to clear' => 'จำนวนแถวที่จะล้าง',
        'Bills' => 'จำนวนบิล',
        'Customers' => 'ลูกค้า',
        'Cars' => 'รถ',
        'Selected data to clear' => 'ข้อมูลที่จะล้าง',
        'Table group' => 'กลุ่มตาราง',
        'Rows' => 'จำนวนแถว',
        'Kept after reset' => 'ข้อมูลที่คงไว้หลังรีเซ็ต',
        'Logs kept' => 'Log ที่คงไว้',
        'Log group' => 'กลุ่ม Log',
        'Current bill distribution' => 'การกระจายบิลปัจจุบัน',
        'Source' => 'แหล่งที่มา',
        'Total' => 'ยอดรวม',
        'A full database backup will be created automatically before deletion starts.' => 'ระบบจะสร้างไฟล์สำรองฐานข้อมูลเต็มรูปแบบอัตโนมัติก่อนเริ่มลบข้อมูล',
        'Cleanup Quick Service Guest Vehicle Data' => 'ล้างข้อมูลรถ Guest ของ Quick Service',
        'Preview Quick Service Guest Cleanup' => 'พรีวิวการล้างข้อมูล Guest ของ Quick Service',
        'Vehicle rows' => 'จำนวนรายการรถ',
        'Vehicle type to clear' => 'ประเภทรถที่จะล้าง',
        'Brand / model to clear' => 'ยี่ห้อ / รุ่นที่จะล้าง',
        'Affected guest vehicles' => 'รถ Guest ที่ได้รับผลกระทบ',
        'Only the highlighted placeholder fields will be cleared.' => 'ระบบจะล้างเฉพาะฟิลด์ placeholder ที่ถูกทำเครื่องหมายไว้',
        'Customer' => 'ลูกค้า',
        'Plate' => 'ทะเบียน',
        'Province' => 'จังหวัด',
        'Vehicle type' => 'ประเภทรถ',
        'Brand' => 'ยี่ห้อ',
        'Model' => 'รุ่น',
        'Quick Service branches' => 'สาขา Quick Service',
        'Execute Quick Service Guest Cleanup' => 'เริ่มล้างข้อมูล Guest ของ Quick Service',
        'Remove only `audit_logs` rows. Today is always blocked.' => 'ลบเฉพาะรายการใน `audit_logs` เท่านั้น และจะบล็อกข้อมูลของวันนี้เสมอ',
        'Date from' => 'วันที่เริ่มต้น',
        'Date to' => 'วันที่สิ้นสุด',
        'Module' => 'โมดูล',
        'Action' => 'การทำงาน',
        'All branches' => 'ทุกสาขา',
        'Preview Clear Log' => 'พรีวิวการล้าง Log',
        'Matched logs' => 'Log ที่ตรงเงื่อนไข',
        'Row cap' => 'เพดานจำนวนแถว',
        'By module' => 'แยกตามโมดูล',
        'By action' => 'แยกตามการทำงาน',
        'No rows' => 'ไม่มีข้อมูล',
        'Execute Clear Log' => 'เริ่มล้าง Log',
        'Only unpaid booking rows in Waiting or Cancelled status can be removed here.' => 'ลบได้เฉพาะรายการ booking ที่ยังไม่ชำระและอยู่ในสถานะ Waiting หรือ Cancelled เท่านั้น',
        'Select branch' => 'เลือกสาขา',
        'Preview Clear Booking / Queue' => 'พรีวิวการล้าง Booking / Queue',
        'Matched' => 'ตรงเงื่อนไข',
        'Eligible' => 'ล้างได้',
        'Blocked' => 'ถูกบล็อก',
        'Eligible bills' => 'บิลที่ล้างได้',
        'Status' => 'สถานะ',
        'No eligible bills' => 'ไม่มีบิลที่ล้างได้',
        'Blocked reasons' => 'สาเหตุที่ถูกบล็อก',
        'Reason' => 'เหตุผล',
        'No blocked reasons' => 'ไม่มีสาเหตุที่ถูกบล็อก',
        'Blocked bills' => 'บิลที่ถูกบล็อก',
        'Reasons' => 'เหตุผล',
        'Execute Clear Booking / Queue' => 'เริ่มล้าง Booking / Queue',
        'Use this only for closed paid bills that must be removed after reversing financial side effects.' => 'ใช้สำหรับบิลที่ปิดและชำระครบแล้วเท่านั้น เมื่อจำเป็นต้องลบหลังย้อนผลกระทบทางการเงิน',
        'Order source' => 'แหล่งที่มาของบิล',
        'Both' => 'ทั้งสองแบบ',
        'Booking' => 'Booking',
        'Quick Service' => 'Quick Service',
        'Preview Clear Sale' => 'พรีวิวการล้าง Sale',
        'Payment total' => 'ยอดชำระรวม',
        'Reverse loyalty' => 'แต้มที่ต้องย้อนกลับ',
        'Reverse package usage' => 'การใช้แพ็กเกจที่ต้องย้อนกลับ',
        'Paid' => 'ชำระแล้ว',
        'Execute Clear Sale' => 'เริ่มล้าง Sale',
        'Reset' => 'รีเซ็ต',
    );
}

function data_maintenance_localize_output(string $html): string
{
    if (current_language() !== 'th') {
        return $html;
    }

    return strtr($html, data_maintenance_output_map());
}

function data_maintenance_order_source_label(string $source): string
{
    if ($source === 'quick_service') {
        return data_maintenance_text('ควิกเซอร์วิส', 'Quick Service');
    }

    if ($source === 'booking') {
        return data_maintenance_text('งานจอง', 'Booking');
    }

    if ($source === 'both') {
        return data_maintenance_text('ทั้งสองแบบ', 'Both');
    }

    return $source;
}

function data_maintenance_module_labels(): array
{
    return array(
        '' => data_maintenance_text('ทุกโมดูล', 'All modules'),
        'bill' => data_maintenance_text('บิล', 'Bill'),
        'booking' => data_maintenance_text('Booking', 'Booking'),
        'car' => data_maintenance_text('รถ', 'Car'),
        'customer' => data_maintenance_text('ลูกค้า', 'Customer'),
        'employee' => data_maintenance_text('พนักงาน', 'Employee'),
        'job' => data_maintenance_text('งาน / คิว', 'Job / Queue'),
        'loyalty' => data_maintenance_text('แต้มสะสม', 'Loyalty'),
        'package' => data_maintenance_text('แพ็กเกจ', 'Package'),
        'payment' => data_maintenance_text('การชำระเงิน', 'Payment'),
        'position' => data_maintenance_text('ตำแหน่ง', 'Position'),
        'service' => data_maintenance_text('บริการ', 'Service'),
        'service_category' => data_maintenance_text('หมวดหมู่', 'Category'),
        'service_group' => data_maintenance_text('กลุ่มบริการ', 'Service Group'),
        'void' => data_maintenance_text('ยกเลิกบิล', 'Void'),
    );
}

function data_maintenance_action_labels(): array
{
    return array(
        '' => data_maintenance_text('ทุกการทำงาน', 'All actions'),
        'create' => data_maintenance_text('สร้าง', 'Create'),
        'update' => data_maintenance_text('อัปเดต', 'Update'),
        'delete' => data_maintenance_text('ลบ', 'Delete'),
        'cancel' => data_maintenance_text('ยกเลิก', 'Cancel'),
        'reverse' => data_maintenance_text('ย้อนกลับ', 'Reverse'),
        'receive' => data_maintenance_text('รับชำระเงิน', 'Receive payment'),
        'status' => data_maintenance_text('เปลี่ยนสถานะ', 'Status change'),
        'usage' => data_maintenance_text('ใช้แพ็กเกจ', 'Package usage'),
        'hold' => data_maintenance_text('พักรายการ', 'Hold'),
    );
}

function data_maintenance_reason_label(string $reason): string
{
    $map = array(
        'payment_status_not_unpaid' => data_maintenance_text('สถานะชำระเงินไม่ใช่ Unpaid', 'Payment status is not Unpaid'),
        'has_payment' => data_maintenance_text('มีรายการชำระเงิน', 'Has payment rows'),
        'has_loyalty' => data_maintenance_text('มีรายการแต้มสะสม', 'Has loyalty rows'),
        'has_package_purchase' => data_maintenance_text('มีการซื้อแพ็กเกจ', 'Has package purchases'),
        'has_package_usage' => data_maintenance_text('มีการใช้แพ็กเกจ', 'Has package usage'),
        'payment_not_fully_closed' => data_maintenance_text('สถานะชำระเงินไม่ใช่ Paid', 'Payment status is not Paid'),
        'has_non_earn_loyalty' => data_maintenance_text('มีรายการแต้มสะสมที่ไม่ใช่ Earn', 'Has loyalty rows that are not Earn'),
        'package_purchase_already_used' => data_maintenance_text('แพ็กเกจจากบิลนี้ถูกนำไปใช้ภายหลังแล้ว', 'Package from this bill was already used later'),
    );

    return $map[$reason] ?? $reason;
}

function data_maintenance_checkbox_checked(array $values, string $value): string
{
    return in_array($value, $values, true) ? ' checked' : '';
}

function data_maintenance_hidden_array(string $name, array $values): string
{
    $html = '';
    foreach ($values as $value) {
        $html .= '<input type="hidden" name="' . e($name) . '[]" value="' . e((string) $value) . '">' . PHP_EOL;
    }

    return $html;
}

function data_maintenance_hidden_structure_config(string $prefix, array $config): string
{
    $fields = array('use_current', 'host', 'port', 'user', 'pass', 'database');
    $html = '';

    foreach ($fields as $field) {
        $value = $field === 'use_current'
            ? (!empty($config[$field]) ? '1' : '0')
            : (string) ($config[$field] ?? '');
        $html .= '<input type="hidden" name="' . e($prefix . '[' . $field . ']') . '" value="' . e($value) . '">' . PHP_EOL;
    }

    return $html;
}

function data_maintenance_section_definitions(mysqli $conn): array
{
    $sections = array();

    if (can_access($conn, 'maintenance_backup_database') || can_access($conn, 'maintenance_restore_database')) {
        $sections['backup_restore'] = array(
            'title' => data_maintenance_text('สำรองและกู้คืนฐานข้อมูล', 'Backup & Restore'),
            'description' => data_maintenance_text('สำรองฐานข้อมูลปัจจุบันหรือกู้คืนจากไฟล์ SQL ที่บันทึกไว้', 'Backup the current database or restore from saved SQL files.'),
        );
    }

    if (can_access($conn, 'maintenance_compare_database_structure') || can_access($conn, 'maintenance_apply_database_structure')) {
        $sections['structure_sync'] = array(
            'title' => data_maintenance_text('ซิงก์โครงสร้างฐานข้อมูล', 'Structure Sync'),
            'description' => data_maintenance_text('เปรียบเทียบ Source DB กับ Target DB ดาวน์โหลด SQL patch และอัปเดตเฉพาะรายการที่ตรวจแล้ว', 'Compare Source DB and Target DB, download SQL patch, and apply reviewed changes.'),
        );
    }

    if (can_access($conn, 'maintenance_clear_log')) {
        $sections['clear_log'] = array(
            'title' => data_maintenance_text('ล้าง Log', 'Clear Log'),
            'description' => data_maintenance_text('ลบเฉพาะรายการ audit log ที่เลือก', 'Remove selected audit log rows only.'),
        );
    }

    if (can_access($conn, 'maintenance_clear_booking_queue')) {
        $sections['clear_booking_queue'] = array(
            'title' => data_maintenance_text('ล้าง Booking / Queue', 'Clear Booking / Queue'),
            'description' => data_maintenance_text('ลบเฉพาะรายการ booking/queue ที่ยังไม่ชำระและปลอดภัยต่อการล้าง', 'Remove only unpaid booking queue rows that are still safe to clear.'),
        );
    }

    if (can_access($conn, 'maintenance_clear_sale')) {
        $sections['clear_sale'] = array(
            'title' => data_maintenance_text('ล้าง Sale', 'Clear Sale'),
            'description' => data_maintenance_text('ลบรายการ sale ที่เลือกหลังตรวจสอบผลกระทบด้านการชำระเงิน แต้มสะสม และแพ็กเกจ', 'Remove selected sale rows after validating payment, loyalty and package side effects.'),
        );
    }

    if (can_access($conn, 'maintenance_reset_operational_data')) {
        $sections['reset_operational'] = array(
            'title' => data_maintenance_text('รีเซ็ตข้อมูลการใช้งาน', 'Reset Operational Data'),
            'description' => data_maintenance_text('เริ่มต้นใหม่ด้วยการล้างข้อมูลการใช้งาน โดยคงค่าตั้งต้นและพนักงานไว้', 'Start fresh by clearing operational usage data while keeping setup and employees.'),
        );
    }

    if (can_access($conn, 'maintenance_cleanup_quick_service_guest')) {
        $sections['cleanup_guest'] = array(
            'title' => data_maintenance_text('ล้างข้อมูล Guest ใน Quick Service', 'Quick Service Guest Cleanup'),
            'description' => data_maintenance_text('ล้างค่า placeholder เก่าจากข้อมูลรถลูกค้า Guest ของ Quick Service', 'Clear legacy placeholder values from Quick Service guest vehicle data.'),
        );
    }

    return $sections;
}

function data_maintenance_section_url(string $section = 'home', array $extra = array()): string
{
    $params = $extra;
    if ($section !== 'home') {
        $params['section'] = $section;
    }

    $query = http_build_query($params);
    return 'data_maintenance.php' . ($query !== '' ? '?' . $query : '');
}

$branchOptions = maintenance_branch_options($conn);
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
$logDefaultTo = $yesterday;
$logDefaultFrom = date('Y-m-01', strtotime($logDefaultTo));
$bookingDefaultFrom = date('Y-m-01');
$saleDefaultFrom = date('Y-m-01');

$previewType = trim((string) ($_GET['preview'] ?? ''));
$maintenanceSections = data_maintenance_section_definitions($conn);
$maintenanceSection = trim((string) ($_GET['section'] ?? 'home'));
if ($maintenanceSection !== 'home' && !isset($maintenanceSections[$maintenanceSection])) {
    $maintenanceSection = 'home';
}

$clearLogInput = array(
    'date_from' => trim((string) ($_GET['log_date_from'] ?? $logDefaultFrom)),
    'date_to' => trim((string) ($_GET['log_date_to'] ?? $logDefaultTo)),
    'module' => trim((string) ($_GET['log_module'] ?? '')),
    'action' => trim((string) ($_GET['log_action'] ?? '')),
    'branch_name' => trim((string) ($_GET['log_branch_name'] ?? '')),
);

$clearBookingInput = array(
    'branch_name' => trim((string) ($_GET['booking_branch_name'] ?? '')),
    'date_from' => trim((string) ($_GET['booking_date_from'] ?? $bookingDefaultFrom)),
    'date_to' => trim((string) ($_GET['booking_date_to'] ?? $today)),
    'statuses' => maintenance_selected_values($_GET['booking_statuses'] ?? maintenance_allowed_booking_statuses()),
);

$clearSaleInput = array(
    'branch_name' => trim((string) ($_GET['sale_branch_name'] ?? '')),
    'date_from' => trim((string) ($_GET['sale_date_from'] ?? $saleDefaultFrom)),
    'date_to' => trim((string) ($_GET['sale_date_to'] ?? $today)),
    'order_source' => trim((string) ($_GET['sale_order_source'] ?? 'both')),
    'statuses' => maintenance_selected_values($_GET['sale_statuses'] ?? maintenance_allowed_sale_statuses()),
);

$resetOperationalDefaults = maintenance_reset_operational_default_input();
$resetOperationalInput = array(
    'include_logs' => ((string) ($_GET['reset_include_logs'] ?? ($resetOperationalDefaults['include_logs'] ? '1' : '0'))) === '1',
    'reset_counters' => ((string) ($_GET['reset_reset_counters'] ?? ($resetOperationalDefaults['reset_counters'] ? '1' : '0'))) === '1',
);

$databaseCapabilities = maintenance_database_capabilities($conn);
$databaseBackups = maintenance_database_backup_files();
$restoreBackupFileName = trim((string) ($_GET['restore_backup_file'] ?? ''));
$restoreBackupPreview = null;
if ($previewType === 'restore_database' && $restoreBackupFileName !== '' && can_access($conn, 'maintenance_restore_database')) {
    $restoreBackupPreview = maintenance_database_find_backup_file($restoreBackupFileName);
}

$structureSyncSourceDefaults = maintenance_structure_sync_current_config($conn);
$structureSyncTargetDefaults = maintenance_structure_sync_custom_defaults($conn);
$structureSyncSourceInput = maintenance_structure_sync_input($_POST['structure_source'] ?? array(), $structureSyncSourceDefaults);
$structureSyncTargetInput = maintenance_structure_sync_input($_POST['structure_target'] ?? array(), $structureSyncTargetDefaults);
$structureSyncPreview = null;
$structureSyncPreviewError = '';

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && (string) ($_POST['maintenance_preview_type'] ?? '') === 'database_structure_sync'
    && can_access($conn, 'maintenance_compare_database_structure')
) {
    try {
        $structureSyncPreview = maintenance_structure_sync_preview($structureSyncSourceInput, $structureSyncTargetInput, $conn);
    } catch (Throwable $exception) {
        $structureSyncPreviewError = $exception->getMessage() !== ''
            ? $exception->getMessage()
            : data_maintenance_text('การพรีวิว Database Structure Sync ล้มเหลว', 'Database Structure Sync preview failed.');
    }
}

$clearLogPreview = null;
$clearBookingPreview = null;
$clearSalePreview = null;
$resetOperationalPreview = null;
$quickServiceGuestCleanupPreview = null;

if ($previewType === 'clear_log' && can_access($conn, 'maintenance_clear_log')) {
    $clearLogPreview = maintenance_preview_clear_log($conn, $clearLogInput);
}

if ($previewType === 'clear_booking_queue' && can_access($conn, 'maintenance_clear_booking_queue')) {
    $clearBookingPreview = maintenance_preview_clear_booking_queue($conn, $clearBookingInput);
}

if ($previewType === 'clear_sale' && can_access($conn, 'maintenance_clear_sale')) {
    $clearSalePreview = maintenance_preview_clear_sale($conn, $clearSaleInput);
}

if ($previewType === 'reset_operational_data' && can_access($conn, 'maintenance_reset_operational_data')) {
    $resetOperationalPreview = maintenance_preview_reset_operational_data($conn, $resetOperationalInput);
}

if ($previewType === 'cleanup_quick_service_guest' && can_access($conn, 'maintenance_cleanup_quick_service_guest')) {
    $quickServiceGuestCleanupPreview = maintenance_preview_cleanup_quick_service_guest($conn);
}

$pageTitle = data_maintenance_text('ดูแลข้อมูลระบบ', 'Data Maintenance');

render_page_start($pageTitle, 'data_maintenance', array('translation_buffer' => false));
ob_start('data_maintenance_localize_output');
?>

<section class="page-hero">
    <div>
        <h1>Data Maintenance</h1>
        <p>Preview, export snapshot and clear only selected data ranges. Every action requires typed confirmation before execution.</p>
    </div>
    <div class="hero-actions">
        <a class="button button-secondary" href="manage_system.php">Manage System</a>
    </div>
</section>

<section class="table-card" style="margin-top: 18px;">
    <div class="section-head" style="padding: 18px 18px 0;">
        <div>
            <h2 class="section-title">Safety rules</h2>
            <p class="helper">Use the smallest date range possible. Snapshot export is created before each clear action. Customer, car and master data are never removed by these tools.</p>
        </div>
    </div>
    <div class="stack" style="padding: 18px;">
        <p class="helper">Database backup files are stored inside `storage/database_backups` and restore should only use files created by this system.</p>
        <p class="helper is-danger">Clear Log does not allow deleting log rows from today and is capped at 50,000 rows per run.</p>
        <p class="helper is-danger">Clear Booking / Queue only removes unpaid booking rows that have no payment, loyalty, package purchase or package usage side effects.</p>
        <p class="helper is-danger">Clear Sale only removes paid and closed sale rows after reversing loyalty/package effects and blocks bills that already affected later package usage.</p>
        <p class="helper is-danger">Reset Operational Data removes customers, cars, bills, queue, payments, package balances and loyalty history across the whole system, but keeps service setup, positions, employees and Quick Service settings.</p>
        <p class="helper is-danger">Quick Service guest cleanup only clears old default placeholder values from guest vehicle type, brand and model. It does not delete bills, customers or service history.</p>
        <p class="helper is-danger">Database Structure Sync only applies safe structure additions automatically: create missing tables, add missing columns, indexes and foreign keys. Changed columns or destructive drops stay in manual review.</p>
    </div>
</section>

<?php if ($maintenanceSections !== array()): ?>
    <section class="table-card" style="margin-top: 18px;">
        <div class="section-head" style="padding: 18px 18px 0;">
            <div>
                <h2 class="section-title">Data Maintenance Functions</h2>
                <p class="helper">Open a maintenance function from the list below. Each function keeps its own preview, confirm and execute flow.</p>
            </div>
        </div>
        <div class="button-row" style="padding: 18px; flex-wrap: wrap;">
            <a class="button<?= $maintenanceSection === 'home' ? '' : ' button-secondary' ?>" href="<?= e(data_maintenance_section_url('home')) ?>">Overview</a>
            <?php foreach ($maintenanceSections as $sectionKey => $sectionMeta): ?>
                <a class="button<?= $maintenanceSection === $sectionKey ? '' : ' button-secondary' ?>" href="<?= e(data_maintenance_section_url($sectionKey)) ?>"><?= e((string) ($sectionMeta['title'] ?? $sectionKey)) ?></a>
            <?php endforeach; ?>
        </div>
        <?php if ($maintenanceSection === 'home'): ?>
            <div class="grid grid-3" style="padding: 0 18px 18px;">
                <?php foreach ($maintenanceSections as $sectionKey => $sectionMeta): ?>
                    <article class="card">
                        <h3 class="section-title"><?= e((string) ($sectionMeta['title'] ?? $sectionKey)) ?></h3>
                        <p class="helper"><?= e((string) ($sectionMeta['description'] ?? '')) ?></p>
                        <div class="button-row" style="margin-top: 12px;">
                            <a class="button button-secondary" href="<?= e(data_maintenance_section_url($sectionKey)) ?>">Open function</a>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
<?php endif; ?>

<?php if ((can_access($conn, 'maintenance_backup_database') || can_access($conn, 'maintenance_restore_database')) && $maintenanceSection === 'backup_restore'): ?>
    <section class="table-card" style="margin-top: 18px;">
        <div class="section-head" style="padding: 18px 18px 0;">
            <div>
                <h2 class="section-title">Database Backup and Restore</h2>
                <p class="helper">Backup exports the full database to SQL. Restore always creates an automatic pre-restore backup first.</p>
            </div>
        </div>

        <div class="stats-grid" style="padding: 18px 18px 0;">
            <article class="stat-card">
                <span class="stat-label">Backup directory</span>
                <strong class="stat-value" style="font-size: 1rem;"><?= e(str_replace('\\', '/', (string) ($databaseCapabilities['backup_directory'] ?? ''))) ?></strong>
            </article>
            <article class="stat-card">
                <span class="stat-label">Backup method</span>
                <strong class="stat-value" style="font-size: 1rem;"><?= e((string) (($databaseCapabilities['backup_method'] ?? 'php') === 'mysqldump' ? 'mysqldump' : 'PHP fallback')) ?></strong>
            </article>
            <article class="stat-card">
                <span class="stat-label">Restore method</span>
                <strong class="stat-value" style="font-size: 1rem;"><?= e((string) (($databaseCapabilities['restore_method'] ?? 'php') === 'mysql' ? 'mysql client' : 'PHP fallback')) ?></strong>
            </article>
            <article class="stat-card">
                <span class="stat-label">Saved backups</span>
                <strong class="stat-value"><?= number_format(count($databaseBackups)) ?></strong>
            </article>
        </div>

        <?php if (can_access($conn, 'maintenance_backup_database')): ?>
            <div style="padding: 18px 18px 0;">
                <h3 class="section-title">Backup Database</h3>
                <?php if (!$databaseCapabilities['can_backup']): ?>
                    <p class="helper is-danger">Backup directory is not writable. Backup Database cannot run yet.</p>
                <?php else: ?>
                    <?php if (($databaseCapabilities['backup_method'] ?? 'php') === 'php'): ?>
                        <p class="helper">Production fallback is active. The system will create SQL backups directly from PHP without using mysqldump.</p>
                    <?php endif; ?>
                    <form method="POST" action="../process/run_data_maintenance.php" style="margin-top: 12px;">
                        <input type="hidden" name="maintenance_type" value="backup_database">
                        <input type="hidden" name="return_section" value="backup_restore">
                        <div class="button-row">
                            <button class="button" type="submit">Create Database Backup</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if (can_access($conn, 'maintenance_restore_database')): ?>
            <div style="padding: 18px;">
                <h3 class="section-title">Restore Database</h3>
                <?php if (empty($databaseBackups)): ?>
                    <p class="helper is-danger">No SQL backup files were found in the backup directory yet.</p>
                <?php elseif (!$databaseCapabilities['can_restore']): ?>
                    <p class="helper is-danger">Restore Database cannot run yet.</p>
                <?php else: ?>
                    <?php if (($databaseCapabilities['restore_method'] ?? 'php') === 'php'): ?>
                        <p class="helper">Production fallback is active. The system will restore SQL files directly from PHP when mysql client is unavailable.</p>
                    <?php endif; ?>
                    <form method="GET" style="margin-top: 12px;">
                        <input type="hidden" name="section" value="backup_restore">
                        <input type="hidden" name="preview" value="restore_database">
                        <label>
                            <span>Select backup file</span>
                            <select name="restore_backup_file">
                                <option value="">Select backup</option>
                                <?php foreach ($databaseBackups as $backupRow): ?>
                                    <?php $fileName = (string) ($backupRow['file_name'] ?? ''); ?>
                                    <option value="<?= e($fileName) ?>"<?= $restoreBackupFileName === $fileName ? ' selected' : '' ?>>
                                        <?= e($fileName) ?> / <?= number_format(((int) ($backupRow['size_bytes'] ?? 0)) / 1024, 1) ?> KB / <?= e((string) ($backupRow['modified_at'] ?? '')) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <div class="button-row" style="margin-top: 16px;">
                            <button class="button" type="submit">Preview Restore</button>
                        </div>
                    </form>

                    <?php if ($previewType === 'restore_database' && $restoreBackupFileName !== '' && !$restoreBackupPreview): ?>
                        <p class="helper is-danger" style="margin-top: 12px;">Selected backup file was not found.</p>
                    <?php endif; ?>

                    <?php if ($restoreBackupPreview): ?>
                        <div class="table-card" style="margin-top: 18px;">
                            <div class="section-head" style="padding: 18px 18px 0;">
                                <div>
                                    <h3 class="section-title">Restore preview</h3>
                                    <p class="helper">The system will create a pre-restore backup automatically before importing this file.</p>
                                </div>
                            </div>
                            <table>
                                <tbody>
                                <tr>
                                    <th>Backup file</th>
                                    <td><?= e((string) ($restoreBackupPreview['file_name'] ?? '')) ?></td>
                                </tr>
                                <tr>
                                    <th>Size</th>
                                    <td><?= number_format(((int) ($restoreBackupPreview['size_bytes'] ?? 0)) / 1024, 1) ?> KB</td>
                                </tr>
                                <tr>
                                    <th>Modified</th>
                                    <td><?= e((string) ($restoreBackupPreview['modified_at'] ?? '')) ?></td>
                                </tr>
                                </tbody>
                            </table>
                        </div>

                        <form method="POST" action="../process/run_data_maintenance.php" style="margin-top: 18px;">
                            <input type="hidden" name="maintenance_type" value="restore_database">
                            <input type="hidden" name="return_section" value="backup_restore">
                            <input type="hidden" name="backup_file" value="<?= e((string) ($restoreBackupPreview['file_name'] ?? '')) ?>">
                            <label>
                                <span><?= data_maintenance_text('พิมพ์ <strong>RESTORE DATABASE</strong> เพื่อยืนยัน', 'Type <strong>RESTORE DATABASE</strong> to confirm') ?></span>
                                <input type="text" name="confirm_phrase" value="">
                            </label>
                            <div class="button-row" style="margin-top: 16px;">
                                <button class="button button-danger" type="submit">Execute Restore Database</button>
                            </div>
                        </form>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($databaseBackups)): ?>
            <div style="padding: 0 18px 18px;">
                <div class="table-card">
                    <div class="section-head" style="padding: 18px 18px 0;">
                        <div>
                            <h3 class="section-title">Available backup files</h3>
                        </div>
                    </div>
                    <table>
                        <thead>
                        <tr>
                            <th>File</th>
                            <th>Size</th>
                            <th>Modified</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($databaseBackups as $backupRow): ?>
                            <tr>
                                <td><?= e((string) ($backupRow['file_name'] ?? '')) ?></td>
                                <td><?= number_format(((int) ($backupRow['size_bytes'] ?? 0)) / 1024, 1) ?> KB</td>
                                <td><?= e((string) ($backupRow['modified_at'] ?? '')) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>
    </section>
<?php endif; ?>

<?php if ((can_access($conn, 'maintenance_compare_database_structure') || can_access($conn, 'maintenance_apply_database_structure')) && $maintenanceSection === 'structure_sync'): ?>
    <section class="table-card" style="margin-top: 18px;">
        <div class="section-head" style="padding: 18px 18px 0;">
            <div>
                <h2 class="section-title">Database Structure Sync</h2>
                <p class="helper">Compare structure between Source DB (A) and Target DB (B), generate SQL patch, then apply only safe updates to B after an automatic backup.</p>
            </div>
        </div>

        <form method="POST" style="padding: 18px;">
            <input type="hidden" name="maintenance_preview_type" value="database_structure_sync">

            <div class="grid grid-2">
                <section class="card">
                    <div class="stack">
                        <h3 class="section-title">Source DB (A)</h3>
                        <label class="checkbox">
                            <input type="checkbox" name="structure_source[use_current]" value="1"<?= !empty($structureSyncSourceInput['use_current']) ? ' checked' : '' ?>>
                            <span>Use current system database connection</span>
                        </label>
                        <label>
                            <span>Host</span>
                            <input type="text" name="structure_source[host]" value="<?= e((string) ($structureSyncSourceInput['host'] ?? '')) ?>">
                        </label>
                        <label>
                            <span>Port</span>
                            <input type="number" name="structure_source[port]" min="1" value="<?= e((string) ($structureSyncSourceInput['port'] ?? '3306')) ?>">
                        </label>
                        <label>
                            <span>Username</span>
                            <input type="text" name="structure_source[user]" value="<?= e((string) ($structureSyncSourceInput['user'] ?? '')) ?>">
                        </label>
                        <label>
                            <span>Password</span>
                            <input type="password" name="structure_source[pass]" value="<?= e((string) ($structureSyncSourceInput['pass'] ?? '')) ?>">
                        </label>
                        <label>
                            <span>Database</span>
                            <input type="text" name="structure_source[database]" value="<?= e((string) ($structureSyncSourceInput['database'] ?? '')) ?>">
                        </label>
                    </div>
                </section>

                <section class="card">
                    <div class="stack">
                        <h3 class="section-title">Target DB (B)</h3>
                        <label class="checkbox">
                            <input type="checkbox" name="structure_target[use_current]" value="1"<?= !empty($structureSyncTargetInput['use_current']) ? ' checked' : '' ?>>
                            <span>Use current system database connection</span>
                        </label>
                        <label>
                            <span>Host</span>
                            <input type="text" name="structure_target[host]" value="<?= e((string) ($structureSyncTargetInput['host'] ?? '')) ?>">
                        </label>
                        <label>
                            <span>Port</span>
                            <input type="number" name="structure_target[port]" min="1" value="<?= e((string) ($structureSyncTargetInput['port'] ?? '3306')) ?>">
                        </label>
                        <label>
                            <span>Username</span>
                            <input type="text" name="structure_target[user]" value="<?= e((string) ($structureSyncTargetInput['user'] ?? '')) ?>">
                        </label>
                        <label>
                            <span>Password</span>
                            <input type="password" name="structure_target[pass]" value="<?= e((string) ($structureSyncTargetInput['pass'] ?? '')) ?>">
                        </label>
                        <label>
                            <span>Database</span>
                            <input type="text" name="structure_target[database]" value="<?= e((string) ($structureSyncTargetInput['database'] ?? '')) ?>">
                        </label>
                    </div>
                </section>
            </div>

            <div class="button-row" style="margin-top: 16px;">
                <?php if (can_access($conn, 'maintenance_compare_database_structure')): ?>
                    <button class="button" type="submit">Compare structure / Generate SQL</button>
                <?php endif; ?>
            </div>
        </form>

        <?php if ($structureSyncPreviewError !== ''): ?>
            <div style="padding: 0 18px 18px;">
                <p class="helper is-danger"><?= e(translate_text($structureSyncPreviewError)) ?></p>
            </div>
        <?php endif; ?>

        <?php if ($structureSyncPreview): ?>
            <div style="padding: 0 18px 18px;">
                <div class="stats-grid">
                    <article class="stat-card">
                        <span class="stat-label">Missing tables</span>
                        <strong class="stat-value"><?= number_format((int) ($structureSyncPreview['summary']['missing_tables'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Missing columns</span>
                        <strong class="stat-value"><?= number_format((int) ($structureSyncPreview['summary']['missing_columns'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Changed columns</span>
                        <strong class="stat-value"><?= number_format((int) ($structureSyncPreview['summary']['changed_columns'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Missing views</span>
                        <strong class="stat-value"><?= number_format((int) ($structureSyncPreview['summary']['missing_views'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Missing triggers</span>
                        <strong class="stat-value"><?= number_format((int) ($structureSyncPreview['summary']['missing_triggers'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Missing routines</span>
                        <strong class="stat-value"><?= number_format((int) ($structureSyncPreview['summary']['missing_routines'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Safe SQL</span>
                        <strong class="stat-value"><?= number_format((int) ($structureSyncPreview['summary']['safe_sql_count'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Manual review</span>
                        <strong class="stat-value"><?= number_format((int) ($structureSyncPreview['summary']['manual_sql_count'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Manual apply items</span>
                        <strong class="stat-value"><?= number_format((int) ($structureSyncPreview['summary']['manual_apply_count'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Warnings</span>
                        <strong class="stat-value"><?= number_format((int) ($structureSyncPreview['summary']['warnings'] ?? 0)) ?></strong>
                    </article>
                </div>

                <div class="grid grid-2" style="margin-top: 18px;">
                    <section class="card">
                        <h3 class="section-title">Source summary</h3>
                        <p class="helper"><?= e((string) (($structureSyncPreview['source']['database'] ?? '-'))) ?> @ <?= e((string) (($structureSyncPreview['source']['host'] ?? '-'))) ?>:<?= e((string) (($structureSyncPreview['source']['port'] ?? '3306'))) ?></p>
                    </section>
                    <section class="card">
                        <h3 class="section-title">Target summary</h3>
                        <p class="helper"><?= e((string) (($structureSyncPreview['target']['database'] ?? '-'))) ?> @ <?= e((string) (($structureSyncPreview['target']['host'] ?? '-'))) ?>:<?= e((string) (($structureSyncPreview['target']['port'] ?? '3306'))) ?></p>
                    </section>
                </div>

                <?php if (!empty($structureSyncPreview['missing_tables'])): ?>
                    <div class="stack" style="margin-top: 18px;">
                        <h3 class="section-title">Missing tables in target</h3>
                        <ul class="stack compact-list">
                            <?php foreach ($structureSyncPreview['missing_tables'] as $row): ?>
                                <li><?= e((string) ($row['table_name'] ?? '')) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <?php if (!empty($structureSyncPreview['missing_views']) || !empty($structureSyncPreview['missing_triggers']) || !empty($structureSyncPreview['missing_routines'])): ?>
                    <div class="grid grid-3" style="margin-top: 18px;">
                        <?php if (!empty($structureSyncPreview['missing_views'])): ?>
                            <section class="card">
                                <h3 class="section-title">Missing views</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['missing_views'] as $row): ?>
                                        <li><?= e((string) ($row['view_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['missing_triggers'])): ?>
                            <section class="card">
                                <h3 class="section-title">Missing triggers</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['missing_triggers'] as $row): ?>
                                        <li><?= e((string) ($row['trigger_name'] ?? '')) ?><?php if (!empty($row['table_name'])): ?> on <?= e((string) $row['table_name']) ?><?php endif; ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['missing_routines'])): ?>
                            <section class="card">
                                <h3 class="section-title">Missing routines</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['missing_routines'] as $row): ?>
                                        <li><?= e((string) ($row['routine_type'] ?? '')) ?> <?= e((string) ($row['routine_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                <?php if (!empty($structureSyncPreview['changed_columns']) || !empty($structureSyncPreview['extra_tables']) || !empty($structureSyncPreview['extra_columns']) || !empty($structureSyncPreview['changed_indexes']) || !empty($structureSyncPreview['changed_foreign_keys']) || !empty($structureSyncPreview['table_option_changes']) || !empty($structureSyncPreview['changed_views']) || !empty($structureSyncPreview['extra_views']) || !empty($structureSyncPreview['changed_triggers']) || !empty($structureSyncPreview['extra_triggers']) || !empty($structureSyncPreview['changed_routines']) || !empty($structureSyncPreview['extra_routines'])): ?>
                    <div class="stack" style="margin-top: 18px;">
                        <h3 class="section-title">Manual review required</h3>
                        <p class="helper is-danger">These differences were detected but will not be applied automatically because they may be destructive or require manual review.</p>
                    </div>
                <?php endif; ?>

                <?php if (!empty($structureSyncPreview['changed_columns']) || !empty($structureSyncPreview['changed_indexes']) || !empty($structureSyncPreview['changed_foreign_keys']) || !empty($structureSyncPreview['table_option_changes']) || !empty($structureSyncPreview['extra_tables']) || !empty($structureSyncPreview['extra_columns']) || !empty($structureSyncPreview['extra_indexes']) || !empty($structureSyncPreview['extra_foreign_keys'])): ?>
                    <div class="grid grid-3" style="margin-top: 18px;">
                        <?php if (!empty($structureSyncPreview['changed_columns'])): ?>
                            <section class="card">
                                <h3 class="section-title">Changed columns</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['changed_columns'] as $row): ?>
                                        <li><?= e((string) ($row['table_name'] ?? '')) ?>.<?= e((string) ($row['column_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['changed_indexes'])): ?>
                            <section class="card">
                                <h3 class="section-title">Changed indexes</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['changed_indexes'] as $row): ?>
                                        <li><?= e((string) ($row['table_name'] ?? '')) ?>.<?= e((string) ($row['index_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['changed_foreign_keys'])): ?>
                            <section class="card">
                                <h3 class="section-title">Changed foreign keys</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['changed_foreign_keys'] as $row): ?>
                                        <li><?= e((string) ($row['table_name'] ?? '')) ?>.<?= e((string) ($row['constraint_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['table_option_changes'])): ?>
                            <section class="card">
                                <h3 class="section-title">Changed table options</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['table_option_changes'] as $row): ?>
                                        <li><?= e((string) ($row['table_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['extra_tables'])): ?>
                            <section class="card">
                                <h3 class="section-title">Extra tables in target</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['extra_tables'] as $row): ?>
                                        <li><?= e((string) ($row['table_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['extra_columns'])): ?>
                            <section class="card">
                                <h3 class="section-title">Extra columns in target</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['extra_columns'] as $row): ?>
                                        <li><?= e((string) ($row['table_name'] ?? '')) ?>.<?= e((string) ($row['column_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['extra_indexes'])): ?>
                            <section class="card">
                                <h3 class="section-title">Extra indexes in target</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['extra_indexes'] as $row): ?>
                                        <li><?= e((string) ($row['table_name'] ?? '')) ?>.<?= e((string) ($row['index_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['extra_foreign_keys'])): ?>
                            <section class="card">
                                <h3 class="section-title">Extra foreign keys in target</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['extra_foreign_keys'] as $row): ?>
                                        <li><?= e((string) ($row['table_name'] ?? '')) ?>.<?= e((string) ($row['constraint_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                <?php if (!empty($structureSyncPreview['changed_views']) || !empty($structureSyncPreview['extra_views']) || !empty($structureSyncPreview['changed_triggers']) || !empty($structureSyncPreview['extra_triggers']) || !empty($structureSyncPreview['changed_routines']) || !empty($structureSyncPreview['extra_routines'])): ?>
                    <div class="grid grid-3" style="margin-top: 18px;">
                        <?php if (!empty($structureSyncPreview['changed_views'])): ?>
                            <section class="card">
                                <h3 class="section-title">Changed views</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['changed_views'] as $row): ?>
                                        <li><?= e((string) ($row['view_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['extra_views'])): ?>
                            <section class="card">
                                <h3 class="section-title">Extra views in target</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['extra_views'] as $row): ?>
                                        <li><?= e((string) ($row['view_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['changed_triggers'])): ?>
                            <section class="card">
                                <h3 class="section-title">Changed triggers</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['changed_triggers'] as $row): ?>
                                        <li><?= e((string) ($row['trigger_name'] ?? '')) ?><?php if (!empty($row['table_name'])): ?> on <?= e((string) $row['table_name']) ?><?php endif; ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['extra_triggers'])): ?>
                            <section class="card">
                                <h3 class="section-title">Extra triggers in target</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['extra_triggers'] as $row): ?>
                                        <li><?= e((string) ($row['trigger_name'] ?? '')) ?><?php if (!empty($row['table_name'])): ?> on <?= e((string) $row['table_name']) ?><?php endif; ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['changed_routines'])): ?>
                            <section class="card">
                                <h3 class="section-title">Changed routines</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['changed_routines'] as $row): ?>
                                        <li><?= e((string) ($row['routine_type'] ?? '')) ?> <?= e((string) ($row['routine_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                        <?php if (!empty($structureSyncPreview['extra_routines'])): ?>
                            <section class="card">
                                <h3 class="section-title">Extra routines in target</h3>
                                <ul class="stack compact-list">
                                    <?php foreach ($structureSyncPreview['extra_routines'] as $row): ?>
                                        <li><?= e((string) ($row['routine_type'] ?? '')) ?> <?= e((string) ($row['routine_name'] ?? '')) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </section>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                <div class="button-row" style="margin-top: 18px;">
                    <form method="POST" action="../process/download_structure_compare.php">
                        <?= data_maintenance_hidden_structure_config('source', $structureSyncSourceInput) ?>
                        <?= data_maintenance_hidden_structure_config('target', $structureSyncTargetInput) ?>
                        <button class="button button-secondary" type="submit">Download compare JSON</button>
                    </form>
                    <form method="POST" action="../process/download_structure_patch.php">
                        <?= data_maintenance_hidden_structure_config('source', $structureSyncSourceInput) ?>
                        <?= data_maintenance_hidden_structure_config('target', $structureSyncTargetInput) ?>
                        <input type="hidden" name="patch_scope" value="safe">
                        <button class="button button-secondary" type="submit">Download safe SQL</button>
                    </form>
                    <form method="POST" action="../process/download_structure_patch.php">
                        <?= data_maintenance_hidden_structure_config('source', $structureSyncSourceInput) ?>
                        <?= data_maintenance_hidden_structure_config('target', $structureSyncTargetInput) ?>
                        <input type="hidden" name="patch_scope" value="manual">
                        <button class="button button-secondary" type="submit">Download manual-only patch</button>
                    </form>
                    <form method="POST" action="../process/download_structure_patch.php">
                        <?= data_maintenance_hidden_structure_config('source', $structureSyncSourceInput) ?>
                        <?= data_maintenance_hidden_structure_config('target', $structureSyncTargetInput) ?>
                        <input type="hidden" name="patch_scope" value="combined">
                        <button class="button button-secondary" type="submit">Download full patch</button>
                    </form>
                </div>

                <div class="grid grid-2" style="margin-top: 12px;">
                    <section class="card">
                        <h3 class="section-title">Download compare JSON</h3>
                        <p class="helper">ดาวน์โหลดผลเปรียบเทียบโครงสร้างทั้งหมดในรูปแบบ JSON เพื่อเก็บหลักฐาน ตรวจย้อนหลัง หรือส่งต่อให้ทีมตรวจสอบ diff ระหว่าง Source DB และ Target DB</p>
                    </section>
                    <section class="card">
                        <h3 class="section-title">Download safe SQL</h3>
                        <p class="helper">ดาวน์โหลดเฉพาะ SQL ที่ระบบมองว่าปลอดภัย เช่น <code>CREATE TABLE</code>, <code>ADD COLUMN</code>, <code>ADD INDEX</code>, <code>ADD FOREIGN KEY</code> เหมาะสำหรับ sync โครงสร้างแบบเสี่ยงต่ำ</p>
                    </section>
                    <section class="card">
                        <h3 class="section-title">Download manual-only patch</h3>
                        <p class="helper">ดาวน์โหลดเฉพาะ SQL หรือ note ที่ต้องให้คนตรวจเองก่อน เช่น changed columns, changed indexes, changed foreign keys หรือ programmable objects ที่ยังไม่ควร apply อัตโนมัติ</p>
                    </section>
                    <section class="card">
                        <h3 class="section-title">Download full patch</h3>
                        <p class="helper">ดาวน์โหลดรวมทั้ง safe SQL และ manual review ไว้ในไฟล์เดียว เหมาะสำหรับส่งให้ dev หรือ DBA ตรวจภาพรวมทั้งหมดก่อนเลือกนำไปใช้</p>
                    </section>
                </div>

                <div class="grid grid-2" style="margin-top: 18px;">
                    <section class="card">
                        <h3 class="section-title">Safe SQL patch</h3>
                        <textarea rows="14" readonly><?= e(implode(PHP_EOL . PHP_EOL, (array) ($structureSyncPreview['safe_sql'] ?? array()))) ?></textarea>
                    </section>
                    <section class="card">
                        <h3 class="section-title">Manual SQL / review notes</h3>
                        <textarea rows="14" readonly><?= e(implode(PHP_EOL . PHP_EOL, (array) ($structureSyncPreview['manual_sql'] ?? array()))) ?></textarea>
                    </section>
                </div>

                <?php if (!empty($structureSyncPreview['manual_apply_items']) && can_access($conn, 'maintenance_apply_database_structure')): ?>
                    <form method="POST" action="../process/run_data_maintenance.php" style="margin-top: 18px;">
                        <input type="hidden" name="maintenance_type" value="database_structure_sync_apply_manual">
                        <input type="hidden" name="return_section" value="structure_sync">
                        <?= data_maintenance_hidden_structure_config('source', $structureSyncSourceInput) ?>
                        <?= data_maintenance_hidden_structure_config('target', $structureSyncTargetInput) ?>
                        <div class="stack">
                            <h3 class="section-title">Select manual SQL items to apply</h3>
                            <p class="helper">Choose only the reviewed items you want to apply to Target DB (B). A backup will be created before execution.</p>
                            <div class="stack">
                                <?php foreach ((array) ($structureSyncPreview['manual_apply_items'] ?? array()) as $index => $manualItem): ?>
                                    <?php
                                    $sqlBlock = trim((string) ($manualItem['sql'] ?? ''));
                                    $manualLabel = trim((string) ($manualItem['label'] ?? ''));
                                    $sqlBlock = trim((string) $sqlBlock);
                                    ?>
                                    <details class="card">
                                        <summary class="checkbox" style="cursor: pointer; user-select: none;">
                                            <input type="checkbox" name="selected_manual_sql[]" value="<?= e($sqlBlock) ?>">
                                            <span><?= e($manualLabel !== '' ? translate_text($manualLabel) : data_maintenance_text('รายการ Manual SQL ', 'Manual SQL item ') . ($index + 1)) ?></span>
                                        </summary>
                                        <pre style="white-space: pre-wrap; margin: 12px 0 0; font-size: 12px;"><?= e($sqlBlock) ?></pre>
                                    </details>
                                <?php endforeach; ?>
                            </div>
                            <label>
                                <span><?= data_maintenance_text('พิมพ์ <code>APPLY MANUAL STRUCTURE</code> เพื่อดำเนินการต่อ', 'Type <code>APPLY MANUAL STRUCTURE</code> to continue') ?></span>
                                <input type="text" name="confirm_phrase" required placeholder="APPLY MANUAL STRUCTURE">
                            </label>
                            <div class="button-row">
                                <button class="button button-danger" type="submit">Apply selected manual SQL</button>
                            </div>
                        </div>
                    </form>
                <?php endif; ?>

                <?php if (can_access($conn, 'maintenance_apply_database_structure')): ?>
                    <form method="POST" action="../process/run_data_maintenance.php" style="margin-top: 18px;">
                        <input type="hidden" name="maintenance_type" value="database_structure_sync_apply">
                        <input type="hidden" name="return_section" value="structure_sync">
                        <?= data_maintenance_hidden_structure_config('source', $structureSyncSourceInput) ?>
                        <?= data_maintenance_hidden_structure_config('target', $structureSyncTargetInput) ?>
                        <label>
                            <span><?= data_maintenance_text('พิมพ์ <code>APPLY DATABASE STRUCTURE</code> เพื่อยืนยันการอัปเดตโครงสร้างฐานข้อมูลปลายทาง', 'Type <code>APPLY DATABASE STRUCTURE</code> to confirm applying database structure changes to the target database') ?></span>
                            <input type="text" name="confirm_phrase" required placeholder="APPLY DATABASE STRUCTURE">
                        </label>
                        <label style="display:none;">
                            <span>พิมพ์ <code>APPLY DATABASE STRUCTURE</code> เพื่อยืนยันการอัปเดตโครงสร้างฐานข้อมูลปลายทาง</span>
                            <input type="text" name="confirm_phrase_legacy" value="" placeholder="APPLY DATABASE STRUCTURE">
                        </label>
                        <p class="helper is-danger" style="margin-top: 12px;"><?= e(data_maintenance_text('ระบบจะสร้างไฟล์สำรองของ Target DB (B) อัตโนมัติก่อนอัปเดตเฉพาะคำสั่ง SQL ที่ปลอดภัย', 'The system will create an automatic backup of Target DB (B) before applying only safe SQL statements.')) ?></p>
                        <div class="card" style="margin-top: 12px;">
                            <h3 class="section-title"><?= e(data_maintenance_text('ปุ่มนี้ทำอะไร', 'What this button does')) ?></h3>
                            <p class="helper"><?= data_maintenance_text('เมื่อกดปุ่มนี้ ระบบจะนำเฉพาะ <strong>Safe SQL patch</strong> ไปอัปเดตที่ <strong>Target DB (B)</strong> โดยอัตโนมัติ', 'When you click this button, the system will apply only the <strong>Safe SQL patch</strong> to <strong>Target DB (B)</strong> automatically.') ?></p>
                            <p class="helper"><?= data_maintenance_text('ระบบจะ apply เฉพาะรายการที่ปลอดภัย เช่น <code>CREATE TABLE</code>, <code>ADD COLUMN</code>, <code>ADD INDEX</code>, <code>ADD FOREIGN KEY</code>', 'The system applies only safe items such as <code>CREATE TABLE</code>, <code>ADD COLUMN</code>, <code>ADD INDEX</code>, and <code>ADD FOREIGN KEY</code>.') ?></p>
                            <p class="helper is-danger"><?= data_maintenance_text('ระบบจะไม่ apply ส่วนที่ต้องตรวจเอง เช่น changed columns, changed indexes, changed foreign keys, extra tables/columns และ programmable objects ในส่วน manual review', 'The system will not apply items that require manual review such as changed columns, changed indexes, changed foreign keys, extra tables/columns, and programmable objects in the manual review section.') ?></p>
                        </div>
                        <div class="card" style="display:none; margin-top: 12px;">
                            <h3 class="section-title">ปุ่มนี้ทำอะไร</h3>
                            <p class="helper">เมื่อกดปุ่มนี้ ระบบจะนำเฉพาะ <strong>Safe SQL patch</strong> ไปอัปเดตที่ <strong>Target DB (B)</strong> โดยอัตโนมัติ</p>
                            <p class="helper">ระบบจะ apply เฉพาะรายการที่ปลอดภัย เช่น <code>CREATE TABLE</code>, <code>ADD COLUMN</code>, <code>ADD INDEX</code>, <code>ADD FOREIGN KEY</code></p>
                            <p class="helper is-danger">ระบบจะไม่ apply ส่วนที่ต้องตรวจเอง เช่น changed columns, changed indexes, changed foreign keys, extra tables/columns และ programmable objects ในส่วน manual review</p>
                        </div>
                        <div class="button-row" style="margin-top: 16px;">
                            <button class="button button-danger" type="submit"><?= e(data_maintenance_text('อัปเดตโครงสร้างปลอดภัยไปยัง Target DB', 'Apply safe structure updates to Target DB')) ?></button>
                        </div>
                        <div class="button-row" style="display:none; margin-top: 16px;">
                            <button class="button button-danger" type="submit">อัปเดตโครงสร้างปลอดภัยไปยัง Target DB</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </section>
<?php endif; ?>

<?php if (can_access($conn, 'maintenance_reset_operational_data') && $maintenanceSection === 'reset_operational'): ?>
    <section class="table-card" style="margin-top: 18px;">
        <div class="section-head" style="padding: 18px 18px 0;">
            <div>
                <h2 class="section-title">Reset Operational Data</h2>
                <p class="helper">Use this to start fresh with a clean system while keeping service structure, positions, employees and payment settings.</p>
            </div>
        </div>
        <form method="GET" style="padding: 18px;">
            <input type="hidden" name="section" value="reset_operational">
            <input type="hidden" name="preview" value="reset_operational_data">
            <div class="grid grid-2">
                <label class="checkbox-card">
                    <input type="checkbox" name="reset_include_logs" value="1"<?= $resetOperationalInput['include_logs'] ? ' checked' : '' ?>>
                    <span>Clear audit and maintenance logs too</span>
                </label>
                <label class="checkbox-card">
                    <input type="checkbox" name="reset_reset_counters" value="1"<?= $resetOperationalInput['reset_counters'] ? ' checked' : '' ?>>
                    <span>Reset bill and queue counters</span>
                </label>
            </div>
            <div class="button-row" style="margin-top: 16px;">
                <button class="button" type="submit">Preview Reset Operational Data</button>
                <a class="button button-secondary" href="<?= e(data_maintenance_section_url('reset_operational')) ?>">Reset</a>
            </div>
        </form>

        <?php if ($resetOperationalPreview !== null): ?>
            <div style="padding: 0 18px 18px;">
                <?php foreach ($resetOperationalPreview['errors'] as $errorMessage): ?>
                    <p class="helper is-danger"><?= e(translate_text($errorMessage)) ?></p>
                <?php endforeach; ?>
                <?php foreach ($resetOperationalPreview['warnings'] as $warningMessage): ?>
                    <p class="helper is-danger"><?= e(translate_text($warningMessage)) ?></p>
                <?php endforeach; ?>

                <div class="stats-grid" style="margin-top: 12px;">
                    <article class="stat-card">
                        <span class="stat-label">Rows to clear</span>
                        <strong class="stat-value"><?= number_format((int) ($resetOperationalPreview['summary']['selected_rows'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Bills</span>
                        <strong class="stat-value"><?= number_format((int) ($resetOperationalPreview['summary']['order_count'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Customers</span>
                        <strong class="stat-value"><?= number_format((int) ($resetOperationalPreview['summary']['customer_count'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Cars</span>
                        <strong class="stat-value"><?= number_format((int) ($resetOperationalPreview['summary']['car_count'] ?? 0)) ?></strong>
                    </article>
                </div>

                <div class="grid grid-2" style="margin-top: 18px;">
                    <div class="table-card">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">Selected data to clear</h3>
                            </div>
                        </div>
                        <table>
                            <thead><tr><th>Table group</th><th>Rows</th></tr></thead>
                            <tbody>
                            <?php foreach ($resetOperationalPreview['selected_counts'] as $row): ?>
                                <tr>
                                    <td><?= e(translate_text((string) ($row['label'] ?? '-'))) ?></td>
                                    <td><?= number_format((int) ($row['count'] ?? 0)) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="table-card">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">Kept after reset</h3>
                            </div>
                        </div>
                        <table>
                            <tbody>
                            <tr><th>Service structure</th><td>Categories, groups, services and package definitions</td></tr>
                            <tr><th>Access setup</th><td>Positions, employees and branch access</td></tr>
                            <tr><th>Payment setup</th><td>Quick Service PromptPay / QR settings</td></tr>
                            <tr><th>Master items</th><td>Products and legacy setup tables are not changed</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <?php if (!empty($resetOperationalPreview['log_counts'])): ?>
                    <div class="table-card" style="margin-top: 18px;">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">Logs kept</h3>
                            </div>
                        </div>
                        <table>
                            <thead><tr><th>Log group</th><th>Rows</th></tr></thead>
                            <tbody>
                            <?php foreach ($resetOperationalPreview['log_counts'] as $row): ?>
                                <tr>
                                    <td><?= e(translate_text((string) ($row['label'] ?? '-'))) ?></td>
                                    <td><?= number_format((int) ($row['count'] ?? 0)) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>

                <?php if (!empty($resetOperationalPreview['branch_summary'])): ?>
                    <div class="table-card" style="margin-top: 18px;">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">Current bill distribution</h3>
                            </div>
                        </div>
                        <table>
                            <thead><tr><th>Branch</th><th>Source</th><th>Bills</th><th>Total</th></tr></thead>
                            <tbody>
                            <?php foreach ($resetOperationalPreview['branch_summary'] as $row): ?>
                                <tr>
                                    <td><?= e((string) ($row['branch_name'] ?? '-')) ?></td>
                                    <td><?= e(data_maintenance_order_source_label((string) ($row['order_source'] ?? '-'))) ?></td>
                                    <td><?= number_format((int) ($row['order_count'] ?? 0)) ?></td>
                                    <td><?= number_format((float) ($row['total_price'] ?? 0), 2) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>

                <?php if (!empty($resetOperationalPreview['can_execute'])): ?>
                    <form method="POST" action="../process/run_data_maintenance.php" style="margin-top: 18px;">
                        <input type="hidden" name="maintenance_type" value="reset_operational_data">
                        <input type="hidden" name="return_section" value="reset_operational">
                        <?php if ($resetOperationalPreview['filters']['include_logs']): ?>
                            <input type="hidden" name="include_logs" value="1">
                        <?php endif; ?>
                        <?php if ($resetOperationalPreview['filters']['reset_counters']): ?>
                            <input type="hidden" name="reset_counters" value="1">
                        <?php endif; ?>
                        <label>
                            <span><?= data_maintenance_text('พิมพ์ <strong>RESET OPERATIONAL DATA</strong> เพื่อยืนยัน', 'Type <strong>RESET OPERATIONAL DATA</strong> to confirm') ?></span>
                            <input type="text" name="confirm_phrase" value="">
                        </label>
                        <p class="helper" style="margin-top: 12px;">A full database backup will be created automatically before deletion starts.</p>
                        <div class="button-row" style="margin-top: 16px;">
                            <button class="button button-danger" type="submit">Execute Reset Operational Data</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </section>
<?php endif; ?>

<?php if (can_access($conn, 'maintenance_cleanup_quick_service_guest') && $maintenanceSection === 'cleanup_guest'): ?>
    <section class="table-card" style="margin-top: 18px;">
        <div class="section-head" style="padding: 18px 18px 0;">
            <div>
                <h2 class="section-title">Cleanup Quick Service Guest Vehicle Data</h2>
                <p class="helper">Clear old default values such as <code>Quick Service</code>, branch names, <code>Guest</code> or <code>Walk-in</code> from guest vehicle brand, model and vehicle type.</p>
            </div>
        </div>
        <form method="GET" style="padding: 18px;">
            <input type="hidden" name="section" value="cleanup_guest">
            <input type="hidden" name="preview" value="cleanup_quick_service_guest">
            <div class="button-row">
                <button class="button" type="submit">Preview Quick Service Guest Cleanup</button>
                <a class="button button-secondary" href="<?= e(data_maintenance_section_url('cleanup_guest')) ?>">Reset</a>
            </div>
        </form>

        <?php if ($quickServiceGuestCleanupPreview !== null): ?>
            <div style="padding: 0 18px 18px;">
                <?php foreach ($quickServiceGuestCleanupPreview['errors'] as $errorMessage): ?>
                    <p class="helper is-danger"><?= e(translate_text($errorMessage)) ?></p>
                <?php endforeach; ?>
                <?php foreach ($quickServiceGuestCleanupPreview['warnings'] as $warningMessage): ?>
                    <p class="helper is-danger"><?= e(translate_text($warningMessage)) ?></p>
                <?php endforeach; ?>

                <div class="stats-grid" style="margin-top: 12px;">
                    <article class="stat-card">
                        <span class="stat-label">Vehicle rows</span>
                        <strong class="stat-value"><?= number_format((int) ($quickServiceGuestCleanupPreview['summary']['candidate_rows'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Customers</span>
                        <strong class="stat-value"><?= number_format((int) ($quickServiceGuestCleanupPreview['summary']['customer_count'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Vehicle type to clear</span>
                        <strong class="stat-value"><?= number_format((int) ($quickServiceGuestCleanupPreview['summary']['vehicle_type_rows'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Brand / model to clear</span>
                        <strong class="stat-value"><?= number_format((int) (($quickServiceGuestCleanupPreview['summary']['brand_rows'] ?? 0) + ($quickServiceGuestCleanupPreview['summary']['model_rows'] ?? 0))) ?></strong>
                    </article>
                </div>

                <?php if (!empty($quickServiceGuestCleanupPreview['rows'])): ?>
                    <div class="table-card" style="margin-top: 18px;">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">Affected guest vehicles</h3>
                                <p class="helper">Only the highlighted placeholder fields will be cleared.</p>
                            </div>
                        </div>
                        <table>
                            <thead>
                            <tr>
                                <th>Customer</th>
                                <th>Plate</th>
                                <th>Province</th>
                                <th>Vehicle type</th>
                                <th>Brand</th>
                                <th>Model</th>
                                <th>Quick Service branches</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($quickServiceGuestCleanupPreview['rows'] as $row): ?>
                                <tr>
                                    <td><?= e((string) ($row['customer_name'] ?? '')) ?></td>
                                    <td><?= e((string) ($row['plate_number'] ?? '')) ?></td>
                                    <td><?= e((string) ($row['province'] ?? '-')) ?></td>
                                    <td><?= e((string) ($row['vehicle_type'] ?? '')) ?><?= !empty($row['cleanup_vehicle_type']) ? ' *' : '' ?></td>
                                    <td><?= e((string) ($row['brand'] ?? '')) ?><?= !empty($row['cleanup_brand']) ? ' *' : '' ?></td>
                                    <td><?= e((string) ($row['model'] ?? '')) ?><?= !empty($row['cleanup_model']) ? ' *' : '' ?></td>
                                    <td><?= e((string) ($row['quick_service_branches'] ?? '-')) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>

                <?php if (!empty($quickServiceGuestCleanupPreview['can_execute'])): ?>
                    <form method="POST" action="../process/run_data_maintenance.php" style="margin-top: 18px;">
                        <input type="hidden" name="maintenance_type" value="cleanup_quick_service_guest">
                        <input type="hidden" name="return_section" value="cleanup_guest">
                        <label>
                            <span><?= data_maintenance_text('พิมพ์ <strong>CLEANUP QUICK SERVICE GUEST</strong> เพื่อยืนยัน', 'Type <strong>CLEANUP QUICK SERVICE GUEST</strong> to confirm') ?></span>
                            <input type="text" name="confirm_phrase" value="">
                        </label>
                        <p class="helper" style="margin-top: 12px;">A full database backup will be created automatically before cleanup starts.</p>
                        <div class="button-row" style="margin-top: 16px;">
                            <button class="button button-danger" type="submit">Execute Quick Service Guest Cleanup</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </section>
<?php endif; ?>

<?php if (can_access($conn, 'maintenance_clear_log') && $maintenanceSection === 'clear_log'): ?>
    <section class="table-card" style="margin-top: 18px;">
        <div class="section-head" style="padding: 18px 18px 0;">
            <div>
                <h2 class="section-title">Clear Log</h2>
                <p class="helper">Remove only `audit_logs` rows. Today is always blocked.</p>
            </div>
        </div>
        <form method="GET" style="padding: 18px;">
            <input type="hidden" name="section" value="clear_log">
            <input type="hidden" name="preview" value="clear_log">
            <div class="form-grid">
                <label>
                    <span>Date from</span>
                    <input type="date" name="log_date_from" value="<?= e($clearLogInput['date_from']) ?>">
                </label>
                <label>
                    <span>Date to</span>
                    <input type="date" name="log_date_to" value="<?= e($clearLogInput['date_to']) ?>">
                </label>
                <label>
                    <span>Module</span>
                    <select name="log_module">
                        <?php foreach (data_maintenance_module_labels() as $moduleKey => $moduleLabel): ?>
                            <option value="<?= e($moduleKey) ?>"<?= $clearLogInput['module'] === $moduleKey ? ' selected' : '' ?>><?= e($moduleLabel) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>
                    <span>Action</span>
                    <select name="log_action">
                        <?php foreach (data_maintenance_action_labels() as $actionKey => $actionLabel): ?>
                            <option value="<?= e($actionKey) ?>"<?= $clearLogInput['action'] === $actionKey ? ' selected' : '' ?>><?= e($actionLabel) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>
                    <span>Branch</span>
                    <select name="log_branch_name">
                        <option value="">All branches</option>
                        <?php foreach ($branchOptions as $branchName): ?>
                            <option value="<?= e($branchName) ?>"<?= $clearLogInput['branch_name'] === $branchName ? ' selected' : '' ?>><?= e($branchName) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
            </div>
            <div class="button-row" style="margin-top: 16px;">
                <button class="button" type="submit">Preview Clear Log</button>
                <a class="button button-secondary" href="<?= e(data_maintenance_section_url('clear_log')) ?>">Reset</a>
            </div>
        </form>

        <?php if ($clearLogPreview !== null): ?>
            <div style="padding: 0 18px 18px;">
                <?php foreach ($clearLogPreview['errors'] as $errorMessage): ?>
                    <p class="helper is-danger"><?= e(translate_text($errorMessage)) ?></p>
                <?php endforeach; ?>
                <?php foreach ($clearLogPreview['warnings'] as $warningMessage): ?>
                    <p class="helper is-danger"><?= e(translate_text($warningMessage)) ?></p>
                <?php endforeach; ?>

                <div class="stats-grid" style="margin-top: 12px;">
                    <article class="stat-card">
                        <span class="stat-label">Matched logs</span>
                        <strong class="stat-value"><?= number_format((int) ($clearLogPreview['summary']['total_logs'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Row cap</span>
                        <strong class="stat-value"><?= number_format((int) ($clearLogPreview['summary']['row_limit'] ?? 0)) ?></strong>
                    </article>
                </div>

                <div class="grid grid-2" style="margin-top: 18px;">
                    <div class="table-card">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">By module</h3>
                            </div>
                        </div>
                        <table>
                            <thead><tr><th>Module</th><th>Rows</th></tr></thead>
                            <tbody>
                            <?php if (empty($clearLogPreview['module_rows'])): ?>
                                <tr><td colspan="2">No rows</td></tr>
                            <?php else: ?>
                                <?php foreach ($clearLogPreview['module_rows'] as $row): ?>
                                    <tr>
                                        <td><?= e(data_maintenance_module_labels()[(string) ($row['module_key'] ?? '')] ?? (string) ($row['module_key'] ?? '')) ?></td>
                                        <td><?= number_format((int) ($row['row_count'] ?? 0)) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="table-card">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">By action</h3>
                            </div>
                        </div>
                        <table>
                            <thead><tr><th>Action</th><th>Rows</th></tr></thead>
                            <tbody>
                            <?php if (empty($clearLogPreview['action_rows'])): ?>
                                <tr><td colspan="2">No rows</td></tr>
                            <?php else: ?>
                                <?php foreach ($clearLogPreview['action_rows'] as $row): ?>
                                    <tr>
                                        <td><?= e(data_maintenance_action_labels()[(string) ($row['action_key'] ?? '')] ?? (string) ($row['action_key'] ?? '')) ?></td>
                                        <td><?= number_format((int) ($row['row_count'] ?? 0)) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <?php if (!empty($clearLogPreview['can_execute'])): ?>
                    <form method="POST" action="../process/run_data_maintenance.php" style="margin-top: 18px;">
                        <input type="hidden" name="maintenance_type" value="clear_log">
                        <input type="hidden" name="return_section" value="clear_log">
                        <input type="hidden" name="date_from" value="<?= e($clearLogPreview['filters']['date_from']) ?>">
                        <input type="hidden" name="date_to" value="<?= e($clearLogPreview['filters']['date_to']) ?>">
                        <input type="hidden" name="module" value="<?= e($clearLogPreview['filters']['module']) ?>">
                        <input type="hidden" name="action" value="<?= e($clearLogPreview['filters']['action']) ?>">
                        <input type="hidden" name="branch_name" value="<?= e($clearLogPreview['filters']['branch_name']) ?>">
                        <label>
                            <span><?= data_maintenance_text('พิมพ์ <strong>CLEAR LOG</strong> เพื่อยืนยัน', 'Type <strong>CLEAR LOG</strong> to confirm') ?></span>
                            <input type="text" name="confirm_phrase" value="">
                        </label>
                        <div class="button-row" style="margin-top: 16px;">
                            <button class="button button-danger" type="submit">Execute Clear Log</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </section>
<?php endif; ?>

<?php if (can_access($conn, 'maintenance_clear_booking_queue') && $maintenanceSection === 'clear_booking_queue'): ?>
    <section class="table-card" style="margin-top: 18px;">
        <div class="section-head" style="padding: 18px 18px 0;">
            <div>
                <h2 class="section-title">Clear Booking / Queue</h2>
                <p class="helper">Only unpaid booking rows in Waiting or Cancelled status can be removed here.</p>
            </div>
        </div>
        <form method="GET" style="padding: 18px;">
            <input type="hidden" name="section" value="clear_booking_queue">
            <input type="hidden" name="preview" value="clear_booking_queue">
            <div class="form-grid">
                <label>
                    <span>Branch</span>
                    <select name="booking_branch_name">
                        <option value="">Select branch</option>
                        <?php foreach ($branchOptions as $branchName): ?>
                            <option value="<?= e($branchName) ?>"<?= $clearBookingInput['branch_name'] === $branchName ? ' selected' : '' ?>><?= e($branchName) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>
                    <span>Date from</span>
                    <input type="date" name="booking_date_from" value="<?= e($clearBookingInput['date_from']) ?>">
                </label>
                <label>
                    <span>Date to</span>
                    <input type="date" name="booking_date_to" value="<?= e($clearBookingInput['date_to']) ?>">
                </label>
            </div>
            <div class="grid grid-2" style="margin-top: 12px;">
                <?php foreach (maintenance_allowed_booking_statuses() as $statusKey): ?>
                    <label class="checkbox-card">
                        <input type="checkbox" name="booking_statuses[]" value="<?= e($statusKey) ?>"<?= data_maintenance_checkbox_checked($clearBookingInput['statuses'], $statusKey) ?>>
                        <span><?= e(status_label($statusKey)) ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
            <div class="button-row" style="margin-top: 16px;">
                <button class="button" type="submit">Preview Clear Booking / Queue</button>
                <a class="button button-secondary" href="<?= e(data_maintenance_section_url('clear_booking_queue')) ?>">Reset</a>
            </div>
        </form>

        <?php if ($clearBookingPreview !== null): ?>
            <div style="padding: 0 18px 18px;">
                <?php foreach ($clearBookingPreview['errors'] as $errorMessage): ?>
                    <p class="helper is-danger"><?= e(translate_text($errorMessage)) ?></p>
                <?php endforeach; ?>
                <?php foreach ($clearBookingPreview['warnings'] as $warningMessage): ?>
                    <p class="helper is-danger"><?= e(translate_text($warningMessage)) ?></p>
                <?php endforeach; ?>

                <div class="stats-grid" style="margin-top: 12px;">
                    <article class="stat-card">
                        <span class="stat-label">Matched</span>
                        <strong class="stat-value"><?= number_format((int) ($clearBookingPreview['summary']['matched_orders'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Eligible</span>
                        <strong class="stat-value"><?= number_format((int) ($clearBookingPreview['summary']['eligible_orders'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Blocked</span>
                        <strong class="stat-value"><?= number_format((int) ($clearBookingPreview['summary']['blocked_orders'] ?? 0)) ?></strong>
                    </article>
                </div>

                <div class="grid grid-2" style="margin-top: 18px;">
                    <div class="table-card">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">Eligible bills</h3>
                            </div>
                        </div>
                        <table>
                            <thead><tr><th>Bill</th><th>Status</th><th>Total</th></tr></thead>
                            <tbody>
                            <?php if (empty($clearBookingPreview['eligible_orders'])): ?>
                                <tr><td colspan="3">No eligible bills</td></tr>
                            <?php else: ?>
                                <?php foreach ($clearBookingPreview['eligible_orders'] as $row): ?>
                                    <tr>
                                        <td><?= e((string) ($row['bill_number'] ?? '')) ?></td>
                                        <td><?= e(status_label((string) ($row['status'] ?? ''))) ?></td>
                                        <td><?= number_format((float) ($row['total_price'] ?? 0), 2) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="table-card">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">Blocked reasons</h3>
                            </div>
                        </div>
                        <table>
                            <thead><tr><th>Reason</th><th>Bills</th></tr></thead>
                            <tbody>
                            <?php if (empty($clearBookingPreview['blocked_reasons'])): ?>
                                <tr><td colspan="2">No blocked reasons</td></tr>
                            <?php else: ?>
                                <?php foreach ($clearBookingPreview['blocked_reasons'] as $reason => $count): ?>
                                    <tr>
                                        <td><?= e(data_maintenance_reason_label((string) $reason)) ?></td>
                                        <td><?= number_format((int) $count) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <?php if (!empty($clearBookingPreview['blocked_orders'])): ?>
                    <div class="table-card" style="margin-top: 18px;">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">Blocked bills</h3>
                            </div>
                        </div>
                        <table>
                            <thead><tr><th>Bill</th><th>Status</th><th>Reasons</th></tr></thead>
                            <tbody>
                            <?php foreach ($clearBookingPreview['blocked_orders'] as $row): ?>
                                <tr>
                                    <td><?= e((string) ($row['bill_number'] ?? '')) ?></td>
                                    <td><?= e(status_label((string) ($row['status'] ?? ''))) ?></td>
                                    <td><?= e(implode(', ', array_map('data_maintenance_reason_label', (array) ($row['blocked_reasons'] ?? array())))) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>

                <?php if (!empty($clearBookingPreview['can_execute'])): ?>
                    <form method="POST" action="../process/run_data_maintenance.php" style="margin-top: 18px;">
                        <input type="hidden" name="maintenance_type" value="clear_booking_queue">
                        <input type="hidden" name="return_section" value="clear_booking_queue">
                        <input type="hidden" name="branch_name" value="<?= e($clearBookingPreview['filters']['branch_name']) ?>">
                        <input type="hidden" name="date_from" value="<?= e($clearBookingPreview['filters']['date_from']) ?>">
                        <input type="hidden" name="date_to" value="<?= e($clearBookingPreview['filters']['date_to']) ?>">
                        <?= data_maintenance_hidden_array('statuses', (array) $clearBookingPreview['filters']['statuses']) ?>
                        <label>
                            <span><?= data_maintenance_text('พิมพ์ <strong>CLEAR BOOKING</strong> เพื่อยืนยัน', 'Type <strong>CLEAR BOOKING</strong> to confirm') ?></span>
                            <input type="text" name="confirm_phrase" value="">
                        </label>
                        <div class="button-row" style="margin-top: 16px;">
                            <button class="button button-danger" type="submit">Execute Clear Booking / Queue</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </section>
<?php endif; ?>

<?php if (can_access($conn, 'maintenance_clear_sale') && $maintenanceSection === 'clear_sale'): ?>
    <section class="table-card" style="margin-top: 18px;">
        <div class="section-head" style="padding: 18px 18px 0;">
            <div>
                <h2 class="section-title">Clear Sale</h2>
                <p class="helper">Use this only for closed paid bills that must be removed after reversing financial side effects.</p>
            </div>
        </div>
        <form method="GET" style="padding: 18px;">
            <input type="hidden" name="section" value="clear_sale">
            <input type="hidden" name="preview" value="clear_sale">
            <div class="form-grid">
                <label>
                    <span>Branch</span>
                    <select name="sale_branch_name">
                        <option value="">Select branch</option>
                        <?php foreach ($branchOptions as $branchName): ?>
                            <option value="<?= e($branchName) ?>"<?= $clearSaleInput['branch_name'] === $branchName ? ' selected' : '' ?>><?= e($branchName) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>
                    <span>Date from</span>
                    <input type="date" name="sale_date_from" value="<?= e($clearSaleInput['date_from']) ?>">
                </label>
                <label>
                    <span>Date to</span>
                    <input type="date" name="sale_date_to" value="<?= e($clearSaleInput['date_to']) ?>">
                </label>
                <label>
                    <span>Order source</span>
                    <select name="sale_order_source">
                        <option value="both"<?= $clearSaleInput['order_source'] === 'both' ? ' selected' : '' ?>><?= e(data_maintenance_order_source_label('both')) ?></option>
                        <option value="booking"<?= $clearSaleInput['order_source'] === 'booking' ? ' selected' : '' ?>><?= e(data_maintenance_order_source_label('booking')) ?></option>
                        <option value="quick_service"<?= $clearSaleInput['order_source'] === 'quick_service' ? ' selected' : '' ?>><?= e(data_maintenance_order_source_label('quick_service')) ?></option>
                    </select>
                </label>
            </div>
            <div class="grid grid-2" style="margin-top: 12px;">
                <?php foreach (maintenance_allowed_sale_statuses() as $statusKey): ?>
                    <label class="checkbox-card">
                        <input type="checkbox" name="sale_statuses[]" value="<?= e($statusKey) ?>"<?= data_maintenance_checkbox_checked($clearSaleInput['statuses'], $statusKey) ?>>
                        <span><?= e(status_label($statusKey)) ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
            <div class="button-row" style="margin-top: 16px;">
                <button class="button" type="submit">Preview Clear Sale</button>
                <a class="button button-secondary" href="<?= e(data_maintenance_section_url('clear_sale')) ?>">Reset</a>
            </div>
        </form>

        <?php if ($clearSalePreview !== null): ?>
            <div style="padding: 0 18px 18px;">
                <?php foreach ($clearSalePreview['errors'] as $errorMessage): ?>
                    <p class="helper is-danger"><?= e(translate_text($errorMessage)) ?></p>
                <?php endforeach; ?>
                <?php foreach ($clearSalePreview['warnings'] as $warningMessage): ?>
                    <p class="helper is-danger"><?= e(translate_text($warningMessage)) ?></p>
                <?php endforeach; ?>

                <div class="stats-grid" style="margin-top: 12px;">
                    <article class="stat-card">
                        <span class="stat-label">Matched</span>
                        <strong class="stat-value"><?= number_format((int) ($clearSalePreview['summary']['matched_orders'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Eligible</span>
                        <strong class="stat-value"><?= number_format((int) ($clearSalePreview['summary']['eligible_orders'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Blocked</span>
                        <strong class="stat-value"><?= number_format((int) ($clearSalePreview['summary']['blocked_orders'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Payment total</span>
                        <strong class="stat-value"><?= number_format((float) ($clearSalePreview['summary']['payment_total'] ?? 0), 2) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Reverse loyalty</span>
                        <strong class="stat-value"><?= number_format((int) ($clearSalePreview['summary']['loyalty_reverse_points'] ?? 0)) ?></strong>
                    </article>
                    <article class="stat-card">
                        <span class="stat-label">Reverse package usage</span>
                        <strong class="stat-value"><?= number_format((int) ($clearSalePreview['summary']['package_usages_to_reverse'] ?? 0)) ?></strong>
                    </article>
                </div>

                <div class="grid grid-2" style="margin-top: 18px;">
                    <div class="table-card">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">Eligible bills</h3>
                            </div>
                        </div>
                        <table>
                            <thead><tr><th>Bill</th><th>Source</th><th>Paid</th></tr></thead>
                            <tbody>
                            <?php if (empty($clearSalePreview['eligible_orders'])): ?>
                                <tr><td colspan="3">No eligible bills</td></tr>
                            <?php else: ?>
                                <?php foreach ($clearSalePreview['eligible_orders'] as $row): ?>
                                    <tr>
                                        <td><?= e((string) ($row['bill_number'] ?? '')) ?></td>
                                        <td><?= e(data_maintenance_order_source_label((string) ($row['order_source'] ?? '-'))) ?></td>
                                        <td><?= number_format((float) ($row['paid_amount'] ?? 0), 2) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="table-card">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">Blocked reasons</h3>
                            </div>
                        </div>
                        <table>
                            <thead><tr><th>Reason</th><th>Bills</th></tr></thead>
                            <tbody>
                            <?php if (empty($clearSalePreview['blocked_reasons'])): ?>
                                <tr><td colspan="2">No blocked reasons</td></tr>
                            <?php else: ?>
                                <?php foreach ($clearSalePreview['blocked_reasons'] as $reason => $count): ?>
                                    <tr>
                                        <td><?= e(data_maintenance_reason_label((string) $reason)) ?></td>
                                        <td><?= number_format((int) $count) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <?php if (!empty($clearSalePreview['blocked_orders'])): ?>
                    <div class="table-card" style="margin-top: 18px;">
                        <div class="section-head" style="padding: 18px 18px 0;">
                            <div>
                                <h3 class="section-title">Blocked bills</h3>
                            </div>
                        </div>
                        <table>
                            <thead><tr><th>Bill</th><th>Status</th><th>Reasons</th></tr></thead>
                            <tbody>
                            <?php foreach ($clearSalePreview['blocked_orders'] as $row): ?>
                                <tr>
                                    <td><?= e((string) ($row['bill_number'] ?? '')) ?></td>
                                    <td><?= e(status_label((string) ($row['status'] ?? ''))) ?> / <?= e(payment_status_label((string) ($row['payment_status'] ?? ''))) ?></td>
                                    <td><?= e(implode(', ', array_map('data_maintenance_reason_label', (array) ($row['blocked_reasons'] ?? array())))) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>

                <?php if (!empty($clearSalePreview['can_execute'])): ?>
                    <form method="POST" action="../process/run_data_maintenance.php" style="margin-top: 18px;">
                        <input type="hidden" name="maintenance_type" value="clear_sale">
                        <input type="hidden" name="return_section" value="clear_sale">
                        <input type="hidden" name="branch_name" value="<?= e($clearSalePreview['filters']['branch_name']) ?>">
                        <input type="hidden" name="date_from" value="<?= e($clearSalePreview['filters']['date_from']) ?>">
                        <input type="hidden" name="date_to" value="<?= e($clearSalePreview['filters']['date_to']) ?>">
                        <input type="hidden" name="order_source" value="<?= e($clearSalePreview['filters']['order_source']) ?>">
                        <?= data_maintenance_hidden_array('statuses', (array) $clearSalePreview['filters']['statuses']) ?>
                        <label>
                            <span><?= data_maintenance_text('พิมพ์ <strong>CLEAR SALE</strong> เพื่อยืนยัน', 'Type <strong>CLEAR SALE</strong> to confirm') ?></span>
                            <input type="text" name="confirm_phrase" value="">
                        </label>
                        <div class="button-row" style="margin-top: 16px;">
                            <button class="button button-danger" type="submit">Execute Clear Sale</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </section>
<?php endif; ?>

<?php
ob_end_flush();
render_page_end();
?>
