<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

require_login($conn);

process_post_only_or_redirect('../pages/data_maintenance.php');

function maintenance_redirect_query(string $maintenanceType, array $filters): string
{
    if ($maintenanceType === 'clear_log') {
        return http_build_query(array(
            'preview' => 'clear_log',
            'log_date_from' => (string) ($filters['date_from'] ?? ''),
            'log_date_to' => (string) ($filters['date_to'] ?? ''),
            'log_module' => (string) ($filters['module'] ?? ''),
            'log_action' => (string) ($filters['action'] ?? ''),
            'log_branch_name' => (string) ($filters['branch_name'] ?? ''),
        ));
    }

    if ($maintenanceType === 'clear_booking_queue') {
        return http_build_query(array(
            'preview' => 'clear_booking_queue',
            'booking_branch_name' => (string) ($filters['branch_name'] ?? ''),
            'booking_date_from' => (string) ($filters['date_from'] ?? ''),
            'booking_date_to' => (string) ($filters['date_to'] ?? ''),
            'booking_statuses' => array_values((array) ($filters['statuses'] ?? array())),
        ));
    }

    if ($maintenanceType === 'clear_sale') {
        return http_build_query(array(
            'preview' => 'clear_sale',
            'sale_branch_name' => (string) ($filters['branch_name'] ?? ''),
            'sale_date_from' => (string) ($filters['date_from'] ?? ''),
            'sale_date_to' => (string) ($filters['date_to'] ?? ''),
            'sale_order_source' => (string) ($filters['order_source'] ?? 'both'),
            'sale_statuses' => array_values((array) ($filters['statuses'] ?? array())),
        ));
    }

    if ($maintenanceType === 'reset_operational_data') {
        return http_build_query(array(
            'preview' => 'reset_operational_data',
            'reset_include_logs' => !empty($filters['include_logs']) ? '1' : '0',
            'reset_reset_counters' => !empty($filters['reset_counters']) ? '1' : '0',
        ));
    }

    if ($maintenanceType === 'cleanup_quick_service_guest') {
        return http_build_query(array(
            'preview' => 'cleanup_quick_service_guest',
        ));
    }

    if ($maintenanceType === 'restore_database') {
        return http_build_query(array(
            'preview' => 'restore_database',
            'restore_backup_file' => (string) ($filters['backup_file'] ?? ''),
        ));
    }

    return '';
}

$maintenanceType = trim((string) ($_POST['maintenance_type'] ?? ''));
$confirmPhrase = strtoupper(trim((string) ($_POST['confirm_phrase'] ?? '')));
$allowedReturnSections = array(
    'backup_restore',
    'structure_sync',
    'clear_log',
    'clear_booking_queue',
    'clear_sale',
    'reset_operational',
    'cleanup_guest',
);
$returnSection = trim((string) ($_POST['return_section'] ?? ''));
if (!in_array($returnSection, $allowedReturnSections, true)) {
    $returnSection = '';
}

$pagePath = '../pages/data_maintenance.php' . ($returnSection !== '' ? '?section=' . rawurlencode($returnSection) : '');

$config = array(
    'clear_log' => array(
        'permission' => 'maintenance_clear_log',
        'confirm' => 'CLEAR LOG',
        'filters' => array(
            'date_from' => trim((string) ($_POST['date_from'] ?? '')),
            'date_to' => trim((string) ($_POST['date_to'] ?? '')),
            'module' => trim((string) ($_POST['module'] ?? '')),
            'action' => trim((string) ($_POST['action'] ?? '')),
            'branch_name' => trim((string) ($_POST['branch_name'] ?? '')),
        ),
    ),
    'clear_booking_queue' => array(
        'permission' => 'maintenance_clear_booking_queue',
        'confirm' => 'CLEAR BOOKING',
        'filters' => array(
            'branch_name' => trim((string) ($_POST['branch_name'] ?? '')),
            'date_from' => trim((string) ($_POST['date_from'] ?? '')),
            'date_to' => trim((string) ($_POST['date_to'] ?? '')),
            'statuses' => maintenance_selected_values($_POST['statuses'] ?? array()),
        ),
    ),
    'clear_sale' => array(
        'permission' => 'maintenance_clear_sale',
        'confirm' => 'CLEAR SALE',
        'filters' => array(
            'branch_name' => trim((string) ($_POST['branch_name'] ?? '')),
            'date_from' => trim((string) ($_POST['date_from'] ?? '')),
            'date_to' => trim((string) ($_POST['date_to'] ?? '')),
            'order_source' => trim((string) ($_POST['order_source'] ?? 'both')),
            'statuses' => maintenance_selected_values($_POST['statuses'] ?? array()),
        ),
    ),
    'reset_operational_data' => array(
        'permission' => 'maintenance_reset_operational_data',
        'confirm' => 'RESET OPERATIONAL DATA',
        'filters' => array(
            'include_logs' => isset($_POST['include_logs']) ? '1' : '0',
            'reset_counters' => isset($_POST['reset_counters']) ? '1' : '0',
        ),
    ),
    'cleanup_quick_service_guest' => array(
        'permission' => 'maintenance_cleanup_quick_service_guest',
        'confirm' => 'CLEANUP QUICK SERVICE GUEST',
        'filters' => array(),
    ),
    'database_structure_sync_apply' => array(
        'permission' => 'maintenance_apply_database_structure',
        'confirm' => 'APPLY DATABASE STRUCTURE',
        'filters' => array(
            'source' => maintenance_structure_sync_input($_POST['source'] ?? array(), maintenance_structure_sync_current_config($conn)),
            'target' => maintenance_structure_sync_input($_POST['target'] ?? array(), maintenance_structure_sync_custom_defaults($conn)),
        ),
    ),
    'database_structure_sync_apply_manual' => array(
        'permission' => 'maintenance_apply_database_structure',
        'confirm' => 'APPLY MANUAL STRUCTURE',
        'filters' => array(
            'source' => maintenance_structure_sync_input($_POST['source'] ?? array(), maintenance_structure_sync_current_config($conn)),
            'target' => maintenance_structure_sync_input($_POST['target'] ?? array(), maintenance_structure_sync_custom_defaults($conn)),
            'selected_manual_sql' => array_values(array_filter(
                array_map(static fn($value): string => trim((string) $value), (array) ($_POST['selected_manual_sql'] ?? array())),
                static fn(string $value): bool => $value !== ''
            )),
        ),
    ),
    'backup_database' => array(
        'permission' => 'maintenance_backup_database',
        'confirm' => '',
        'filters' => array(),
    ),
    'restore_database' => array(
        'permission' => 'maintenance_restore_database',
        'confirm' => 'RESTORE DATABASE',
        'filters' => array(
            'backup_file' => trim((string) ($_POST['backup_file'] ?? '')),
        ),
    ),
);

