<?php
declare(strict_types=1);

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

require_permission($conn, 'services');

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

function quick_service_settings_redirect_url(string $scopeKey, string $branchName = ''): string
{
    $query = http_build_query(array_filter(array(
        'scope' => $scopeKey,
        'branch' => $branchName,
    ), static fn ($value): bool => $value !== ''));

    return '../pages/quick_service_settings.php' . ($query !== '' ? '?' . $query : '');
}

function quick_service_local_upload_path(string $appBasePath, string $imageUrl): ?string
{
    $path = parse_url($imageUrl, PHP_URL_PATH);

    if (!is_string($path) || $path === '') {
        return null;
    }

    $normalizedBasePath = $appBasePath !== '' ? rtrim($appBasePath, '/') : '';
    $prefix = ($normalizedBasePath !== '' ? $normalizedBasePath : '') . '/storage/uploads/quick_service/';

    if (!str_starts_with($path, $prefix)) {
        return null;
    }

    $relativePath = ltrim(substr($path, strlen($normalizedBasePath)), '/');
    if ($relativePath === '' || str_contains($relativePath, '..')) {
        return null;
    }

    $absolutePath = dirname(__DIR__) . '/' . str_replace('/', DIRECTORY_SEPARATOR, $relativePath);

    return is_file($absolutePath) ? $absolutePath : null;
}

$scopeKey = trim((string) ($_POST['scope_key'] ?? 'quick_service'));
$scopeKey = array_key_exists($scopeKey, quick_service_qr_scopes()) ? $scopeKey : 'quick_service';
$branchName = normalize_branch_name((string) ($_POST['branch_name'] ?? ''));
$redirectUrl = quick_service_settings_redirect_url($scopeKey, $branchName);

$promptpayId = trim((string) ($_POST['promptpay_id'] ?? ''));
$merchantName = trim((string) ($_POST['merchant_name'] ?? 'CCW Car Care'));
$merchantCity = trim((string) ($_POST['merchant_city'] ?? 'Bangkok'));
$qrImageUrl = trim((string) ($_POST['qr_image_url'] ?? ''));
$removeQrImage = isset($_POST['remove_qr_image']);
$qrImageFile = $_FILES['qr_image_file'] ?? null;

$oldInput = array(
    'scope_key' => $scopeKey,
    'branch_name' => $branchName,
    'promptpay_id' => $promptpayId,
    'merchant_name' => $merchantName,
    'merchant_city' => $merchantCity,
    'qr_image_url' => $qrImageUrl,
    'remove_qr_image' => $removeQrImage ? '1' : '0',
);

$allowedBranches = auth_filter_branch_options($conn, service_branches($conn));
if ($branchName !== '' && !in_array($branchName, $allowedBranches, true)) {
    redirect_with_flash(
        $redirectUrl,
        'error',
        localized_flash_message('Please select a valid branch.', 'Please select a valid branch.'),
        $oldInput
    );
}

$currentExactProfile = quick_service_payment_profile_exact($branchName, $scopeKey);
$currentConfig = $currentExactProfile ?? quick_service_payment_resolve_config($branchName, $scopeKey);
$allProfiles = quick_service_payment_profiles();
$profileKey = quick_service_payment_profile_key($branchName, $scopeKey);
$appBasePath = str_replace('\\', '/', dirname(dirname((string) ($_SERVER['SCRIPT_NAME'] ?? '/'))));
$appBasePath = $appBasePath === '.' || $appBasePath === '/' ? '' : rtrim($appBasePath, '/');
$currentLocalUpload = $currentExactProfile
    ? quick_service_local_upload_path($appBasePath, (string) ($currentExactProfile['qr_image_url'] ?? ''))
    : null;
$nextQrImageUrl = $removeQrImage ? '' : $qrImageUrl;
$newUploadPath = null;

if (
    $nextQrImageUrl !== ''
    && !preg_match('#^[a-z][a-z0-9+.-]*:#i', $nextQrImageUrl)
    && !str_starts_with($nextQrImageUrl, '/')
) {
    $nextQrImageUrl = ($appBasePath !== '' ? $appBasePath : '') . '/' . ltrim($nextQrImageUrl, '/');
}

