<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/app/bootstrap.php';
require_login();

if (!navigation_can('settings.manage', ['super_admin','clinic_admin']) && !navigation_can('system.manage', ['super_admin','clinic_admin']) && !role_context_has(['super_admin','clinic_admin'])) {
    http_response_code(403);
    exit('Access denied.');
}

function dental_kiosk_root_url(): string
{
    $configured = rtrim((string) app_config('app.url', ''), '/');
    if ($configured !== '') {
        return $configured;
    }
    $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
    $scheme = $https ? 'https' : 'http';
    $host = (string) ($_SERVER['HTTP_HOST'] ?? 'localhost');
    $script = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? '/'));
    $dir = rtrim(dirname($script), '/.');
    if (basename($dir) === 'handlers') {
        $dir = rtrim(dirname($dir), '/.');
    }
    return $scheme . '://' . $host . ($dir !== '' ? $dir : '');
}

function dental_kiosk_entry_url(string $entry): string
{
    return dental_kiosk_root_url() . '/' . ltrim($entry, '/');
}

$browser = strtolower(trim((string) ($_GET['browser'] ?? 'edge')));
$target = strtolower(trim((string) ($_GET['target'] ?? 'login')));
$mode = strtolower(trim((string) ($_GET['mode'] ?? 'shortcut')));

if (!in_array($browser, ['edge', 'chrome'], true)) {
    $browser = 'edge';
}
if (!in_array($mode, ['shortcut', 'batch'], true)) {
    $mode = 'shortcut';
}

// Use physical, server-rendered entry points for kiosk launchers.
// Clean slugs are convenient in the app, but kiosk shortcuts must not depend on rewrite rules.
$targetPaths = [
    'login' => 'login.php',
    'dashboard' => 'route.php?route=dashboard',
    'queue_display' => 'route.php?route=queue_display',
    'appointments' => 'route.php?route=appointments',
    'billing' => 'route.php?route=billing',
];

$entry = $targetPaths[$target] ?? 'login.php';
$url = dental_kiosk_entry_url($entry);
$safeTarget = preg_replace('/[^A-Za-z0-9_-]+/', '-', $target);
$browserLabel = $browser === 'edge' ? 'Edge' : 'Chrome';
$profileDir = $browser === 'edge' ? '%LOCALAPPDATA%\\DentalCareKioskEdge' : '%LOCALAPPDATA%\\DentalCareKioskChrome';
$kioskArgs = $browser === 'edge'
    ? '--no-first-run --user-data-dir="' . $profileDir . '" --kiosk "' . $url . '" --edge-kiosk-type=fullscreen'
    : '--no-first-run --user-data-dir="' . $profileDir . '" --kiosk "' . $url . '"';

