<?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);

$profiles = quick_service_payment_profiles();
$profileKey = quick_service_payment_profile_key($branchName, $scopeKey);
$profile = $profiles[$profileKey] ?? null;

if (!is_array($profile)) {
    redirect_with_flash($redirectUrl, 'error', localized_flash_message('ไม่พบโปรไฟล์ QR', 'QR profile was not found.'));
}

$appBasePath = str_replace('\\', '/', dirname(dirname((string) ($_SERVER['SCRIPT_NAME'] ?? '/'))));
$appBasePath = $appBasePath === '.' || $appBasePath === '/' ? '' : rtrim($appBasePath, '/');
$qrImageUrl = trim((string) ($profile['qr_image_url'] ?? ''));
$localUploadPath = $qrImageUrl !== '' ? quick_service_local_upload_path($appBasePath, $qrImageUrl) : null;

unset($profiles[$profileKey]);

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

$encodedSettings = json_encode($settingsPayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($encodedSettings) || file_put_contents(quick_service_payment_storage_path(), $encodedSettings) === false) {
    redirect_with_flash($redirectUrl, 'error', localized_flash_message('ลบโปรไฟล์ QR ไม่สำเร็จ', 'QR profile could not be deleted.'));
}

if ($localUploadPath && is_file($localUploadPath)) {
    $imageStillUsed = false;

    foreach ($profiles as $remainingProfile) {
        if (trim((string) ($remainingProfile['qr_image_url'] ?? '')) === $qrImageUrl) {
            $imageStillUsed = true;
            break;
        }
    }

    if (!$imageStillUsed) {
        @unlink($localUploadPath);
    }
}

redirect_with_flash($redirectUrl, 'success', localized_flash_message('ลบโปรไฟล์ QR เรียบร้อยแล้ว', 'QR profile deleted.'));