if ($qrImageFile && (int) ($qrImageFile['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
    $uploadError = (int) ($qrImageFile['error'] ?? UPLOAD_ERR_OK);

    if ($uploadError !== UPLOAD_ERR_OK) {
        redirect_with_flash($redirectUrl, 'error', localized_flash_message('อัปโหลดรูป QR ไม่สำเร็จ', 'QR image upload failed.'), $oldInput);
    }

    $tmpName = (string) ($qrImageFile['tmp_name'] ?? '');
    $imageInfo = @getimagesize($tmpName);
    $mimeType = '';

    if (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $detectedMimeType = $finfo ? finfo_file($finfo, $tmpName) : false;
        if ($finfo) {
            finfo_close($finfo);
        }
        $mimeType = is_string($detectedMimeType) ? trim($detectedMimeType) : '';
    }

    if ($mimeType === '' && is_array($imageInfo)) {
        $mimeType = (string) ($imageInfo['mime'] ?? '');
    }

    if ($mimeType === '') {
        $extension = strtolower((string) pathinfo((string) ($qrImageFile['name'] ?? ''), PATHINFO_EXTENSION));
        $fileContents = @file_get_contents($tmpName);

        if ($extension === 'svg' && is_string($fileContents) && str_contains(strtolower($fileContents), '<svg')) {
            $mimeType = 'image/svg+xml';
        }
    }

    $allowedMimeTypes = array(
        'image/png' => 'png',
        'image/jpeg' => 'jpg',
        'image/gif' => 'gif',
        'image/webp' => 'webp',
        'image/svg+xml' => 'svg',
    );

    if (!array_key_exists($mimeType, $allowedMimeTypes)) {
        redirect_with_flash($redirectUrl, 'error', localized_flash_message('อนุญาตเฉพาะไฟล์รูป PNG, JPG, GIF, WEBP หรือ SVG', 'Only PNG, JPG, GIF, WEBP or SVG image files are allowed.'), $oldInput);
    }

    $targetDirectory = dirname(__DIR__) . '/storage/uploads/quick_service';
    if (!is_dir($targetDirectory) && !mkdir($targetDirectory, 0777, true) && !is_dir($targetDirectory)) {
        redirect_with_flash($redirectUrl, 'error', localized_flash_message('ไม่สามารถสร้างโฟลเดอร์รูป QR ได้', 'QR image directory could not be created.'), $oldInput);
    }

    $fileName = 'quick-service-qr-' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '.' . $allowedMimeTypes[$mimeType];
    $targetPath = $targetDirectory . '/' . $fileName;

    if (!move_uploaded_file($tmpName, $targetPath)) {
        redirect_with_flash($redirectUrl, 'error', localized_flash_message('บันทึกรูป QR ไม่สำเร็จ', 'QR image could not be saved.'), $oldInput);
    }

    $nextQrImageUrl = ($appBasePath !== '' ? $appBasePath : '') . '/storage/uploads/quick_service/' . $fileName;
    $newUploadPath = $targetPath;
}

$settingsDirectory = dirname(__DIR__) . '/storage/settings';
if (!is_dir($settingsDirectory) && !mkdir($settingsDirectory, 0777, true) && !is_dir($settingsDirectory)) {
    if ($newUploadPath && is_file($newUploadPath)) {
        @unlink($newUploadPath);
    }

    redirect_with_flash($redirectUrl, 'error', localized_flash_message('ไม่สามารถสร้างโฟลเดอร์การตั้งค่าได้', 'Settings directory could not be created.'), $oldInput);
}

$allProfiles[$profileKey] = array(
    'branch_name' => $branchName,
    'scope_key' => $scopeKey,
    'promptpay_id' => $promptpayId,
    'merchant_name' => $merchantName !== '' ? $merchantName : 'CCW Car Care',
    'merchant_city' => $merchantCity !== '' ? $merchantCity : 'Bangkok',
    'qr_image_url' => $nextQrImageUrl,
);

$settingsPayload = array(
    'profiles' => $allProfiles,
);

$jsonPath = quick_service_payment_storage_path();
$encodedSettings = json_encode($settingsPayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

if (!is_string($encodedSettings) || file_put_contents($jsonPath, $encodedSettings) === false) {
    if ($newUploadPath && is_file($newUploadPath)) {
        @unlink($newUploadPath);
    }

    redirect_with_flash($redirectUrl, 'error', localized_flash_message('บันทึกการตั้งค่า Quick Service ไม่สำเร็จ', 'Quick Service settings were not saved.'), $oldInput);
}

if ($currentLocalUpload && is_file($currentLocalUpload) && $currentLocalUpload !== $newUploadPath && $nextQrImageUrl !== (string) ($currentConfig['qr_image_url'] ?? '')) {
    @unlink($currentLocalUpload);
}

redirect_with_flash($redirectUrl, 'success', localized_flash_message('บันทึกการตั้งค่า QR เรียบร้อยแล้ว', 'QR configuration saved.'));