if (!isset($config[$maintenanceType])) {
    redirect_with_flash($pagePath, 'error', localized_flash_message('ไม่รู้จักงานบำรุงรักษาที่ร้องขอ', 'Maintenance action was not recognized.'));
}

$actionConfig = $config[$maintenanceType];
$returnQuery = maintenance_redirect_query($maintenanceType, (array) ($actionConfig['filters'] ?? array()));
$returnPath = $pagePath . ($returnQuery !== '' ? (str_contains($pagePath, '?') ? '&' : '?') . $returnQuery : '');

process_ensure_permission_or_redirect(
    $conn,
    (string) ($actionConfig['permission'] ?? ''),
    $pagePath,
    localized_flash_message('คุณไม่มีสิทธิ์รันงานบำรุงรักษานี้', 'You do not have permission to run this maintenance action.')
);

if ((string) ($actionConfig['confirm'] ?? '') !== '' && $confirmPhrase !== (string) ($actionConfig['confirm'] ?? '')) {
    redirect_with_flash($returnPath, 'error', localized_flash_message('ข้อความยืนยันไม่ตรงกัน', 'Typed confirmation did not match.'));
}

try {
    if ($maintenanceType === 'backup_database') {
        $result = maintenance_execute_database_backup($conn, 'manual');
        redirect_with_flash(
            $pagePath,
            'success',
            localized_flash_message(
                'สร้างไฟล์สำรองฐานข้อมูลเรียบร้อยแล้ว: {file_name}',
                'Database backup created: {file_name}',
                array(
                    'file_name' => (string) ($result['file_name'] ?? ''),
                )
            )
        );
    }

    if ($maintenanceType === 'clear_log') {
        $result = maintenance_execute_clear_log($conn, (array) $actionConfig['filters']);
        redirect_with_flash(
            $returnPath,
            'success',
            localized_flash_message(
                'ล้างประวัติการใช้งานเรียบร้อยแล้ว ลบไป {deleted_count} รายการ',
                'Clear Log completed. {deleted_count} log row(s) removed.',
                array(
                    'deleted_count' => number_format((int) ($result['deleted_count'] ?? 0)),
                )
            )
        );
    }

    if ($maintenanceType === 'clear_booking_queue') {
        $result = maintenance_execute_clear_booking_queue($conn, (array) $actionConfig['filters']);
        redirect_with_flash(
            $returnPath,
            'success',
            localized_flash_message(
                'ล้างข้อมูลจอง/คิวเรียบร้อยแล้ว ลบใบจอง {deleted_orders} ใบ',
                'Clear Booking / Queue completed. {deleted_orders} booking bill(s) removed.',
                array(
                    'deleted_orders' => number_format((int) ($result['deleted_orders'] ?? 0)),
                )
            )
        );
    }

    if ($maintenanceType === 'clear_sale') {
        $result = maintenance_execute_clear_sale($conn, (array) $actionConfig['filters']);
        $deletedOrders = (int) (($result['deleted_counts']['orders'] ?? 0));
        redirect_with_flash(
            $returnPath,
            'success',
            localized_flash_message(
                'ล้างข้อมูลยอดขายเรียบร้อยแล้ว ลบบิลขาย {deleted_orders} ใบ',
                'Clear Sale completed. {deleted_orders} sale bill(s) removed.',
                array(
                    'deleted_orders' => number_format($deletedOrders),
                )
            )
        );
    }

    if ($maintenanceType === 'reset_operational_data') {
        $result = maintenance_execute_reset_operational_data($conn, (array) $actionConfig['filters']);
        $deletedOrders = (int) (($result['deleted_counts']['orders'] ?? 0));
        $deletedCustomers = (int) (($result['deleted_counts']['customers'] ?? 0));
        redirect_with_flash(
            $returnPath,
            'success',
            localized_flash_message(
                'รีเซ็ตข้อมูลการดำเนินงานเรียบร้อยแล้ว ลบบิล {deleted_orders} ใบ และข้อมูลลูกค้า {deleted_customers} รายการ',
                'Reset Operational Data completed. Removed {deleted_orders} bill(s) and {deleted_customers} customer record(s).',
                array(
                    'deleted_orders' => number_format($deletedOrders),
                    'deleted_customers' => number_format($deletedCustomers),
                )
            )
        );
    }

    if ($maintenanceType === 'cleanup_quick_service_guest') {
        $result = maintenance_execute_cleanup_quick_service_guest($conn);
        redirect_with_flash(
            $returnPath,
            'success',
            localized_flash_message(
                'ล้างข้อมูลลูกค้า Quick Service เรียบร้อยแล้ว อัปเดตรถ {updated_rows} รายการ',
                'Quick Service guest cleanup completed. {updated_rows} vehicle row(s) updated.',
                array(
                    'updated_rows' => number_format((int) ($result['updated_rows'] ?? 0)),
                )
            )
        );
    }

    if ($maintenanceType === 'database_structure_sync_apply') {
        $result = maintenance_execute_database_structure_sync(
            $conn,
            (array) (($actionConfig['filters']['source'] ?? array())),
            (array) (($actionConfig['filters']['target'] ?? array()))
        );
        redirect_with_flash(
            $pagePath,
            'success',
            localized_flash_message(
                'ปรับโครงสร้างฐานข้อมูลเรียบร้อยแล้ว ใช้คำสั่ง SQL ที่ปลอดภัย {executed_count} รายการกับฐานข้อมูลปลายทาง',
                'Database Structure Sync completed. {executed_count} safe SQL statement(s) applied to target.',
                array(
                    'executed_count' => number_format((int) ($result['executed_count'] ?? 0)),
                )
            )
        );
    }

    if ($maintenanceType === 'database_structure_sync_apply_manual') {
        $result = maintenance_execute_database_structure_manual_sync(
            $conn,
            (array) (($actionConfig['filters']['source'] ?? array())),
            (array) (($actionConfig['filters']['target'] ?? array())),
            (array) (($actionConfig['filters']['selected_manual_sql'] ?? array()))
        );
        redirect_with_flash(
            $pagePath,
            'success',
            localized_flash_message(
                'ปรับโครงสร้างฐานข้อมูลแบบเลือกเองเรียบร้อยแล้ว เลือก {selected_item_count} รายการ และรัน SQL {executed_count} รายการกับฐานข้อมูลปลายทาง',
                'Database Structure Sync manual apply completed. {selected_item_count} item(s) selected and {executed_count} SQL statement(s) executed on target.',
                array(
                    'selected_item_count' => number_format((int) ($result['selected_item_count'] ?? 0)),
                    'executed_count' => number_format((int) ($result['executed_count'] ?? 0)),
                )
            )
        );
    }

    if ($maintenanceType === 'restore_database') {
        $result = maintenance_execute_database_restore($conn, (string) (($actionConfig['filters']['backup_file'] ?? '')));
        $preRestore = (string) (($result['pre_restore_backup']['file_name'] ?? ''));
        redirect_with_flash(
            $returnPath,
            'success',
            localized_flash_message(
                'กู้คืนฐานข้อมูลเรียบร้อยแล้วจาก {restore_file} และสำรองก่อนกู้คืนไว้ที่ {pre_restore_file}',
                'Database restore completed from {restore_file}. Pre-restore backup: {pre_restore_file}',
                array(
                    'restore_file' => (string) ($result['restore_file'] ?? ''),
                    'pre_restore_file' => $preRestore,
                )
            )
        );
    }

    redirect_with_flash($pagePath, 'error', localized_flash_message('งานบำรุงรักษาไม่ได้ถูกดำเนินการ', 'Maintenance action did not run.'));
} catch (Throwable $exception) {
    process_handle_exception_and_redirect(
        $conn,
        $exception,
        'run_data_maintenance',
        $returnPath,
        localized_flash_message('งานบำรุงรักษาไม่สำเร็จ', 'Maintenance action failed.'),
        array(
            'maintenance_type' => $maintenanceType,
            'return_section' => $returnSection,
        ),
        array(),
        true
    );
}