if ($mode === 'batch') {
    $filename = 'DentalCare-Kiosk-' . $browserLabel . '-' . $safeTarget . '.bat';
    $lines = [
        '@echo off',
        'title DentalCare Kiosk Launcher',
        'set "DENTALCARE_URL=' . $url . '"',
        '',
    ];
    if ($browser === 'edge') {
        $lines[] = 'set "EDGE_EXE=%ProgramFiles(x86)%\\Microsoft\\Edge\\Application\\msedge.exe"';
        $lines[] = 'if not exist "%EDGE_EXE%" set "EDGE_EXE=%ProgramFiles%\\Microsoft\\Edge\\Application\\msedge.exe"';
        $lines[] = 'if not exist "%EDGE_EXE%" (';
        $lines[] = '  echo Microsoft Edge was not found. Install Edge or use the Chrome launcher.';
        $lines[] = '  pause';
        $lines[] = '  exit /b 1';
        $lines[] = ')';
        $lines[] = 'start "" "%EDGE_EXE%" --no-first-run --user-data-dir="%LOCALAPPDATA%\\DentalCareKioskEdge" --kiosk "%DENTALCARE_URL%" --edge-kiosk-type=fullscreen';
    } else {
        $lines[] = 'set "CHROME_EXE=%ProgramFiles%\\Google\\Chrome\\Application\\chrome.exe"';
        $lines[] = 'if not exist "%CHROME_EXE%" set "CHROME_EXE=%ProgramFiles(x86)%\\Google\\Chrome\\Application\\chrome.exe"';
        $lines[] = 'if not exist "%CHROME_EXE%" (';
        $lines[] = '  echo Google Chrome was not found. Install Chrome or use the Edge launcher.';
        $lines[] = '  pause';
        $lines[] = '  exit /b 1';
        $lines[] = ')';
        $lines[] = 'start "" "%CHROME_EXE%" --no-first-run --user-data-dir="%LOCALAPPDATA%\\DentalCareKioskChrome" --kiosk "%DENTALCARE_URL%"';
    }
    $lines[] = 'exit /b 0';
    $content = implode("\r\n", $lines) . "\r\n";
} else {
    $filename = 'Create-DentalCare-Kiosk-' . $browserLabel . '-' . $safeTarget . '.cmd';
    $lines = [
        '@echo off',
        'title Create DentalCare Kiosk Shortcut',
        'set "DENTALCARE_URL=' . $url . '"',
        'set "SHORTCUT_NAME=DentalCare Kiosk - ' . $browserLabel . '"',
    ];

    if ($browser === 'edge') {
        $lines[] = 'set "BROWSER_EXE=%ProgramFiles(x86)%\\Microsoft\\Edge\\Application\\msedge.exe"';
        $lines[] = 'if not exist "%BROWSER_EXE%" set "BROWSER_EXE=%ProgramFiles%\\Microsoft\\Edge\\Application\\msedge.exe"';
        $lines[] = 'set "KIOSK_ARGUMENTS=--no-first-run --user-data-dir=""%LOCALAPPDATA%\\DentalCareKioskEdge"" --kiosk ""%DENTALCARE_URL%"" --edge-kiosk-type=fullscreen"';
    } else {
        $lines[] = 'set "BROWSER_EXE=%ProgramFiles%\\Google\\Chrome\\Application\\chrome.exe"';
        $lines[] = 'if not exist "%BROWSER_EXE%" set "BROWSER_EXE=%ProgramFiles(x86)%\\Google\\Chrome\\Application\\chrome.exe"';
        $lines[] = 'set "KIOSK_ARGUMENTS=--no-first-run --user-data-dir=""%LOCALAPPDATA%\\DentalCareKioskChrome"" --kiosk ""%DENTALCARE_URL%"""';
    }

    $lines[] = 'if not exist "%BROWSER_EXE%" (';
    $lines[] = '  echo Browser was not found on this computer.';
    $lines[] = '  pause';
    $lines[] = '  exit /b 1';
    $lines[] = ')';
    $ps = '$ws=New-Object -ComObject WScript.Shell; '
        . '$desktop=[Environment]::GetFolderPath(' . "'Desktop'" . '); '
        . '$lnk=$ws.CreateShortcut((Join-Path $desktop ($env:SHORTCUT_NAME + ' . "'.lnk'" . '))); '
        . '$lnk.TargetPath=$env:BROWSER_EXE; '
        . '$lnk.Arguments=$env:KIOSK_ARGUMENTS; '
        . '$lnk.WorkingDirectory=Split-Path $env:BROWSER_EXE; '
        . '$lnk.IconLocation=$env:BROWSER_EXE; '
        . '$lnk.Save();';
    $lines[] = 'powershell -NoProfile -ExecutionPolicy Bypass -Command "' . $ps . '"';
    $lines[] = 'echo.';
    $lines[] = 'echo DentalCare Kiosk shortcut has been created on the Desktop.';
    $lines[] = 'echo It points to: %DENTALCARE_URL%';
    $lines[] = 'echo Double-click the Desktop shortcut to open DentalCare fullscreen.';
    $lines[] = 'echo If it opens in a normal window, close all existing Chrome/Edge windows and open the shortcut again.';
    $lines[] = 'echo To exit kiosk mode, press Alt + F4.';
    $lines[] = 'pause';
    $content = implode("\r\n", $lines) . "\r\n";
}

if (!headers_sent()) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . strlen($content));
    header('X-Content-Type-Options: nosniff');
}
echo $content;
