<?php

/*
|--------------------------------------------------------------------------
| LARGE FILE WIZARD DOWNLOADER
|--------------------------------------------------------------------------
| PHP 7.4+
|
| ورودی:
|   URL
|   File Name
|
| فایل:
|   filename.part     => دانلود در حال انجام
|   filename          => دانلود کامل
|
| وضعیت:
|   .download-status.json
|
| تنظیمات:
|   .download-config.json
|
| قفل:
|   .download.lock
|--------------------------------------------------------------------------
*/

ini_set('memory_limit', '256M');
ini_set('max_execution_time', '0');

set_time_limit(0);
ignore_user_abort(true);

clearstatcache(true);

session_name('file_transfer_session');
session_start([
    'use_strict_mode' => true,
    'cookie_httponly' => true,
    'cookie_samesite' => 'Lax',
    'cookie_secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'
]);

header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: same-origin');
header('X-Robots-Tag: noindex, nofollow');


/* =========================================================
   FILES
========================================================= */

$statusFile = __DIR__ . '/.download-status.json';
$configFile = __DIR__ . '/.download-config.json';
$lockDir    = __DIR__ . '/.download.lock';
$uploadPrefix = __DIR__ . '/.upload-';
$databaseFile = __DIR__ . '/.file-transfer.sqlite';

$retryDelay = 10;

/* بعد از این تعداد تلاش ناموفق پشت سر هم، دانلود با خطا متوقف می‌شود */
$maxFailureStreak = 60;

const LEGACY_DEFAULT_PASSWORD = '12345@#admin';

function initialPasswordFile()
{
    return __DIR__ . '/.initial-admin-password.txt';
}


/* =========================================================
   AUTHENTICATION AND SQLITE
========================================================= */

function authDatabase()
{
    global $databaseFile;

    static $database;
    if ($database instanceof PDO) {
        return $database;
    }

    if (!extension_loaded('pdo_sqlite')) {
        http_response_code(500);
        die('SQLite support (pdo_sqlite) is required.');
    }

    $databaseExisted = file_exists($databaseFile);
    if (!$databaseExisted) {
        $previousUmask = umask(0077);
        touch($databaseFile);
        umask($previousUmask);
    }

    $database = new PDO('sqlite:' . $databaseFile);
    $database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $database->exec('PRAGMA busy_timeout = 5000');
    $database->exec('PRAGMA foreign_keys = ON');
    @chmod($databaseFile, 0600);
    $database->exec(
        'CREATE TABLE IF NOT EXISTS users (' .
        'id INTEGER PRIMARY KEY AUTOINCREMENT,' .
        'username TEXT NOT NULL UNIQUE,' .
        'password_hash TEXT NOT NULL,' .
        'created_at INTEGER NOT NULL)'
    );
    $database->exec(
        'CREATE TABLE IF NOT EXISTS library (' .
        'id INTEGER PRIMARY KEY AUTOINCREMENT,' .
        'user_id INTEGER NOT NULL,' .
        'name TEXT NOT NULL,' .
        'url TEXT NOT NULL,' .
        'type TEXT NOT NULL DEFAULT \'file\',' .
        'created_at INTEGER NOT NULL,' .
        'UNIQUE(user_id, url),' .
        'FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE)'
    );

    $database->exec(
        'CREATE TABLE IF NOT EXISTS login_attempts (' .
        'id INTEGER PRIMARY KEY AUTOINCREMENT,' .
        'ip TEXT NOT NULL,' .
        'attempted_at INTEGER NOT NULL)'
    );
    $database->exec(
        'CREATE TABLE IF NOT EXISTS transfer_settings (' .
        'user_id INTEGER PRIMARY KEY,' .
        'mode TEXT NOT NULL DEFAULT \'direct\',' .
        'protocol TEXT NOT NULL DEFAULT \'sftp\',' .
        'host TEXT NOT NULL DEFAULT \'\',' .
        'port INTEGER NOT NULL DEFAULT 0,' .
        'remote_path TEXT NOT NULL DEFAULT \'\',' .
        'username TEXT NOT NULL DEFAULT \'\',' .
        'password_enc TEXT NOT NULL DEFAULT \'\',' .
        'ssl_verify INTEGER NOT NULL DEFAULT 1,' .
        'delete_local INTEGER NOT NULL DEFAULT 1,' .
        'updated_at INTEGER NOT NULL,' .
        'FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE)'
    );

    $transferColumns = [];

    foreach ($database->query('PRAGMA table_info(transfer_settings)') as $columnRow) {
        $transferColumns[] = $columnRow['name'];
    }

    $newTransferColumns = [
        'public_domain' => 'TEXT NOT NULL DEFAULT \'\'',
        'public_scheme' => 'TEXT NOT NULL DEFAULT \'https\'',
        'docroot'       => 'TEXT NOT NULL DEFAULT \'public_html\''
    ];

    foreach ($newTransferColumns as $columnName => $columnDefinition) {
        if (!in_array($columnName, $transferColumns, true)) {
            $database->exec('ALTER TABLE transfer_settings ADD COLUMN ' . $columnName . ' ' . $columnDefinition);
        }
    }

    if ((int)$database->query('SELECT COUNT(*) FROM users')->fetchColumn() === 0) {
        /* رمز اولیه تصادفی است و در یک فایل محافظت‌شده کنار index.php ذخیره می‌شود */
        $initialPassword = bin2hex(random_bytes(8));
        $statement = $database->prepare(
            'INSERT INTO users (username, password_hash, created_at) VALUES (?, ?, ?)'
        );
        $statement->execute(['admin', password_hash($initialPassword, PASSWORD_DEFAULT), time()]);
        $previousUmask = umask(0077);
        @file_put_contents(
            initialPasswordFile(),
            "username: admin\npassword: " . $initialPassword . "\n",
            LOCK_EX
        );
        umask($previousUmask);
    }

    return $database;
}


function currentUser()
{
    return isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
}


function requirePostCsrf()
{
    if (
        empty($_POST['csrf']) ||
        empty($_SESSION['csrf']) ||
        !hash_equals($_SESSION['csrf'], $_POST['csrf'])
    ) {
        http_response_code(403);
        die('Invalid request token.');
    }
}


$database = authDatabase();

if (!isset($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}

if (isset($_GET['logout'])) {
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
    }
    session_destroy();
    header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
    exit;
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    requirePostCsrf();
    $clientIp = substr((string)(isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''), 0, 64);
    $submittedUser = trim((string)(isset($_POST['username']) ? $_POST['username'] : ''));

    $database->prepare('DELETE FROM login_attempts WHERE attempted_at < ?')->execute([time() - 86400]);
    $statement = $database->prepare('SELECT COUNT(*) FROM login_attempts WHERE ip = ? AND attempted_at > ?');
    $statement->execute([$clientIp, time() - 900]);

    if ((int)$statement->fetchColumn() >= 5) {
        $loginError = 'تعداد تلاش‌های ناموفق زیاد است. ۱۵ دقیقه بعد دوباره تلاش کنید.';
    } else {
        $statement = $database->prepare('SELECT id, password_hash FROM users WHERE username = ?');
        $statement->execute([$submittedUser]);
        $user = $statement->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify((string)(isset($_POST['password']) ? $_POST['password'] : ''), $user['password_hash'])) {
            $database->prepare('DELETE FROM login_attempts WHERE ip = ?')->execute([$clientIp]);
            session_regenerate_id(true);
            $_SESSION['user_id'] = (int)$user['id'];
            $_SESSION['username'] = $submittedUser;
            $_SESSION['must_change_password'] =
                password_verify(LEGACY_DEFAULT_PASSWORD, $user['password_hash']) ||
                file_exists(initialPasswordFile());
            header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
            exit;
        }

        $database->prepare('INSERT INTO login_attempts (ip, attempted_at) VALUES (?, ?)')->execute([$clientIp, time()]);
        $loginError = 'نام کاربری یا رمز عبور نادرست است.';
    }
}


if (!currentUser()) {
    $csrf = htmlspecialchars($_SESSION['csrf'], ENT_QUOTES, 'UTF-8');
    $loginError = isset($loginError) ? htmlspecialchars($loginError, ENT_QUOTES, 'UTF-8') : '';
    ?><!DOCTYPE html>
    <html lang="fa" dir="rtl"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>ورود</title>
    <style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#080c15;color:#fff;font-family:Segoe UI,Tahoma,sans-serif}.login{width:min(390px,calc(100% - 40px));padding:30px;border:1px solid #263652;border-radius:18px;background:#121928;box-shadow:0 20px 60px #0008}h1{margin-top:0;font-size:24px}label{display:block;margin:14px 0 6px;color:#aab5c8}input{width:100%;padding:12px;box-sizing:border-box;border:1px solid #30415f;border-radius:9px;background:#0c1320;color:#fff}button{width:100%;margin-top:20px;padding:12px;border:0;border-radius:9px;background:#315efb;color:#fff;font-weight:bold}.error{color:#ff9b9b;margin-top:14px}</style></head><body><main class="login"><h1>ورود به انتقال فایل</h1><form method="post" autocomplete="off"><input type="hidden" name="csrf" value="<?php echo $csrf; ?>"><input type="hidden" name="login" value="1"><label>نام کاربری</label><input name="username" autocomplete="username" required><label>رمز عبور</label><input type="password" name="password" autocomplete="current-password" required><button type="submit">ورود</button><?php if (file_exists(initialPasswordFile())): ?><div class="error" style="color:#9ecbff">اولین ورود: نام کاربری و رمز اولیه در فایل .initial-admin-password.txt کنار index.php ذخیره شده است. بعد از ورود رمز را تغییر دهید.</div><?php endif; ?><?php if ($loginError !== ''): ?><div class="error"><?php echo $loginError; ?></div><?php endif; ?></form></main></body></html><?php
    exit;
}


/* =========================================================
   HELPERS
========================================================= */

function formatBytes($bytes)
{
    $bytes = (float)$bytes;

    if ($bytes >= 1024 * 1024 * 1024) {
        return number_format(
            $bytes / 1024 / 1024 / 1024,
            2
        ) . ' GB';
    }

    if ($bytes >= 1024 * 1024) {
        return number_format(
            $bytes / 1024 / 1024,
            2
        ) . ' MB';
    }

    if ($bytes >= 1024) {
        return number_format(
            $bytes / 1024,
            2
        ) . ' KB';
    }

    return number_format($bytes, 0) . ' B';
}


function writeStatus(array $data)
{
    global $statusFile, $statusQuiet, $lastDeliverError;

    if (!empty($statusQuiet)) {
        if (isset($data['status']) && $data['status'] === 'error') {
            $lastDeliverError = isset($data['message']) ? $data['message'] : 'Transfer failed.';
        }

        return;
    }

    $data['time'] = time();

    $tmp = $statusFile . '.tmp';

    file_put_contents(
        $tmp,
        json_encode(
            $data,
            JSON_UNESCAPED_SLASHES |
            JSON_UNESCAPED_UNICODE
        ),
        LOCK_EX
    );

    @rename($tmp, $statusFile);
}


function readStatus()
{
    global $statusFile;

    if (!file_exists($statusFile)) {
        return [
            'status'     => 'idle',
            'downloaded' => 0,
            'total'      => 0,
            'percent'    => 0,
            'speed'      => 0,
            'message'    => 'Ready'
        ];
    }

    $raw = @file_get_contents($statusFile);

    if (!$raw) {
        return [
            'status'     => 'idle',
            'downloaded' => 0,
            'total'      => 0,
            'percent'    => 0,
            'speed'      => 0,
            'message'    => 'Ready'
        ];
    }

    $data = json_decode($raw, true);

    if (!is_array($data)) {
        return [
            'status'     => 'idle',
            'downloaded' => 0,
            'total'      => 0,
            'percent'    => 0,
            'speed'      => 0,
            'message'    => 'Ready'
        ];
    }

    return $data;
}


/* =========================================================
   CONFIG
========================================================= */

function saveConfig($url, $filename)
{
    global $configFile;

    $config = [
        'url'      => $url,
        'filename' => $filename
    ];

    $tmp = $configFile . '.tmp';

    file_put_contents(
        $tmp,
        json_encode(
            $config,
            JSON_UNESCAPED_SLASHES |
            JSON_UNESCAPED_UNICODE
        ),
        LOCK_EX
    );

    @rename($tmp, $configFile);
}


function readConfig()
{
    global $configFile;

    if (!file_exists($configFile)) {
        return null;
    }

    $raw = @file_get_contents($configFile);

    if (!$raw) {
        return null;
    }

    $config = json_decode($raw, true);

    if (
        !is_array($config) ||
        empty($config['url']) ||
        empty($config['filename'])
    ) {
        return null;
    }

    return $config;
}


/* =========================================================
   SAFETY HELPERS
========================================================= */

function hostIsPublic($host)
{
    $host = trim((string)$host, '[] ');

    if ($host === '') {
        return false;
    }

    if (filter_var($host, FILTER_VALIDATE_IP)) {
        return (bool)filter_var(
            $host,
            FILTER_VALIDATE_IP,
            FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
        );
    }

    $addresses = @gethostbynamel($host);

    if (!$addresses) {
        /* resolution problems are reported later by cURL */
        return true;
    }

    foreach ($addresses as $address) {
        if (!filter_var(
            $address,
            FILTER_VALIDATE_IP,
            FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
        )) {
            return false;
        }
    }

    return true;
}


function failDownload($message, $downloaded, $total)
{
    writeStatus([
        'status'     => 'error',
        'downloaded' => $downloaded,
        'total'      => $total,
        'percent'    => $total > 0 ? min(100, ($downloaded / $total) * 100) : 0,
        'speed'      => 0,
        'message'    => $message
    ]);
}


/* =========================================================
   TRANSFER DESTINATION SETTINGS (DIRECT / FTP / FTPS / SFTP)
========================================================= */

function defaultTransferSettings()
{
    return [
        'mode'         => 'direct',
        'protocol'     => 'sftp',
        'host'         => '',
        'port'         => 0,
        'remote_path'  => '',
        'username'     => '',
        'password'     => '',
        'has_password' => false,
        'ssl_verify'   => true,
        'delete_local' => true,
        'public_domain' => '',
        'public_scheme' => 'https',
        'docroot'      => 'public_html'
    ];
}


function transferKey()
{
    static $key = null;

    if ($key !== null) {
        return $key;
    }

    $path = __DIR__ . '/.file-transfer.key';

    if (!file_exists($path)) {
        $previousUmask = umask(0077);
        $written = @file_put_contents($path, bin2hex(random_bytes(32)), LOCK_EX);
        umask($previousUmask);

        if ($written === false) {
            $key = false;
            return $key;
        }
    }

    $raw = trim((string)@file_get_contents($path));
    $key = $raw !== '' ? hash('sha256', $raw, true) : false;

    return $key;
}


function transferCryptoAvailable()
{
    return function_exists('openssl_encrypt') &&
        function_exists('openssl_get_cipher_methods') &&
        in_array('aes-256-gcm', openssl_get_cipher_methods(), true);
}


function encryptTransferSecret($plain)
{
    $key = transferKey();

    if ($key === false || !transferCryptoAvailable()) {
        return false;
    }

    $iv = random_bytes(12);
    $tag = '';
    $cipher = openssl_encrypt($plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);

    if ($cipher === false || $tag === '') {
        return false;
    }

    return 'v1:' . base64_encode($iv . $tag . $cipher);
}


function decryptTransferSecret($stored)
{
    $key = transferKey();

    if ($key === false || !transferCryptoAvailable() || strpos($stored, 'v1:') !== 0) {
        return false;
    }

    $raw = base64_decode(substr($stored, 3), true);

    if ($raw === false || strlen($raw) < 29) {
        return false;
    }

    $iv = substr($raw, 0, 12);
    $tag = substr($raw, 12, 16);
    $cipher = substr($raw, 28);

    return openssl_decrypt($cipher, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
}


function loadTransferSettings($userId)
{
    $settings = defaultTransferSettings();

    $statement = authDatabase()->prepare('SELECT * FROM transfer_settings WHERE user_id = ?');
    $statement->execute([(int)$userId]);
    $row = $statement->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        return $settings;
    }

    $settings['mode'] = $row['mode'] === 'remote' ? 'remote' : 'direct';
    $settings['protocol'] = in_array($row['protocol'], ['sftp', 'ftp', 'ftps'], true)
        ? $row['protocol']
        : 'sftp';
    $settings['host'] = (string)$row['host'];
    $settings['port'] = (int)$row['port'];
    $settings['remote_path'] = (string)$row['remote_path'];
    $settings['username'] = (string)$row['username'];
    $settings['ssl_verify'] = (int)$row['ssl_verify'] === 1;
    $settings['delete_local'] = true;
    $settings['public_domain'] = isset($row['public_domain']) ? (string)$row['public_domain'] : '';
    $settings['public_scheme'] = (isset($row['public_scheme']) && $row['public_scheme'] === 'http') ? 'http' : 'https';
    $settings['docroot'] = (isset($row['docroot']) && $row['docroot'] !== '') ? (string)$row['docroot'] : 'public_html';

    $stored = (string)$row['password_enc'];

    if ($stored !== '') {
        $plain = decryptTransferSecret($stored);

        if ($plain !== false) {
            $settings['password'] = $plain;
            $settings['has_password'] = true;
        }
    }

    return $settings;
}


function saveTransferSettings($userId, array $s, $newPassword)
{
    $database = authDatabase();

    $statement = $database->prepare(
        'INSERT INTO transfer_settings ' .
        '(user_id, mode, protocol, host, port, remote_path, username, ssl_verify, delete_local, ' .
        'public_domain, public_scheme, docroot, updated_at) ' .
        'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ' .
        'ON CONFLICT(user_id) DO UPDATE SET mode = excluded.mode, protocol = excluded.protocol, ' .
        'host = excluded.host, port = excluded.port, remote_path = excluded.remote_path, ' .
        'username = excluded.username, ssl_verify = excluded.ssl_verify, ' .
        'delete_local = excluded.delete_local, public_domain = excluded.public_domain, ' .
        'public_scheme = excluded.public_scheme, docroot = excluded.docroot, updated_at = excluded.updated_at'
    );

    $statement->execute([
        (int)$userId,
        $s['mode'],
        $s['protocol'],
        $s['host'],
        (int)$s['port'],
        $s['remote_path'],
        $s['username'],
        $s['ssl_verify'] ? 1 : 0,
        1,
        $s['public_domain'],
        $s['public_scheme'],
        $s['docroot'],
        time()
    ]);

    if ($newPassword !== null) {
        $statement = $database->prepare('UPDATE transfer_settings SET password_enc = ? WHERE user_id = ?');
        $statement->execute([$newPassword, (int)$userId]);
    }
}


function parseTransferInput(array $input, array $saved)
{
    $s = $saved;
    $s['mode'] = (isset($input['mode']) && $input['mode'] === 'remote') ? 'remote' : 'direct';

    $protocol = strtolower(trim((string)(isset($input['protocol']) ? $input['protocol'] : $saved['protocol'])));

    if (!in_array($protocol, ['sftp', 'ftp', 'ftps'], true)) {
        $protocol = 'sftp';
    }

    $hostInput = trim((string)(isset($input['host']) ? $input['host'] : ''));
    $port = (int)(isset($input['port']) ? $input['port'] : 0);
    $path = trim((string)(isset($input['remote_path']) ? $input['remote_path'] : ''));

    if (strpos($hostInput, '://') !== false) {
        $parts = parse_url($hostInput);

        if (is_array($parts) && !empty($parts['host'])) {
            $scheme = strtolower((string)(isset($parts['scheme']) ? $parts['scheme'] : ''));

            if (in_array($scheme, ['sftp', 'ftp', 'ftps'], true)) {
                $protocol = $scheme;
            }

            $hostInput = $parts['host'];

            if (!empty($parts['port'])) {
                $port = (int)$parts['port'];
            }

            if ($path === '' && !empty($parts['path']) && $parts['path'] !== '/') {
                $path = (string)$parts['path'];
            }
        }
    } elseif (preg_match('/^([^:\/\[\]]+):(\d{1,5})$/', $hostInput, $match)) {
        $hostInput = $match[1];
        $port = (int)$match[2];
    }

    $hostInput = trim($hostInput, '[] ');

    if (
        $hostInput !== '' &&
        !preg_match('/^[A-Za-z0-9._-]+$/', $hostInput) &&
        !preg_match('/^[A-Fa-f0-9:]+$/', $hostInput)
    ) {
        return ['ok' => false, 'error' => 'آدرس سرور نامعتبر است.'];
    }

    if ($port < 0 || $port > 65535) {
        return ['ok' => false, 'error' => 'شماره پورت نامعتبر است.'];
    }

    $path = str_replace('\\', '/', $path);
    $absolute = ($path !== '' && $path[0] === '/');
    $segments = [];

    foreach (explode('/', $path) as $segment) {
        if ($segment === '') {
            continue;
        }

        if (
            $segment === '.' ||
            $segment === '..' ||
            !preg_match('/^[\p{L}\p{N}._ @+,=()-]+$/u', $segment)
        ) {
            return ['ok' => false, 'error' => 'مسیر مقصد نامعتبر است (کاراکتر غیرمجاز یا ..).'];
        }

        $segments[] = $segment;
    }

    $path = ($absolute ? '/' : '') . implode('/', $segments);

    if (strlen($path) > 500) {
        return ['ok' => false, 'error' => 'مسیر مقصد بیش از حد طولانی است.'];
    }

    $username = trim((string)(isset($input['username']) ? $input['username'] : ''));

    if (strlen($username) > 128 || preg_match('/[\x00-\x1f]/', $username)) {
        return ['ok' => false, 'error' => 'نام کاربری نامعتبر است.'];
    }

    $password = (string)(isset($input['password']) ? $input['password'] : '');
    $passwordProvided = $password !== '';

    if (strlen($password) > 256 || preg_match('/[\x00-\x1f]/', $password)) {
        return ['ok' => false, 'error' => 'رمز عبور نامعتبر است.'];
    }

    $domainInput = trim((string)(isset($input['public_domain']) ? $input['public_domain'] : ''));
    $publicScheme = (isset($input['public_scheme']) && $input['public_scheme'] === 'http') ? 'http' : 'https';

    if (preg_match('#^(https?)://#i', $domainInput, $schemeMatch)) {
        $publicScheme = strtolower($schemeMatch[1]);
    }

    $domainInput = preg_replace('#^[a-z][a-z0-9+.-]*://#i', '', $domainInput);
    $slashPosition = strpos($domainInput, '/');

    if ($slashPosition !== false) {
        $domainInput = substr($domainInput, 0, $slashPosition);
    }

    $domainInput = strtolower(trim($domainInput));

    if ($domainInput !== '' && !preg_match('/^[a-z0-9.-]+(:\d{1,5})?$/', $domainInput)) {
        return ['ok' => false, 'error' => 'دامنه نامعتبر است (فقط خود دامنه، مثل example.com).'];
    }

    $docroot = trim((string)(isset($input['docroot']) ? $input['docroot'] : ''));

    if ($docroot === '') {
        $docroot = 'public_html';
    }

    if (!preg_match('/^[A-Za-z0-9._-]{1,64}$/', $docroot)) {
        return ['ok' => false, 'error' => 'نام پوشه ریشه وب نامعتبر است.'];
    }

    $s['public_domain'] = $domainInput;
    $s['public_scheme'] = $publicScheme;
    $s['docroot'] = $docroot;
    $s['delete_local'] = true;

    $s['protocol'] = $protocol;
    $s['host'] = $hostInput;
    $s['port'] = $port;
    $s['remote_path'] = $path;
    $s['username'] = $username;
    $s['ssl_verify'] = (string)(isset($input['ssl_verify']) ? $input['ssl_verify'] : '1') === '1';

    if ($passwordProvided) {
        $s['password'] = $password;
        $s['has_password'] = true;
    }

    if ($s['mode'] === 'remote') {
        if ($s['host'] === '') {
            return ['ok' => false, 'error' => 'آدرس سرور (لینک FTP/SFTP) را وارد کنید.'];
        }

        if ($s['username'] === '') {
            return ['ok' => false, 'error' => 'نام کاربری را وارد کنید.'];
        }

        if ($s['password'] === '') {
            return ['ok' => false, 'error' => 'رمز عبور را وارد کنید.'];
        }
    }

    return ['ok' => true, 'settings' => $s, 'password_provided' => $passwordProvided];
}


function transferPort(array $s)
{
    $port = (int)$s['port'];

    if ($port > 0 && $port < 65536) {
        return $port;
    }

    return $s['protocol'] === 'sftp' ? 22 : 21;
}


function transferHostForUrl(array $s)
{
    return strpos($s['host'], ':') !== false ? '[' . $s['host'] . ']' : $s['host'];
}


function transferPathSegments(array $s)
{
    $segments = [];

    foreach (explode('/', str_replace('\\', '/', (string)$s['remote_path'])) as $segment) {
        if ($segment !== '') {
            $segments[] = $segment;
        }
    }

    return $segments;
}


function transferPathIsAbsolute(array $s)
{
    $path = ltrim((string)$s['remote_path']);

    return $path !== '' && ($path[0] === '/' || $path[0] === '\\');
}


function transferPlainPath(array $s)
{
    $path = implode('/', transferPathSegments($s));

    return transferPathIsAbsolute($s) ? '/' . $path : $path;
}


function remoteScheme(array $s)
{
    return $s['protocol'] === 'sftp' ? 'sftp' : 'ftp';
}


function remoteRootUrl(array $s)
{
    return remoteScheme($s) . '://' . transferHostForUrl($s) . ':' . transferPort($s) . '/';
}


function remoteBaseUrl(array $s)
{
    $encoded = implode('/', array_map('rawurlencode', transferPathSegments($s)));

    if (remoteScheme($s) === 'sftp') {
        $prefix = transferPathIsAbsolute($s) ? '/' : '/~/';
    } else {
        $prefix = transferPathIsAbsolute($s) ? '/%2F' : '/';
    }

    $url = remoteScheme($s) . '://' . transferHostForUrl($s) . ':' . transferPort($s) . $prefix . $encoded;

    return $encoded === '' ? $url : $url . '/';
}


function transferLooksLikeDomain($value)
{
    return (bool)preg_match('/^(?=.{4,253}$)([A-Za-z0-9-]+\.)+[A-Za-z]{2,}$/', (string)$value);
}


function transferDocrootName(array $s)
{
    return strtolower(($s['docroot'] !== '') ? $s['docroot'] : 'public_html');
}


function transferDetectDomain(array $s)
{
    $segments = transferPathSegments($s);
    $docroot = transferDocrootName($s);

    foreach ($segments as $position => $segment) {
        if (strtolower($segment) === $docroot) {
            for ($i = $position - 1; $i >= 0; $i--) {
                if (transferLooksLikeDomain($segments[$i])) {
                    return strtolower($segments[$i]);
                }
            }

            break;
        }
    }

    foreach ($segments as $segment) {
        if (transferLooksLikeDomain($segment)) {
            return strtolower($segment);
        }
    }

    $host = strtolower((string)$s['host']);

    if ($host !== '' && !filter_var($host, FILTER_VALIDATE_IP) && transferLooksLikeDomain($host)) {
        return preg_replace('/^(ftp|sftp|ssh|www|cpanel|server|host)\./', '', $host);
    }

    return '';
}


function remotePublicUrl(array $s, $name)
{
    $domain = trim((string)$s['public_domain']);

    if ($domain === '') {
        $domain = transferDetectDomain($s);
    }

    if ($domain === '') {
        return '';
    }

    $segments = transferPathSegments($s);
    $docroot = transferDocrootName($s);
    $rest = $segments;
    $found = false;

    foreach ($segments as $position => $segment) {
        if (strtolower($segment) === $docroot) {
            $rest = array_slice($segments, $position + 1);
            $found = true;
            break;
        }
    }

    if (!$found && transferPathIsAbsolute($s)) {
        $rest = [];
    }

    $path = implode('/', array_map('rawurlencode', $rest));
    $scheme = ($s['public_scheme'] === 'http') ? 'http' : 'https';

    return $scheme . '://' . $domain . '/' . ($path === '' ? '' : $path . '/') . rawurlencode($name);
}


function remoteDestinationLabel(array $s, $name)
{
    $path = transferPlainPath($s);

    return $s['host'] . ':' . ($path === '' ? '' : $path . '/') . $name;
}


function remoteCurlOptions(array $s)
{
    $options = [
        CURLOPT_USERNAME       => $s['username'],
        CURLOPT_PASSWORD       => $s['password'],
        CURLOPT_CONNECTTIMEOUT => 30,
        CURLOPT_USERAGENT      => 'Reliable-Large-File-Downloader/1.0',
        CURLOPT_TCP_KEEPALIVE  => 1,
        CURLOPT_TCP_KEEPIDLE   => 60,
        CURLOPT_TCP_KEEPINTVL  => 30
    ];

    if ($s['protocol'] === 'sftp') {
        $options[CURLOPT_PROTOCOLS] = CURLPROTO_SFTP;
    } else {
        $options[CURLOPT_PROTOCOLS] = CURLPROTO_FTP | CURLPROTO_FTPS;

        if ($s['protocol'] === 'ftps') {
            $options[defined('CURLOPT_USE_SSL') ? CURLOPT_USE_SSL : 119] = 3;
        }

        $options[CURLOPT_SSL_VERIFYPEER] = !empty($s['ssl_verify']);
        $options[CURLOPT_SSL_VERIFYHOST] = !empty($s['ssl_verify']) ? 2 : 0;
    }

    return $options;
}


function remoteSettingsComplete(array $s)
{
    return $s['host'] !== '' && $s['username'] !== '' && $s['password'] !== '';
}


function remoteTransferSupported(array $s)
{
    if (!function_exists('curl_init')) {
        return 'افزونه cURL روی این هاست فعال نیست.';
    }

    $info = curl_version();
    $protocols = isset($info['protocols']) ? $info['protocols'] : [];
    $needed = $s['protocol'] === 'sftp' ? 'sftp' : 'ftp';

    if (!in_array($needed, $protocols, true)) {
        $message = 'cURL این هاست از پروتکل ' . strtoupper($needed) . ' پشتیبانی نمی‌کند.';

        if ($needed === 'sftp') {
            $message .= ' از FTP/FTPS استفاده کنید یا از پشتیبانی هاست بخواهید libssh2 را فعال کند.';
        }

        return $message;
    }

    return '';
}


function describeRemoteError($errno, $message)
{
    $known = [
        1  => 'این پروتکل روی cURL این هاست پشتیبانی نمی‌شود.',
        6  => 'نام سرور پیدا نشد؛ آدرس را بررسی کنید.',
        7  => 'اتصال به سرور برقرار نشد؛ آدرس، پورت یا فایروال را بررسی کنید.',
        28 => 'زمان اتصال به سرور تمام شد.',
        67 => 'نام کاربری یا رمز عبور نادرست است.',
        35 => 'خطای TLS هنگام اتصال؛ گزینه بررسی گواهی SSL را خاموش کنید یا از SFTP استفاده کنید.',
        51 => 'گواهی SSL سرور تأیید نشد؛ گزینه بررسی گواهی SSL را خاموش کنید.',
        60 => 'گواهی SSL سرور تأیید نشد؛ گزینه بررسی گواهی SSL را خاموش کنید.'
    ];

    if (isset($known[$errno])) {
        return $known[$errno];
    }

    return 'خطای اتصال (' . (int)$errno . '): ' . $message;
}


function remoteTestConnection(array $s)
{
    if (!remoteSettingsComplete($s)) {
        return ['ok' => false, 'error' => 'آدرس سرور، نام کاربری و رمز عبور باید کامل باشند.'];
    }

    $unsupported = remoteTransferSupported($s);

    if ($unsupported !== '') {
        return ['ok' => false, 'error' => $unsupported];
    }

    $ch = curl_init(remoteBaseUrl($s));
    $options = remoteCurlOptions($s);
    $options[CURLOPT_DIRLISTONLY] = true;
    $options[CURLOPT_RETURNTRANSFER] = true;
    $options[CURLOPT_TIMEOUT] = 45;
    curl_setopt_array($ch, $options);

    $result = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($result !== false) {
        return ['ok' => true, 'warning' => ''];
    }

    if (in_array($errno, [9, 19, 78], true)) {
        return [
            'ok' => true,
            'warning' => 'ورود موفق بود اما پوشه مقصد خوانده نشد (وجود ندارد یا دسترسی خواندن ندارید). هنگام ارسال تلاش می‌شود ساخته شود.'
        ];
    }

    return ['ok' => false, 'error' => describeRemoteError($errno, $error)];
}


function remoteFileSize(array $s, $name)
{
    $ch = curl_init(remoteBaseUrl($s) . rawurlencode($name));
    $options = remoteCurlOptions($s);
    $options[CURLOPT_NOBODY] = true;
    $options[CURLOPT_RETURNTRANSFER] = true;
    $options[CURLOPT_TIMEOUT] = 60;
    curl_setopt_array($ch, $options);

    $result = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    $length = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    curl_close($ch);

    if ($result === false) {
        $missing = in_array($errno, [19, 78], true);

        return ['ok' => $missing, 'missing' => $missing, 'size' => 0, 'error' => $error];
    }

    if ($length < 0) {
        return ['ok' => false, 'missing' => false, 'size' => 0, 'error' => 'Remote size unknown.'];
    }

    return ['ok' => true, 'missing' => false, 'size' => (int)$length, 'error' => ''];
}


function remoteUploadChunk(array $s, $localFile, $remoteName, $offset, $total)
{
    $fp = @fopen($localFile, 'rb');

    if (!$fp) {
        return ['ok' => false, 'error' => 'Cannot open the local file.'];
    }

    if ($offset > 0 && fseek($fp, $offset) !== 0) {
        fclose($fp);

        return ['ok' => false, 'error' => 'Cannot seek in the local file.'];
    }

    $started = microtime(true);
    $lastWrite = 0;

    $ch = curl_init(remoteBaseUrl($s) . rawurlencode($remoteName));

    $options = remoteCurlOptions($s);
    $options[CURLOPT_UPLOAD] = true;
    $options[CURLOPT_INFILE] = $fp;
    $options[CURLOPT_INFILESIZE] = $total - $offset;
    $options[defined('CURLOPT_FTPAPPEND') ? CURLOPT_FTPAPPEND : 50] = ($offset > 0);
    $options[defined('CURLOPT_FTP_CREATE_MISSING_DIRS') ? CURLOPT_FTP_CREATE_MISSING_DIRS : 110] = 2;
    $options[CURLOPT_TIMEOUT] = 0;
    $options[CURLOPT_RETURNTRANSFER] = true;
    $options[CURLOPT_NOPROGRESS] = false;
    $options[CURLOPT_PROGRESSFUNCTION] = function (
        $handle,
        $downloadTotal,
        $downloadNow,
        $uploadTotal,
        $uploadNow
    ) use (
        $offset,
        $total,
        $started,
        &$lastWrite
    ) {
        $now = microtime(true);

        if (($now - $lastWrite) >= 1) {
            $current = $offset + $uploadNow;
            $elapsed = max(0.001, $now - $started);

            writeStatus([
                'status'     => 'uploading',
                'downloaded' => $current,
                'total'      => $total,
                'percent'    => $total > 0 ? min(100, ($current / $total) * 100) : 0,
                'speed'      => $uploadNow / $elapsed,
                'message'    => 'در حال ارسال به هاست مقصد...'
            ]);

            $lastWrite = $now;
        }

        return 0;
    };

    curl_setopt_array($ch, $options);

    $result = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    curl_close($ch);
    fclose($fp);

    if ($result === false) {
        return ['ok' => false, 'error' => describeRemoteError($errno, $error)];
    }

    return ['ok' => true, 'error' => ''];
}


function remoteRunQuote(array $s, array $commands)
{
    $ch = curl_init(remoteRootUrl($s));
    $options = remoteCurlOptions($s);
    $options[CURLOPT_NOBODY] = true;
    $options[CURLOPT_RETURNTRANSFER] = true;
    $options[CURLOPT_QUOTE] = $commands;
    $options[CURLOPT_TIMEOUT] = 120;
    curl_setopt_array($ch, $options);

    $result = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($result === false) {
        return ['ok' => false, 'error' => describeRemoteError($errno, $error)];
    }

    return ['ok' => true, 'error' => ''];
}


function remoteFinalize(array $s, $name, $replaceExisting)
{
    $part = $name . '.part';
    $path = transferPlainPath($s);
    $commands = [];

    if ($s['protocol'] === 'sftp') {
        $dir = $path === '' ? '' : rtrim($path, '/') . '/';

        if ($replaceExisting) {
            $commands[] = '*rm "' . $dir . $name . '"';
        }

        $commands[] = 'rename "' . $dir . $part . '" "' . $dir . $name . '"';
    } else {
        if ($path !== '') {
            $commands[] = 'CWD ' . $path;
        }

        if ($replaceExisting) {
            $commands[] = '*DELE ' . $name;
        }

        $commands[] = 'RNFR ' . $part;
        $commands[] = 'RNTO ' . $name;
    }

    return remoteRunQuote($s, $commands);
}


function remoteListContains(array $s, $name)
{
    $ch = curl_init(remoteBaseUrl($s));
    $options = remoteCurlOptions($s);
    $options[CURLOPT_DIRLISTONLY] = true;
    $options[CURLOPT_RETURNTRANSFER] = true;
    $options[CURLOPT_TIMEOUT] = 60;
    curl_setopt_array($ch, $options);

    $result = curl_exec($ch);
    curl_close($ch);

    if ($result === false) {
        return false;
    }

    foreach (preg_split('/\r\n|\r|\n/', (string)$result) as $line) {
        if (basename(trim($line)) === $name) {
            return true;
        }
    }

    return false;
}


function deliverToRemote(array $s, $localFile, $name, $total)
{
    global $retryDelay;

    $total = (int)$total;
    $destination = remoteDestinationLabel($s, $name);

    $fail = function ($message, $sent) use ($total) {
        failDownload($message, $sent, $total);

        return false;
    };

    $check = remoteTestConnection($s);

    if (!$check['ok']) {
        return $fail($check['error'], 0);
    }

    $existing = remoteFileSize($s, $name);

    if ($existing['ok'] && !$existing['missing'] && $existing['size'] === $total) {
        if (is_file($localFile)) {
            @unlink($localFile);
        }

        writeStatus([
            'status'      => 'complete',
            'mode'        => 'remote',
            'destination' => $destination,
            'public_url'  => remotePublicUrl($s, $name),
            'downloaded'  => $total,
            'total'       => $total,
            'percent'     => 100,
            'speed'       => 0,
            'message'     => 'فایل از قبل در مقصد کامل موجود است.'
        ]);

        return true;
    }

    $part = $name . '.part';
    $noProgress = 0;
    $lastOffset = -1;
    $lastError = '';

    while (true) {
        clearstatcache(true, $localFile);

        if (!is_file($localFile) || filesize($localFile) !== $total) {
            return $fail('فایل محلی تغییر کرده یا پیدا نشد؛ ارسال متوقف شد.', 0);
        }

        $remote = remoteFileSize($s, $part);
        $offset = ($remote['ok'] && $remote['size'] > 0 && $remote['size'] <= $total)
            ? $remote['size']
            : 0;

        if ($offset >= $total && $total > 0) {
            break;
        }

        if ($offset > $lastOffset) {
            $noProgress = 0;
        } else {
            $noProgress++;
        }

        $lastOffset = $offset;

        if ($noProgress > 30) {
            return $fail('ارسال به هاست مقصد ادامه پیدا نکرد. ' . $lastError, $offset);
        }

        writeStatus([
            'status'     => 'uploading',
            'downloaded' => $offset,
            'total'      => $total,
            'percent'    => $total > 0 ? min(100, ($offset / $total) * 100) : 0,
            'speed'      => 0,
            'message'    => $offset > 0
                ? 'ادامه ارسال به هاست مقصد...'
                : 'شروع ارسال به هاست مقصد...'
        ]);

        $result = remoteUploadChunk($s, $localFile, $part, $offset, $total);

        if ($result['ok']) {
            $verify = remoteFileSize($s, $part);

            if (!$verify['ok'] || $verify['size'] === $total) {
                break;
            }

            continue;
        }

        $lastError = $result['error'];

        writeStatus([
            'status'     => 'retrying',
            'downloaded' => $offset,
            'total'      => $total,
            'percent'    => $total > 0 ? min(100, ($offset / $total) * 100) : 0,
            'speed'      => 0,
            'message'    => 'ارسال قطع شد؛ تلاش مجدد... ' . $lastError
        ]);

        sleep($retryDelay);
    }

    $rename = remoteFinalize($s, $name, $existing['ok'] && !$existing['missing']);

    if (!$rename['ok']) {
        return $fail(
            'ارسال کامل شد اما تغییر نام در مقصد ناموفق بود؛ فایل با نام ' . $part .
            ' در مقصد موجود است. ' . $rename['error'],
            $total
        );
    }

    $final = remoteFileSize($s, $name);
    $verified = $final['ok'] && !$final['missing'] && $final['size'] === $total;

    if (!$verified && !$final['ok'] && remoteListContains($s, $name)) {
        $verified = true;
    }

    if (!$verified) {
        return $fail(
            'فایل در مقصد تأیید نشد (' . $destination . '). فایل محلی نگه داشته شد.',
            $total
        );
    }

    @unlink($localFile);

    writeStatus([
        'status'      => 'complete',
        'mode'        => 'remote',
        'destination' => $destination,
        'public_url'  => remotePublicUrl($s, $name),
        'downloaded'  => $total,
        'total'       => $total,
        'percent'     => 100,
        'speed'       => 0,
        'message'     => 'فایل در مقصد تأیید شد: ' . $destination
    ]);

    return true;
}


/* =========================================================
   NORMALIZE FILENAME
========================================================= */

function normalizeFilename($filename)
{
    $filename = trim($filename);

    $filename = basename($filename);

    /*
     * کاراکترهای نامناسب برای filename
     */
    $filename = preg_replace(
        '/[^\p{L}\p{N}._ -]/u',
        '_',
        $filename
    );

    $filename = preg_replace('/\s+/u', ' ', $filename);
    $filename = trim($filename, " .");

    /*
     * جلوگیری از نام خالی
     */
    if ($filename === '' || $filename === '.' || $filename === '..') {
        return false;
    }

    return $filename;
}


function prepareUploadFilename($requested, $original)
{
    $requested = trim((string)$requested);
    $original = normalizeFilename($original);
    $requested = normalizeFilename($requested);

    if ($requested === false) {
        $requested = $original;
    }

    if ($requested === false) {
        return false;
    }

    $requestedExtension = pathinfo($requested, PATHINFO_EXTENSION);
    $originalExtension = pathinfo($original, PATHINFO_EXTENSION);

    if ($requestedExtension === '' && $originalExtension !== '') {
        $requested .= '.' . $originalExtension;
    }

    return $requested;
}


function convertUploadedImage($source, $target, $targetExtension)
{
    if (!function_exists('finfo_open')) {
        return false;
    }

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $source);
    finfo_close($finfo);

    $loaders = [
        'image/jpeg' => 'imagecreatefromjpeg',
        'image/png'  => 'imagecreatefrompng',
        'image/gif'  => 'imagecreatefromgif',
        'image/webp' => 'imagecreatefromwebp'
    ];

    if (!isset($loaders[$mime]) || !function_exists($loaders[$mime])) {
        return false;
    }

    $image = @$loaders[$mime]($source);
    if (!$image) {
        return false;
    }

    $targetExtension = strtolower($targetExtension);
    $success = false;

    if (in_array($targetExtension, ['jpg', 'jpeg'], true)) {
        $success = function_exists('imagejpeg') && imagejpeg($image, $target, 90);
    } elseif ($targetExtension === 'png') {
        $success = function_exists('imagepng') && imagepng($image, $target, 6);
    } elseif ($targetExtension === 'gif') {
        $success = function_exists('imagegif') && imagegif($image, $target);
    } elseif ($targetExtension === 'webp') {
        $success = function_exists('imagewebp') && imagewebp($image, $target, 90);
    }

    imagedestroy($image);
    return $success;
}


function uploadFilenameIsAllowed($filename)
{
    $lowerFilename = strtolower($filename);
    $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $blocked = [
        'php', 'phtml', 'php3', 'php4', 'php5', 'php7', 'php8',
        'phar', 'cgi', 'pl', 'py', 'asp', 'aspx', 'jsp', 'sh', 'htaccess'
    ];

    $blockedNames = [
        '.user.ini', 'web.config', 'php.ini', '.env'
    ];

    return !in_array($lowerFilename, $blockedNames, true) &&
        ($extension === '' || !in_array($extension, $blocked, true));
}


/* =========================================================
   CHUNKED UPLOAD
========================================================= */

function uploadJson($data, $statusCode = 200)
{
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store');

    echo json_encode(
        $data,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );

    exit;
}


function uploadIdIsValid($uploadId)
{
    return is_string($uploadId) &&
        preg_match('/^[a-f0-9]{32}$/', $uploadId);
}


function uploadMetaPath($uploadId)
{
    global $uploadPrefix;

    return $uploadPrefix . $uploadId . '.json';
}


function uploadPartPath($uploadId)
{
    global $uploadPrefix;

    return $uploadPrefix . $uploadId . '.part';
}


if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['upload_action'])
) {
    requirePostCsrf();
    $action = $_POST['upload_action'];

    if ($action === 'init') {
        $originalFilename = isset($_POST['original_filename'])
            ? $_POST['original_filename']
            : '';
        $filename = prepareUploadFilename(
            isset($_POST['filename']) ? $_POST['filename'] : '',
            $originalFilename
        );
        $totalSize = isset($_POST['size'])
            ? (int)$_POST['size']
            : 0;

        if (
            $filename === false ||
            !uploadFilenameIsAllowed($filename) ||
            $totalSize < 0
        ) {
            uploadJson([
                'ok' => false,
                'error' => 'Invalid file name, file type, or size.'
            ], 400);
        }

        foreach (glob(__DIR__ . '/.upload-*') ?: [] as $staleUpload) {
            if (is_file($staleUpload) && filemtime($staleUpload) < time() - 172800) {
                @unlink($staleUpload);
            }
        }

        $uploadId = bin2hex(random_bytes(16));
        $meta = [
            'filename' => $filename,
            'original_filename' => normalizeFilename($originalFilename),
            'size' => $totalSize,
            'total_chunks' => 0,
            'next_chunk' => 0,
            'created' => time()
        ];

        if (
            file_put_contents(
                uploadMetaPath($uploadId),
                json_encode($meta, JSON_UNESCAPED_UNICODE),
                LOCK_EX
            ) === false
        ) {
            uploadJson([
                'ok' => false,
                'error' => 'Cannot create upload session.'
            ], 500);
        }

        uploadJson([
            'ok' => true,
            'upload_id' => $uploadId,
            'uploaded' => 0
        ]);
    }

    if ($action === 'chunk') {
        $uploadId = isset($_POST['upload_id'])
            ? $_POST['upload_id']
            : '';
        $chunkIndex = isset($_POST['chunk_index'])
            ? (int)$_POST['chunk_index']
            : -1;
        $totalChunks = isset($_POST['total_chunks'])
            ? (int)$_POST['total_chunks']
            : 0;
        $metaPath = uploadMetaPath($uploadId);
        $partPath = uploadPartPath($uploadId);

        if (
            !uploadIdIsValid($uploadId) ||
            !file_exists($metaPath) ||
            !isset($_FILES['chunk']) ||
            $_FILES['chunk']['error'] !== UPLOAD_ERR_OK ||
            $chunkIndex < 0 ||
            $totalChunks < 1 ||
            $chunkIndex >= $totalChunks
        ) {
            uploadJson([
                'ok' => false,
                'error' => 'Invalid upload chunk.'
            ], 400);
        }

        $meta = json_decode(@file_get_contents($metaPath), true);
        if (!is_array($meta)) {
            uploadJson([
                'ok' => false,
                'error' => 'Upload session not found.'
            ], 404);
        }

        $storedTotalChunks = (int)($meta['total_chunks'] ?? 0);
        $nextChunk = (int)($meta['next_chunk'] ?? 0);

        if ($storedTotalChunks === 0) {
            $meta['total_chunks'] = $totalChunks;
            $storedTotalChunks = $totalChunks;
        }

        if ($storedTotalChunks !== $totalChunks) {
            uploadJson([
                'ok' => false,
                'error' => 'تعداد بخش‌های آپلود تغییر کرده است.'
            ], 400);
        }

        if ($chunkIndex < $nextChunk) {
            uploadJson([
                'ok' => true,
                'uploaded' => file_exists($partPath) ? filesize($partPath) : 0,
                'duplicate' => true
            ]);
        }

        if ($chunkIndex !== $nextChunk) {
            uploadJson([
                'ok' => false,
                'error' => 'ترتیب بخش‌های آپلود صحیح نیست.'
            ], 409);
        }

        $chunk = $_FILES['chunk']['tmp_name'];
        $input = @fopen($chunk, 'rb');
        $output = @fopen($partPath, 'ab');

        if (!$input || !$output) {
            if ($input) {
                fclose($input);
            }
            if ($output) {
                fclose($output);
            }
            uploadJson([
                'ok' => false,
                'error' => 'Cannot write upload data.'
            ], 500);
        }

        stream_copy_to_stream($input, $output);
        fclose($input);
        fclose($output);

        $meta['next_chunk'] = $nextChunk + 1;
        file_put_contents(
            $metaPath,
            json_encode($meta, JSON_UNESCAPED_UNICODE),
            LOCK_EX
        );

        uploadJson([
            'ok' => true,
            'uploaded' => filesize($partPath)
        ]);
    }

    if ($action === 'finish') {
        $uploadId = isset($_POST['upload_id'])
            ? $_POST['upload_id']
            : '';
        $metaPath = uploadMetaPath($uploadId);
        $partPath = uploadPartPath($uploadId);

        if (
            !uploadIdIsValid($uploadId) ||
            !file_exists($metaPath) ||
            !file_exists($partPath)
        ) {
            uploadJson([
                'ok' => false,
                'error' => 'Upload session is incomplete.'
            ], 400);
        }

        $meta = json_decode(@file_get_contents($metaPath), true);
        $partSize = filesize($partPath);

        if (
            !is_array($meta) ||
            (int)($meta['next_chunk'] ?? 0) !==
                (int)($meta['total_chunks'] ?? 0) ||
            (int)$meta['size'] !== (int)$partSize
        ) {
            uploadJson([
                'ok' => false,
                'error' => 'Uploaded size does not match the original file.'
            ], 400);
        }

        $filename = normalizeFilename($meta['filename']);
        $target = __DIR__ . '/' . $filename;

        $originalExtension = strtolower(
            pathinfo($meta['original_filename'] ?? '', PATHINFO_EXTENSION)
        );
        $targetExtension = strtolower(
            pathinfo($filename, PATHINFO_EXTENSION)
        );
        $conversionNeeded =
            $originalExtension !== '' &&
            $targetExtension !== '' &&
            $originalExtension !== $targetExtension;

        if ($conversionNeeded) {
            $convertedPath = $partPath . '.converted';
            $converted = convertUploadedImage(
                $partPath,
                $convertedPath,
                $targetExtension
            );

            if (!$converted) {
                @unlink($convertedPath);
                uploadJson([
                    'ok' => false,
                    'error' => 'این تغییر پسوند بدون تبدیل واقعی فایل ممکن نیست.'
                ], 400);
            }

            @unlink($partPath);
            $partPath = $convertedPath;
            $partSize = filesize($partPath);
        }

        if (file_exists($target)) {
            $info = pathinfo($filename);
            $suffix = '_' . date('Ymd_His');
            $filename = $info['filename'] . $suffix .
                (isset($info['extension']) ? '.' . $info['extension'] : '');
            $target = __DIR__ . '/' . $filename;
        }

        if (!@rename($partPath, $target)) {
            uploadJson([
                'ok' => false,
                'error' => 'Cannot move uploaded file to its final name.'
            ], 500);
        }

        @unlink($metaPath);

        /*
         * اگر مقصد FTP/SFTP تنظیم شده، فایل آپلودشده به آن‌جا منتقل می‌شود
         */

        $uploadSettings = loadTransferSettings(currentUser());

        if ($uploadSettings['mode'] === 'remote') {
            global $statusQuiet, $lastDeliverError;
            $statusQuiet = true;
            $lastDeliverError = '';
            $delivered = deliverToRemote($uploadSettings, $target, $filename, $partSize);
            $statusQuiet = false;

            if (!$delivered) {
                uploadJson([
                    'ok' => false,
                    'error' => 'ارسال به هاست مقصد ناموفق بود: ' . $lastDeliverError .
                        ' (فایل روی همین هاست باقی ماند: ' . $filename . ')'
                ], 502);
            }

            uploadJson([
                'ok' => true,
                'filename' => $filename,
                'destination' => remoteDestinationLabel($uploadSettings, $filename),
                'url' => remotePublicUrl($uploadSettings, $filename),
                'size' => $partSize
            ]);
        }

        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            ? 'https'
            : 'http';
        $basePath = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
        $url = $scheme . '://' . $_SERVER['HTTP_HOST'] .
            ($basePath === '.' ? '' : $basePath) . '/' . rawurlencode($filename);

        uploadJson([
            'ok' => true,
            'filename' => $filename,
            'url' => $url,
            'size' => $partSize
        ]);
    }

    uploadJson([
        'ok' => false,
        'error' => 'Unknown upload action.'
    ], 400);
}


/* =========================================================
   RANGE PROBE
========================================================= */

function probeRemoteFile($url)
{
    $contentRange = '';

    if (!hostIsPublic(parse_url($url, PHP_URL_HOST))) {
        return [
            'ok' => false,
            'error' => 'Download address points to a private or reserved network and is blocked.'
        ];
    }

    $ch = curl_init($url);

    curl_setopt_array($ch, [

        CURLOPT_RETURNTRANSFER => true,

        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
        CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,

        /*
         * فقط یک بایت درخواست می‌کنیم.
         */
        CURLOPT_RANGE => '0-0',

        CURLOPT_HTTP_VERSION =>
            CURL_HTTP_VERSION_1_1,

        CURLOPT_CONNECTTIMEOUT => 30,

        CURLOPT_TIMEOUT => 60,

        CURLOPT_USERAGENT =>
            'Reliable-Large-File-Downloader/1.0',

        CURLOPT_HEADERFUNCTION =>
            function ($ch, $header)
            use (&$contentRange)
            {
                $line = trim($header);

                if (
                    stripos(
                        $line,
                        'Content-Range:'
                    ) === 0
                ) {
                    $contentRange = trim(
                        substr(
                            $line,
                            strlen('Content-Range:')
                        )
                    );
                }

                return strlen($header);
            }
    ]);

    $body = curl_exec($ch);

    $error = curl_error($ch);

    $httpCode = curl_getinfo(
        $ch,
        CURLINFO_HTTP_CODE
    );

    curl_close($ch);


    if ($body === false) {

        return [
            'ok' => false,
            'error' =>
                $error ?: 'Connection failed.'
        ];
    }


    /*
     * برای Range باید 206 بگیریم.
     */
    if ($httpCode != 206) {

        return [
            'ok' => false,
            'error' =>
                'Remote server does not support HTTP Range. '
                . 'HTTP response: '
                . $httpCode
        ];
    }


    /*
     * مثال:
     *
     * bytes 0-0/21474836480
     */

    $total = 0;

    if (
        preg_match(
            '#/(\d+)$#',
            $contentRange,
            $m
        )
    ) {
        $total = (int)$m[1];
    }


    if ($total <= 0) {

        return [
            'ok' => false,
            'error' =>
                'Cannot determine remote file size.'
        ];
    }


    return [
        'ok'    => true,
        'total' => $total
    ];
}


/* =========================================================
   FORM SUBMISSION
========================================================= */

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['start_job'])
) {
    requirePostCsrf();

    $inputUrl =
        isset($_POST['download_url'])
        ? trim($_POST['download_url'])
        : '';

    $inputName =
        isset($_POST['filename'])
        ? trim($_POST['filename'])
        : '';


    /*
     * Validate URL
     */

    if (
        $inputUrl === '' ||
        !filter_var(
            $inputUrl,
            FILTER_VALIDATE_URL
        )
    ) {
        die('Invalid download URL.');
    }


    /*
     * فقط HTTP / HTTPS
     */

    $scheme = strtolower(
        parse_url(
            $inputUrl,
            PHP_URL_SCHEME
        )
    );

    if (
        $scheme !== 'http' &&
        $scheme !== 'https'
    ) {
        die('Only HTTP and HTTPS URLs are allowed.');
    }


    /*
     * Normalize filename
     */

    $inputName =
        normalizeFilename($inputName);


    if ($inputName === false) {
        die('Invalid filename.');
    }


    /*
     * فایل‌های اجرایی (php و مشابه) مثل آپلود مسدود هستند
     */

    if (!uploadFilenameIsAllowed($inputName)) {
        die('This file type is not allowed.');
    }


    /*
     * جلوگیری از دانلود از شبکه داخلی (SSRF)
     */

    if (!hostIsPublic(parse_url($inputUrl, PHP_URL_HOST))) {
        die('The download address points to a private or reserved network.');
    }


    /*
     * اگر نام قبلی فایل متفاوت بود،
     * تنظیمات جدید را ذخیره می‌کنیم.
     */

    saveConfig(
        $inputUrl,
        $inputName
    );


    /*
     * وضعیت جدید
     */

    writeStatus([
        'status'     => 'idle',
        'downloaded' => 0,
        'total'      => 0,
        'percent'    => 0,
        'speed'      => 0,
        'message'    => 'Ready'
    ]);


    /*
     * Redirect
     *
     * باعث می‌شود refresh دوباره POST نکند.
     */

    header(
        'Location: ' .
        strtok(
            $_SERVER['REQUEST_URI'],
            '?'
        )
    );

    exit;
}


/* =========================================================
   USER AND LIBRARY ACTIONS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['library_action'])) {
    requirePostCsrf();
    $action = (string)$_POST['library_action'];

    if ($action === 'list') {
        $statement = $database->prepare(
            'SELECT id, name, url, type FROM library WHERE user_id = ? ORDER BY id DESC'
        );
        $statement->execute([currentUser()]);
        uploadJson(['ok' => true, 'items' => $statement->fetchAll(PDO::FETCH_ASSOC)]);
    }

    if ($action === 'save') {
        $name = normalizeFilename((string)($_POST['name'] ?? ''));
        $url = trim((string)($_POST['url'] ?? ''));
        $type = trim((string)($_POST['type'] ?? 'file'));
        if ($name === false || !filter_var($url, FILTER_VALIDATE_URL)) {
            uploadJson(['ok' => false, 'error' => 'Invalid library item.'], 400);
        }
        $statement = $database->prepare(
            'INSERT INTO library (user_id, name, url, type, created_at) VALUES (?, ?, ?, ?, ?) ' .
            'ON CONFLICT(user_id, url) DO UPDATE SET name = excluded.name, type = excluded.type'
        );
        $statement->execute([currentUser(), $name, $url, $type ?: 'file', time()]);
        uploadJson(['ok' => true]);
    }

    if ($action === 'remove') {
        $statement = $database->prepare('DELETE FROM library WHERE id = ? AND user_id = ?');
        $statement->execute([(int)($_POST['id'] ?? 0), currentUser()]);
        uploadJson(['ok' => true]);
    }

    uploadJson(['ok' => false, 'error' => 'Unknown library action.'], 400);
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_action'])) {
    requirePostCsrf();
    $action = (string)$_POST['user_action'];
    $username = trim((string)($_POST['username'] ?? ''));
    $password = (string)($_POST['password'] ?? '');

    if ($action === 'add') {
        if (!preg_match('/^[A-Za-z0-9_.-]{3,64}$/', $username) || strlen($password) < 8) {
            $userError = 'نام کاربری معتبر و رمز حداقل ۸ کاراکتری وارد کنید.';
        } else {
            try {
                $statement = $database->prepare(
                    'INSERT INTO users (username, password_hash, created_at) VALUES (?, ?, ?)'
                );
                $statement->execute([$username, password_hash($password, PASSWORD_DEFAULT), time()]);
                $userMessage = 'کاربر اضافه شد.';
            } catch (PDOException $exception) {
                $userError = 'این نام کاربری قبلاً ثبت شده است.';
            }
        }
    } elseif ($action === 'change_username') {
        if (!preg_match('/^[A-Za-z0-9_.-]{3,64}$/', $username)) {
            $userError = 'نام کاربری معتبر وارد کنید.';
        } else {
            try {
                $statement = $database->prepare('UPDATE users SET username = ? WHERE id = ?');
                $statement->execute([$username, currentUser()]);
                $_SESSION['username'] = $username;
                $userMessage = 'نام کاربری تغییر کرد.';
            } catch (PDOException $exception) {
                $userError = 'این نام کاربری قبلاً ثبت شده است.';
            }
        }
    } elseif ($action === 'change_password') {
        $statement = $database->prepare('SELECT password_hash FROM users WHERE id = ?');
        $statement->execute([currentUser()]);
        $currentHash = (string)$statement->fetchColumn();

        if (!password_verify((string)(isset($_POST['current_password']) ? $_POST['current_password'] : ''), $currentHash)) {
            $userError = 'رمز فعلی نادرست است.';
        } elseif (strlen($password) < 8) {
            $userError = 'رمز جدید باید حداقل ۸ کاراکتر باشد.';
        } else {
            $statement = $database->prepare('UPDATE users SET password_hash = ? WHERE id = ?');
            $statement->execute([password_hash($password, PASSWORD_DEFAULT), currentUser()]);
            $_SESSION['must_change_password'] = false;
            @unlink(initialPasswordFile());
            $userMessage = 'رمز عبور تغییر کرد.';
        }
    }
}


/* =========================================================
   DESTINATION SETTINGS API
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['settings_action'])) {
    requirePostCsrf();
    $settingsAction = (string)$_POST['settings_action'];
    $savedSettings = loadTransferSettings(currentUser());

    if ($settingsAction === 'get') {
        $publicSettings = $savedSettings;
        unset($publicSettings['password']);
        $publicSettings['crypto_available'] = transferCryptoAvailable();
        $publicSettings['detected_domain'] = transferDetectDomain($savedSettings);
        $publicSettings['public_url_example'] = remotePublicUrl($savedSettings, 'example.zip');
        $publicSettings['sftp_available'] = remoteTransferSupported(['protocol' => 'sftp']) === '';
        uploadJson(['ok' => true, 'settings' => $publicSettings]);
    }

    if ($settingsAction === 'save' || $settingsAction === 'test') {
        $parsedSettings = parseTransferInput($_POST, $savedSettings);

        if (!$parsedSettings['ok']) {
            uploadJson(['ok' => false, 'error' => $parsedSettings['error']], 400);
        }

        $newSettings = $parsedSettings['settings'];

        if ($settingsAction === 'test') {
            $check = remoteTestConnection($newSettings);

            if (!$check['ok']) {
                uploadJson(['ok' => false, 'error' => $check['error']]);
            }

            uploadJson([
                'ok' => true,
                'warning' => $check['warning'],
                'detected_domain' => transferDetectDomain($newSettings),
                'public_url_example' => remotePublicUrl($newSettings, 'example.zip')
            ]);
        }

        $encryptedPassword = null;

        if ($parsedSettings['password_provided']) {
            $encryptedPassword = encryptTransferSecret($newSettings['password']);

            if ($encryptedPassword === false) {
                uploadJson([
                    'ok' => false,
                    'error' => 'ذخیره امن رمز ممکن نیست (افزونه openssl یا نوشتن فایل کلید در این پوشه در دسترس نیست).'
                ], 500);
            }
        }

        saveTransferSettings(currentUser(), $newSettings, $encryptedPassword);
        uploadJson(['ok' => true]);
    }

    uploadJson(['ok' => false, 'error' => 'Unknown settings action.'], 400);
}


/* =========================================================
   LOAD CONFIG
========================================================= */

$config = readConfig();


/* =========================================================
   CONFIG NOT SET => SHOW INPUT
========================================================= */

if ($config === null) {

?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport"
      content="width=device-width, initial-scale=1.0">

<title>جادوگر انتقال فایل</title>

<style>

* {
    box-sizing: border-box;
}

body {

    margin: 0;

    min-height: 100vh;

    display: flex;

    justify-content: center;

    align-items: center;

    background:
        radial-gradient(
            circle at top,
            #18243d 0%,
            #080c15 70%
        );

    font-family:
        Arial,
        Helvetica,
        sans-serif;

    color: white;

    direction: rtl;
}


.app-shell {
    padding-block: 30px;
    
    width: min(1180px, 96%);


    display: grid;

    grid-template-columns: 230px minmax(0, 1fr);

    gap: 18px;
}


.sidebar {

    padding: 22px 14px;

    border: 1px solid rgba(255,255,255,.07);

    border-radius: 22px;

    background: rgba(18, 25, 40, .96);
    
    height: fit-content;
}


.brand {

    display: flex;

    align-items: center;

    gap: 10px;

    padding: 8px 10px 24px;

    font-weight: bold;

    font-size: 17px;
}


.brand-mark {

    width: 38px;
    height: 38px;

    display: grid;

    place-items: center;

    border-radius: 12px;

    background: #315efb;

    font-size: 20px;
}


.nav-title {

    padding: 16px 10px 8px;

    color: #68758b;

    font-size: 10px;
}


.nav-link {

    display: flex;

    align-items: center;

    gap: 10px;

    padding: 12px 11px;

    border-radius: 10px;

    color: #9ba7bb;

    font-size: 13px;

    text-decoration: none;
}


.nav-link:hover,
.nav-link.active {

    background: #1b2c4d;

    color: white;
}


.workspace {
    min-width: 0;
}


.setup-section {
    display: none;
}


.setup-section.active {
    display: block;
}


.workspace .card {
    width: 100%;
}


.setup-language {
    margin-top: 24px;
    padding: 10px;
    border-top: 1px solid #202b40;
}


.setup-language select {
    width: 100%;
    padding: 9px;
    border: 1px solid #2b3850;
    border-radius: 9px;
    background: #0c1320;
    color: white;
}


.setup-library-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
    gap: 12px;
}


.setup-library-card {
    padding: 14px;
    border: 1px solid #202b40;
    border-radius: 13px;
    background: #0c1320;
}


.setup-library-card strong,
.setup-library-card small {
    display: block;
    overflow: hidden;
    margin-bottom: 8px;
    text-overflow: ellipsis;
    white-space: nowrap;
}


.setup-library-card small {
    color: #8490a7;
}


.setup-library-card input {
    margin-bottom: 8px;
    padding: 9px;
    font-size: 10px;
}


.setup-library-card button {
    padding: 9px;
    font-size: 11px;
}

.card {

    width: min(700px, 94%);

    background:
        rgba(18, 25, 40, .96);

    border:
        1px solid
        rgba(255,255,255,.07);

    border-radius: 25px;

    padding: 32px;

    box-shadow:
        0 30px 90px
        rgba(0,0,0,.45);
}

.logo {

    width: 68px;
    height: 68px;

    margin: 0 auto 16px;

    border-radius: 20px;

    display: flex;

    justify-content: center;
    align-items: center;

    font-size: 32px;

    background: #1b2c4d;
}

.title {
    text-align: center;
}

.title h1 {
    margin: 0;
    font-size: 26px;
}

.title p {

    margin: 8px 0 28px;

    color: #8490a7;

    font-size: 13px;
}

label {

    display: block;

    margin-bottom: 7px;

    color: #98a4b8;

    font-size: 13px;
}

input {

    width: 100%;

    padding: 14px;

    margin-bottom: 18px;

    border:
        1px solid
        #2b3850;

    border-radius: 11px;

    background: #0c1320;

    color: white;

    outline: none;

    font-size: 14px;
}

input:focus {

    border-color: #315efb;
}

button {

    width: 100%;

    padding: 15px;

    border: 0;

    border-radius: 12px;

    background: #315efb;

    color: white;

    font-size: 15px;

    font-weight: bold;

    cursor: pointer;
}

button:hover {

    background: #416dfc;
}

.example {

    margin-top: 18px;

    padding: 13px;

    border-radius: 11px;

    background: #0d1422;

    color: #6f7d94;

    font-size: 11px;

    line-height: 1.7;
}


.upload-box {

    margin-top: 24px;

    padding-top: 22px;

    border-top: 1px solid #202b40;
}


.upload-box h2 {

    margin: 0 0 7px;

    font-size: 18px;
}


.upload-box p {

    margin: 0 0 14px;

    color: #8490a7;

    font-size: 12px;
}


.upload-box input {

    width: 100%;

    margin-bottom: 12px;

    padding: 12px;

    border: 1px solid #2b3850;

    border-radius: 10px;

    background: #0c1320;

    color: white;
}


.upload-box button {

    width: 100%;

    padding: 14px;

    border: 0;

    border-radius: 11px;

    background: #1c9b68;

    color: white;

    font-weight: bold;

    cursor: pointer;
}


.upload-box button:disabled {
    opacity: .5;
}


.upload-status,
.upload-link {

    display: none;

    margin-top: 12px;

    color: #9ba7bb;

    font-size: 12px;
}


.upload-link input {
    margin: 0;
}


.setup-preview {
    display: none;
    margin: 4px 0 12px;
    overflow: hidden;
    border: 1px solid #202b40;
    border-radius: 10px;
    background: #0c1320;
}


.setup-preview img,
.setup-preview video {
    display: none;
    width: 100%;
    max-height: 210px;
    object-fit: contain;
    background: #080c15;
}


.setup-preview audio {
    display: none;
    width: 100%;
}


.setup-preview-text {
    padding: 20px;
    color: #9ba7bb;
    text-align: center;
    font-size: 12px;
}


.setup-progress {
    display: none;
    margin-top: 14px;
}


.setup-progress-head {
    display: flex;
    justify-content: space-between;
    margin-bottom: 7px;
    color: #9ba7bb;
    font-size: 12px;
}


.setup-progress-track {
    height: 12px;
    overflow: hidden;
    border: 1px solid #202a3c;
    border-radius: 20px;
    background: #0a101a;
}


.setup-progress-fill {
    width: 0;
    height: 100%;
    border-radius: 20px;
    background: linear-gradient(90deg, #1c9b68, #62d69e);
    transition: width .25s ease;
}


/* Initial setup visual polish */
body {
    background:
        radial-gradient(circle at 12% 8%, rgba(49,94,251,.18), transparent 30%),
        radial-gradient(circle at 88% 90%, rgba(28,155,104,.12), transparent 28%),
        #080c15;
    font-family: "Segoe UI", Tahoma, sans-serif;
}


.app-shell {
    align-items: stretch;
    gap: 22px;
}


.sidebar,
.workspace .card {
    border-color: rgba(132,164,230,.14);
    box-shadow: 0 24px 70px rgba(0,0,0,.28);
}


.sidebar {
    background: linear-gradient(165deg, rgba(24,36,61,.98), rgba(14,20,33,.98));
}


.brand-mark {
    box-shadow: 0 10px 24px rgba(49,94,251,.3);
}


.nav-link {
    transition: background .2s ease, color .2s ease, transform .2s ease;
}


.nav-link:hover {
    transform: translateX(-3px);
}


.workspace .card {
    background: linear-gradient(145deg, rgba(24,34,53,.98), rgba(14,20,33,.98));
}


button {
    box-shadow: 0 9px 20px rgba(49,94,251,.2);
    transition: transform .2s ease, filter .2s ease, box-shadow .2s ease;
}


button:hover:not(:disabled) {
    transform: translateY(-2px);
    filter: brightness(1.08);
    box-shadow: 0 12px 25px rgba(49,94,251,.28);
}


input:hover,
select:hover {
    border-color: #40567e;
}


input:focus,
select:focus {
    border-color: #5d82ff;
    box-shadow: 0 0 0 3px rgba(49,94,251,.14);
}


input[type="file"] {
    padding: 11px;
    border-style: dashed;
    background: rgba(8,12,21,.7);
}

.settings-panel label{display:block;margin:14px 0 6px;color:#aab5c8;font-size:13px}
.settings-panel input[type="text"],.settings-panel input[type="password"],.settings-panel input[type="number"],.settings-panel select{width:100%;padding:12px;box-sizing:border-box;border:1px solid #30415f;border-radius:9px;background:#0c1320;color:#fff}
.settings-panel .settings-choice label,.settings-panel .settings-check{display:flex;align-items:center;gap:10px;color:#e6ecf7;cursor:pointer}
.settings-panel input[type="radio"],.settings-panel input[type="checkbox"]{width:auto;margin:0}
.settings-panel small{display:block;margin-top:6px;color:#7f8ca3;font-size:12px;line-height:1.8}
.settings-panel .settings-help{color:#9ba7bb;line-height:1.9}
.settings-remote{display:none}
.settings-remote.active{display:block}
.settings-actions{display:flex;gap:10px;margin-top:22px;flex-wrap:wrap}
.settings-actions button{flex:1;min-width:140px}
.settings-panel .status.error{color:#ff9b9b}.settings-panel .status.success{color:#7ee2a8}
@media(max-width:640px){.settings-actions button{min-width:100%}}
.settings-card{margin-top:18px;padding:18px;border:1px solid #263652;border-radius:14px;background:#0e1626}
.settings-card h3{margin:0 0 6px;font-size:16px;color:#e6ecf7}
.settings-card form{margin-top:14px;padding-top:14px;border-top:1px solid #1d2a42}
.settings-card form button{margin-top:12px}
.settings-panel .status.error,.settings-panel .status.success{margin-top:14px}
</style>

</head>

<body>

<div class="app-shell">

    <aside class="sidebar">
        <div class="brand"><span class="brand-mark">↕</span><span data-setup-i18n="brand">انتقال فایل</span></div>
        <div class="nav-title" data-setup-i18n="manage">مدیریت فایل</div>
        <a class="nav-link active" data-setup-target="setup-upload" href="#setup-upload" data-setup-i18n="uploadNav">آپلود از سیستم</a>
        <a class="nav-link" data-setup-target="setup-download" href="#setup-download" data-setup-i18n="downloadNav">دانلود از لینک</a>
        <a class="nav-link" data-setup-target="setup-library" href="#setup-library" data-setup-i18n="libraryNav">کتابخانه فایل‌ها</a>
        <a class="nav-link" data-setup-target="setup-settings" href="#setup-settings">تنظیمات مقصد</a>
        <div class="setup-language">
            <label for="setupLanguage" data-setup-i18n="language">زبان پنل</label>
            <select id="setupLanguage">
                <option value="auto">تشخیص خودکار</option>
                <option value="fa">فارسی</option>
                <option value="en">English</option>
            </select>
        </div>
    </aside>

    <main class="workspace">

<div class="card">

    <div class="logo">
        ↓
    </div>

    <div class="title">

        <h1>
            <span data-setup-i18n="title">جادوگر انتقال فایل</span>
        </h1>

        <p>
            <span data-setup-i18n="subtitle">مدیریت آپلود و دانلود فایل‌ها</span>
        </p>

    </div>


    <section id="setup-download" class="setup-section">

    <form method="post">

        <input type="hidden" name="csrf" value="<?php echo htmlspecialchars($_SESSION['csrf'], ENT_QUOTES, 'UTF-8'); ?>">

        <input
            type="hidden"
            name="start_job"
            value="1"
        >


        <label data-setup-i18n="downloadUrl">
            لینک دانلود
        </label>

        <input
            type="url"
            name="download_url"
            placeholder="https://example.com/file.tar.gz"
            required
        >


        <label data-setup-i18n="fileName">
            نام فایل
        </label>

        <input
            type="text"
            name="filename"
            placeholder="cpmove-schema.tar.gz"
            required
        >


        <button type="submit">
            <span data-setup-i18n="registerDownload">ثبت دانلود</span>
        </button>

    </form>


    <div class="example">

        <span data-setup-i18n="exampleUrl">نمونه لینک:</span><br>
        https://example.com/cpmove-schema.tar.gz

        <br><br>

        <span data-setup-i18n="exampleName">نمونه نام فایل:</span><br>
        cpmove-schema.tar.gz

    </div>

    </section>


    <section id="setup-upload" class="setup-section active upload-box">

        <h2 data-setup-i18n="uploadTitle">آپلود فایل روی هاست</h2>

        <p data-setup-i18n="uploadDescription">ویدئو، تصویر، موسیقی، سند و هر فایل دیگری پشتیبانی می‌شود.</p>

        <input type="file" id="setupUploadFile">

        <div class="setup-preview" id="setupPreview">
            <img id="setupPreviewImage" alt="پیش‌نمایش تصویر">
            <video id="setupPreviewVideo" controls></video>
            <audio id="setupPreviewAudio" controls></audio>
            <div id="setupPreviewText" class="setup-preview-text"></div>
        </div>

        <input
            type="text"
            id="setupUploadName"
            placeholder="فقط نام فایل؛ پسوند خودکار اضافه می‌شود">

        <button type="button" id="setupUploadButton" onclick="startSetupUpload()">
            <span data-setup-i18n="startUpload">شروع آپلود</span>
        </button>

        <div class="setup-progress" id="setupUploadProgress">
            <div class="setup-progress-head">
                <span id="setupUploadProgressText">در حال آماده‌سازی...</span>
                <span id="setupUploadPercent">۰٪</span>
            </div>
            <div class="setup-progress-track">
                <div class="setup-progress-fill" id="setupUploadProgressBar"></div>
            </div>
        </div>

        <div class="upload-status" id="setupUploadStatus"></div>

        <div class="upload-link" id="setupUploadLink">
            <input type="text" id="setupUploadUrl" readonly onclick="this.select()">
            <button type="button" onclick="copySetupUploadLink()">کپی لینک فایل</button>
        </div>

    </section>


    <section id="setup-settings" class="setup-section settings-panel">
        <h2>تنظیمات</h2>
        <p class="settings-help">همه تنظیمات مقصد فایل، دامنه لینک عمومی و حساب کاربری این‌جاست. اطلاعات یک بار ذخیره می‌شود و دفعه بعد لازم نیست دوباره وارد کنید.</p>

        <div class="settings-card">
            <h3>۱) مقصد ذخیره فایل</h3>
            <div class="settings-choice">
                <label><input type="radio" name="settingsMode" value="direct"> دایرکت: همین هاست، همان پوشه‌ای که اسکریپت در آن است</label>
                <label><input type="radio" name="settingsMode" value="remote"> ارسال به هاست دانلود با FTP / FTPS / SFTP</label>
            </div>
            <div id="settingsRemote" class="settings-remote">
                <label for="settingsProtocol">پروتکل</label>
                <select id="settingsProtocol">
                    <option value="sftp">SFTP</option>
                    <option value="ftp">FTP</option>
                    <option value="ftps">FTPS (FTP با TLS)</option>
                </select>
                <label for="settingsHost">لینک / آدرس سرور</label>
                <input type="text" id="settingsHost" dir="ltr" placeholder="sftp://host.example.com:22" autocomplete="off">
                <label for="settingsPort">پورت (اختیاری)</label>
                <input type="number" id="settingsPort" dir="ltr" min="0" max="65535" placeholder="پیش‌فرض: SFTP ۲۲ و FTP ۲۱">
                <label for="settingsPath">آدرس مقصد روی سرور</label>
                <input type="text" id="settingsPath" dir="ltr" placeholder="domain/myDomain/public_html" autocomplete="off">
                <small>اگر با / شروع شود مسیر مطلق است، وگرنه نسبت به پوشه اصلی کاربر روی سرور مقصد. پوشه‌های ناموجود هنگام ارسال ساخته می‌شوند.</small>
                <label for="settingsUsername">نام کاربری FTP/SFTP</label>
                <input type="text" id="settingsUsername" dir="ltr" autocomplete="off">
                <label for="settingsPassword">رمز عبور FTP/SFTP</label>
                <input type="password" id="settingsPassword" dir="ltr" autocomplete="new-password">
                <small id="settingsPasswordHint"></small>
                <label class="settings-check"><input type="checkbox" id="settingsSslVerify"> بررسی گواهی SSL (برای FTPS)</label>
                <small>فایل بعد از ارسال و تأیید حجم در مقصد، همیشه از این هاست پاک می‌شود. اگر ارسال شکست بخورد، فایل برای تلاش دوباره نگه داشته می‌شود.</small>
            </div>
        </div>

        <div class="settings-card">
            <h3>۲) دامنه و لینک عمومی فایل</h3>
            <label for="settingsDomain">دامنه سایت (اگر خالی بماند خودکار تشخیص داده می‌شود)</label>
            <input type="text" id="settingsDomain" dir="ltr" placeholder="example.com" autocomplete="off">
            <label for="settingsScheme">پروتکل لینک</label>
            <select id="settingsScheme">
                <option value="https">https</option>
                <option value="http">http</option>
            </select>
            <label for="settingsDocroot">نام پوشه ریشه وب (همه چیز تا این پوشه از لینک حذف می‌شود)</label>
            <input type="text" id="settingsDocroot" dir="ltr" placeholder="public_html" autocomplete="off">
            <small id="settingsLinkPreview"></small>
        </div>

        <div class="settings-actions">
            <button type="button" id="settingsSave">ذخیره تنظیمات</button>
            <button type="button" id="settingsTest">تست اتصال</button>
        </div>
        <div id="settingsMessage" class="status" style="display:none"></div>

        <div class="settings-card">
            <h3>۳) حساب کاربری</h3>
            <small>تغییر نام کاربری و رمز بعد از ثبت اولین دانلود، در همین بخش داشبورد در دسترس است. (یا از منوی «کاربران».)</small>
        </div>
    </section>
    <section id="setup-library" class="setup-section">
        <h2 data-setup-i18n="libraryTitle">کتابخانه فایل‌ها</h2>
        <div id="setupLibraryGrid" class="setup-library-grid"></div>
    </section>

</div>

    </main>

</div>


<script>

const setupCsrf = <?php echo json_encode($_SESSION['csrf']); ?>;


const setupTranslations = {
    fa: {
        brand: 'انتقال فایل',
        manage: 'مدیریت فایل',
        uploadNav: 'آپلود از سیستم',
        downloadNav: 'دانلود از لینک',
        libraryNav: 'کتابخانه فایل‌ها',
        language: 'زبان پنل',
        title: 'جادوگر انتقال فایل',
        subtitle: 'مدیریت آپلود و دانلود فایل‌ها',
        uploadTitle: 'آپلود فایل روی هاست',
        uploadDescription: 'ویدئو، تصویر، موسیقی، سند و هر فایل دیگری پشتیبانی می‌شود.',
        startUpload: 'شروع آپلود',
        downloadUrl: 'لینک دانلود',
        fileName: 'نام فایل',
        registerDownload: 'ثبت دانلود',
        exampleUrl: 'نمونه لینک:',
        exampleName: 'نمونه نام فایل:',
        libraryTitle: 'کتابخانه فایل‌ها',
        empty: 'هنوز فایلی از این مرورگر آپلود نشده است.',
        copy: 'کپی لینک',
        remove: 'حذف'
    },
    en: {
        brand: 'File Transfer',
        manage: 'File management',
        uploadNav: 'Upload from computer',
        downloadNav: 'Download from URL',
        libraryNav: 'File library',
        language: 'Panel language',
        title: 'File Transfer Wizard',
        subtitle: 'Manage uploads and downloads',
        uploadTitle: 'Upload to this host',
        uploadDescription: 'Upload videos, images, music, documents, and other files.',
        startUpload: 'Start upload',
        downloadUrl: 'Download URL',
        fileName: 'File name',
        registerDownload: 'Save download',
        exampleUrl: 'Example URL:',
        exampleName: 'Example file name:',
        libraryTitle: 'File library',
        empty: 'No file has been uploaded from this browser yet.',
        copy: 'Copy link',
        remove: 'Remove'
    }
};


function setupLanguage()
{
    const saved = localStorage.getItem('wizard_language');
    if (saved === 'fa' || saved === 'en') {
        return saved;
    }
    return (navigator.language || '').toLowerCase().startsWith('fa') ? 'fa' : 'en';
}


let setupCurrentLanguage = setupLanguage();


function setupApplyLanguage(language)
{
    setupCurrentLanguage = language === 'fa' ? 'fa' : 'en';
    localStorage.setItem('wizard_language', setupCurrentLanguage);
    document.documentElement.lang = setupCurrentLanguage;
    document.documentElement.dir = setupCurrentLanguage === 'fa' ? 'rtl' : 'ltr';
    document.querySelectorAll('[data-setup-i18n]').forEach(function (element) {
        element.textContent = setupTranslations[setupCurrentLanguage][element.dataset.setupI18n];
    });
    document.getElementById('setupLanguage').value = setupCurrentLanguage;
    setupRenderLibrary();
}


function setupShowPanel(panelId)
{
    document.querySelectorAll('.setup-section').forEach(function (section) {
        section.classList.toggle('active', section.id === panelId);
    });
    document.querySelectorAll('[data-setup-target]').forEach(function (link) {
        link.classList.toggle('active', link.dataset.setupTarget === panelId);
    });
}


document.querySelectorAll('[data-setup-target]').forEach(function (link) {
    link.addEventListener('click', function (event) {
        event.preventDefault();
        setupShowPanel(link.dataset.setupTarget);
    });
});


document.getElementById('setupLanguage').addEventListener('change', function () {
    setupApplyLanguage(this.value);
});


async function setupLibraryRequest(action, values)
{
    const data = new FormData();
    data.append('csrf', setupCsrf);
    data.append('library_action', action);
    Object.keys(values || {}).forEach(function (key) {
        data.append(key, values[key]);
    });
    const response = await fetch('', {method: 'POST', body: data, cache: 'no-store'});
    return response.json();
}


async function setupRenderLibrary()
{
    const grid = document.getElementById('setupLibraryGrid');
    const result = await setupLibraryRequest('list');
    const items = result.ok && Array.isArray(result.items) ? result.items : [];
    grid.innerHTML = '';
    if (!items.length) {
        grid.textContent = setupTranslations[setupCurrentLanguage].empty;
        return;
    }
    items.forEach(function (item) {
        const card = document.createElement('div');
        card.className = 'setup-library-card';
        const name = document.createElement('strong');
        name.textContent = item.name;
        const meta = document.createElement('small');
        meta.textContent = item.type || 'file';
        const link = document.createElement('input');
        link.value = item.url;
        link.readOnly = true;
        const copy = document.createElement('button');
        copy.type = 'button';
        copy.textContent = setupTranslations[setupCurrentLanguage].copy;
        copy.onclick = function () {
            navigator.clipboard.writeText(item.url);
        };
        const remove = document.createElement('button');
        remove.type = 'button';
        remove.textContent = setupTranslations[setupCurrentLanguage].remove;
        remove.onclick = function () {
            setupLibraryRequest('remove', {id: item.id}).then(setupRenderLibrary);
        };
        card.append(name, meta, link, copy, remove);
        grid.appendChild(card);
    });
}


setupApplyLanguage(setupCurrentLanguage);
setupShowPanel(location.hash === '#setup-download' ? 'setup-download' :
    location.hash === '#setup-library' ? 'setup-library' : 'setup-upload');

async function startSetupUpload()
{
    const fileInput = document.getElementById('setupUploadFile');
    const nameInput = document.getElementById('setupUploadName');
    const button = document.getElementById('setupUploadButton');
    const status = document.getElementById('setupUploadStatus');
    const linkBox = document.getElementById('setupUploadLink');
    const urlBox = document.getElementById('setupUploadUrl');
    const progress = document.getElementById('setupUploadProgress');
    const progressBar = document.getElementById('setupUploadProgressBar');
    const progressPercent = document.getElementById('setupUploadPercent');
    const progressText = document.getElementById('setupUploadProgressText');
    const file = fileInput.files[0];

    if (!file) {
        status.style.display = 'block';
        status.innerText = 'Choose a file first.';
        return;
    }

    const filename = nameInput.value.trim() || file.name;
    const chunkSize = 1 * 1024 * 1024;
    const totalChunks = Math.max(1, Math.ceil(file.size / chunkSize));
    button.disabled = true;
    status.style.display = 'block';
    linkBox.style.display = 'none';
    progress.style.display = 'block';
    progressBar.style.width = '0%';
    progressPercent.innerText = '۰٪';
    progressText.innerText = 'در حال آماده‌سازی...';

    try {
        const initData = new FormData();
        initData.append('csrf', setupCsrf);
        initData.append('upload_action', 'init');
        initData.append('filename', filename);
        initData.append('original_filename', file.name);
        initData.append('size', file.size);
        const initResponse = await fetch('', { method: 'POST', body: initData });
        const init = await initResponse.json();

        if (!init.ok) {
            throw new Error(init.error || 'Cannot create upload session.');
        }

        for (let index = 0; index < totalChunks; index++) {
            const chunkData = new FormData();
                chunkData.append('csrf', setupCsrf);
            chunkData.append('upload_action', 'chunk');
            chunkData.append('upload_id', init.upload_id);
            chunkData.append('chunk_index', index);
            chunkData.append('total_chunks', totalChunks);
            chunkData.append('chunk', file.slice(index * chunkSize, (index + 1) * chunkSize), filename);
            status.innerText = 'در حال آپلود بخش ' + (index + 1) + ' از ' + totalChunks + '...';
            progressText.innerText = 'در حال آپلود بخش ' + (index + 1) + ' از ' + totalChunks + '...';
            const chunkResponse = await fetch('', { method: 'POST', body: chunkData });
            const chunk = await chunkResponse.json();

            if (!chunk.ok) {
                throw new Error(chunk.error || 'Upload part failed.');
            }

            const percent = Math.round((index + 1) / totalChunks * 100);
            progressBar.style.width = percent + '%';
            progressPercent.innerText = percent.toLocaleString('fa-IR') + '٪';
        }

        const finishData = new FormData();
        finishData.append('csrf', setupCsrf);
        finishData.append('upload_action', 'finish');
        finishData.append('upload_id', init.upload_id);
        const finishResponse = await fetch('', { method: 'POST', body: finishData });
        const finished = await finishResponse.json();

        if (!finished.ok) {
            throw new Error(finished.error || 'Cannot finalize upload.');
        }

        if (finished.destination && !finished.url) {
            progressText.innerText = 'آپلود کامل شد.';
            progressBar.style.width = '100%';
            progressPercent.innerText = '۱۰۰٪';
            status.innerText = 'به مقصد FTP/SFTP منتقل شد: ' + finished.destination;
            return;
        }

        urlBox.value = finished.url;
        linkBox.style.display = 'block';
        const libraryData = new FormData();
        libraryData.append('csrf', setupCsrf);
        libraryData.append('library_action', 'save');
        libraryData.append('name', finished.filename || filename);
        libraryData.append('url', finished.url);
        libraryData.append('type', file.type || 'application/octet-stream');
        await fetch('', {method: 'POST', body: libraryData, cache: 'no-store'});
        progressText.innerText = 'آپلود کامل شد.';
        progressBar.style.width = '100%';
        progressPercent.innerText = '۱۰۰٪';
        status.innerText = 'آپلود با موفقیت انجام شد.';
    } catch (error) {
        status.innerText = error.message || 'Upload failed.';
    } finally {
        button.disabled = false;
    }
}


document.getElementById('setupUploadFile').addEventListener('change', function () {
    const file = this.files[0];
    const box = document.getElementById('setupPreview');
    const image = document.getElementById('setupPreviewImage');
    const video = document.getElementById('setupPreviewVideo');
    const audio = document.getElementById('setupPreviewAudio');
    const text = document.getElementById('setupPreviewText');

    if (!file) {
        return;
    }

    image.style.display = 'none';
    video.style.display = 'none';
    audio.style.display = 'none';
    text.style.display = 'none';

    const source = URL.createObjectURL(file);
    if (file.type.startsWith('image/')) {
        image.src = source;
        image.style.display = 'block';
    } else if (file.type.startsWith('video/')) {
        video.src = source;
        video.style.display = 'block';
    } else if (file.type.startsWith('audio/')) {
        audio.src = source;
        audio.style.display = 'block';
    } else {
        text.innerText = 'این فایل پیش‌نمایش مستقیم ندارد.';
        text.style.display = 'block';
    }

    box.style.display = 'block';
});


async function copySetupUploadLink()
{
    const urlBox = document.getElementById('setupUploadUrl');
    urlBox.select();
    if (navigator.clipboard) {
        await navigator.clipboard.writeText(urlBox.value);
    } else {
        document.execCommand('copy');
    }
    document.getElementById('setupUploadStatus').innerText = 'Link copied.';
}


const csrf = setupCsrf;
/* =========================================================
   DESTINATION SETTINGS
========================================================= */
const settingsMessage = document.getElementById('settingsMessage');
const settingsRemote = document.getElementById('settingsRemote');
const settingsModeInputs = document.querySelectorAll('input[name="settingsMode"]');
function settingsShow(text, type)
{
    settingsMessage.textContent = text;
    settingsMessage.className = 'status ' + (type || '');
    settingsMessage.style.display = text ? 'block' : 'none';
    if (text && settingsMessage.scrollIntoView) {
        settingsMessage.scrollIntoView({behavior: 'smooth', block: 'nearest'});
    }
}
function settingsCurrentMode()
{
    const checked = document.querySelector('input[name="settingsMode"]:checked');
    return checked ? checked.value : 'direct';
}
function settingsUpdateVisibility()
{
    settingsRemote.classList.toggle('active', settingsCurrentMode() === 'remote');
}
function settingsShowPreview(data)
{
    const box = document.getElementById('settingsLinkPreview');
    if (!box) {
        return;
    }
    const parts = [];
    if (data.detected_domain) {
        parts.push('دامنه تشخیص‌داده‌شده: ' + data.detected_domain);
    }
    if (data.public_url_example) {
        parts.push('نمونه لینک فایل: ' + data.public_url_example);
    } else {
        parts.push('هنوز دامنه‌ای مشخص نیست؛ دامنه را وارد کنید تا لینک عمومی ساخته شود.');
    }
    box.textContent = parts.join(' | ');
}
async function settingsRequest(action, values)
{
    const data = new FormData();
    data.append('csrf', csrf);
    data.append('settings_action', action);
    Object.keys(values || {}).forEach(function (key) {
        data.append(key, values[key]);
    });
    const response = await fetch('', {method: 'POST', body: data, cache: 'no-store', credentials: 'same-origin'});
    const text = await response.text();
    try {
        return JSON.parse(text);
    } catch (e) {
        return {
            ok: false,
            error: 'پاسخ نامعتبر از سرور (HTTP ' + response.status + '): ' +
                text.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 200)
        };
    }
}
function settingsCollect()
{
    return {
        mode: settingsCurrentMode(),
        protocol: document.getElementById('settingsProtocol').value,
        host: document.getElementById('settingsHost').value,
        port: document.getElementById('settingsPort').value,
        remote_path: document.getElementById('settingsPath').value,
        username: document.getElementById('settingsUsername').value,
        password: document.getElementById('settingsPassword').value,
        ssl_verify: document.getElementById('settingsSslVerify').checked ? '1' : '0',
        public_domain: document.getElementById('settingsDomain').value,
        public_scheme: document.getElementById('settingsScheme').value,
        docroot: document.getElementById('settingsDocroot').value
    };
}
async function settingsLoad()
{
    try {
        const data = await settingsRequest('get');
        if (!data.ok) {
            return;
        }
        const s = data.settings;
        settingsModeInputs.forEach(function (input) {
            input.checked = input.value === s.mode;
        });
        document.getElementById('settingsProtocol').value = s.protocol;
        document.getElementById('settingsHost').value = s.host;
        document.getElementById('settingsPort').value = s.port > 0 ? s.port : '';
        document.getElementById('settingsPath').value = s.remote_path;
        document.getElementById('settingsUsername').value = s.username;
        document.getElementById('settingsPassword').value = '';
        document.getElementById('settingsSslVerify').checked = !!s.ssl_verify;
        document.getElementById('settingsDomain').value = s.public_domain || '';
        document.getElementById('settingsScheme').value = s.public_scheme || 'https';
        document.getElementById('settingsDocroot').value = s.docroot || 'public_html';
        document.getElementById('settingsPasswordHint').textContent = s.has_password
            ? 'رمز ذخیره شده است. فقط برای تغییر آن، رمز جدید را وارد کنید.'
            : (s.crypto_available ? '' : 'هشدار: افزونه openssl برای ذخیره امن رمز فعال نیست.');
        if (!s.sftp_available) {
            settingsShow('هشدار: cURL این هاست از SFTP پشتیبانی نمی‌کند؛ از FTP یا FTPS استفاده کنید.', 'error');
        }
        settingsShowPreview(s);
        settingsUpdateVisibility();
    } catch (e) {
        console.log(e);
    }
}
async function settingsSubmit(action)
{
    const saveButton = document.getElementById('settingsSave');
    const testButton = document.getElementById('settingsTest');
    saveButton.disabled = true;
    testButton.disabled = true;
    settingsShow(action === 'test' ? 'در حال تست اتصال...' : 'در حال ذخیره...', '');
    try {
        const data = await settingsRequest(action, settingsCollect());
        if (!data.ok) {
            settingsShow(data.error || 'عملیات ناموفق بود.', 'error');
        } else if (action === 'test') {
            settingsShow(data.warning ? data.warning : 'اتصال و ورود با موفقیت انجام شد.', 'success');
            settingsShowPreview(data);
        } else {
            await settingsLoad();
            settingsShow('تنظیمات ذخیره شد.', 'success');
        }
    } catch (e) {
        settingsShow('ارتباط با سرور برقرار نشد. صفحه را تازه کنید و دوباره تلاش کنید.', 'error');
    } finally {
        saveButton.disabled = false;
        testButton.disabled = false;
    }
}
settingsModeInputs.forEach(function (input) {
    input.addEventListener('change', settingsUpdateVisibility);
});
document.getElementById('settingsSave').addEventListener('click', function () {
    settingsSubmit('save');
});
document.getElementById('settingsTest').addEventListener('click', function () {
    settingsSubmit('test');
});
settingsLoad();

</script>

</body>

</html>

<?php

exit;

}


/* =========================================================
   CONFIG VARIABLES
========================================================= */

$url =
    $config['url'];

$filename =
    $config['filename'];

$file =
    __DIR__ . '/' . $filename;

$temp =
    $file . '.part';


/* =========================================================
   STATUS API
========================================================= */

if (isset($_GET['status'])) {

    header(
        'Content-Type: application/json; charset=utf-8'
    );

    header(
        'Cache-Control: no-store, no-cache, must-revalidate'
    );

    clearstatcache(true);

    $status =
        readStatus();


    /*
     * حجم واقعی .part
     */

    if (file_exists($temp)) {

        $status['downloaded'] =
            filesize($temp);
    }


    /*
     * فایل نهایی
     */

    $statusSettings = loadTransferSettings(currentUser());

    if (file_exists($file)) {

        if ($statusSettings['mode'] !== 'remote') {

            $status['downloaded'] =
                filesize($file);

            $status['status'] =
                'complete';

            if ($status['total'] > 0) {

                $status['percent'] =
                    100;
            }

        } elseif (
            isset($status['status']) &&
            $status['status'] === 'complete' &&
            (isset($status['mode']) ? $status['mode'] : 'direct') !== 'remote'
        ) {
            /* see below */

            /*
             * دانلود قبلاً در حالت دایرکت تمام شده؛
             * حالا مقصد FTP/SFTP است و فایل هنوز ارسال نشده.
             */

            $status['status'] =
                'prepared';

            $status['downloaded'] =
                filesize($file);

            $status['total'] =
                filesize($file);

            $status['message'] =
                'فایل روی همین هاست هست؛ برای ارسال به هاست مقصد دکمه را بزنید.';
        }
    }
    elseif (
        $statusSettings['mode'] === 'remote' &&
        isset($status['status']) &&
        $status['status'] === 'complete' &&
        (isset($status['mode']) ? $status['mode'] : 'direct') !== 'remote'
    ) {
        /*
         * وضعیت «کامل» مربوط به دانلود قدیمی در حالت دایرکت است،
         * نه ارسال به مقصد؛ پس آماده شروع دوباره است.
         */
        $status['status'] = 'idle';
        $status['downloaded'] = 0;
        $status['percent'] = 0;
        $status['message'] = 'آماده؛ برای دانلود و ارسال به هاست مقصد دکمه را بزنید.';
    }


    /*
     * اطمینان از 100%
     */

    if (
        $status['total'] > 0 &&
        $status['downloaded'] >=
        $status['total']
    ) {
        $status['percent'] = 100;
    }


    echo json_encode(
        $status,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES
    );

    exit;
}


/* =========================================================
   PREPARE
========================================================= */

if (isset($_GET['prepare'])) {

    header(
        'Content-Type: application/json; charset=utf-8'
    );

    header(
        'Cache-Control: no-store'
    );


    $prepSettings = loadTransferSettings(currentUser());
    $prepRemote = ($prepSettings['mode'] === 'remote');


    /*
     * حالت FTP/SFTP: قبل از دانلود حجیم، اتصال مقصد را تست می‌کنیم
     */

    if ($prepRemote) {

        $prepCheck = remoteTestConnection($prepSettings);

        if (!$prepCheck['ok']) {

            writeStatus([
                'status'     => 'error',
                'downloaded' => 0,
                'total'      => 0,
                'percent'    => 0,
                'speed'      => 0,
                'message'    => $prepCheck['error']
            ]);

            echo json_encode([
                'ok'    => false,
                'error' => $prepCheck['error']
            ], JSON_UNESCAPED_UNICODE);

            exit;
        }

        /*
         * فایل کامل روی همین هاست هست و فقط باید ارسال شود
         */

        if (file_exists($file)) {

            $size =
                filesize($file);

            writeStatus([
                'status'     => 'prepared',
                'downloaded' => $size,
                'total'      => $size,
                'percent'    => 100,
                'speed'      => 0,
                'message'    => 'دانلود کامل است؛ آماده ارسال به هاست مقصد.'
            ]);

            echo json_encode([
                'ok'         => true,
                'complete'   => false,
                'total'      => $size,
                'downloaded' => $size
            ]);

            exit;
        }
    }


    /*
     * اگر فایل نهایی وجود دارد
     */

    if (file_exists($file) && !$prepRemote) {

        $size =
            filesize($file);


        writeStatus([
            'status'     => 'complete',
            'downloaded' => $size,
            'total'      => $size,
            'percent'    => 100,
            'speed'      => 0,
            'message'    =>
                'دانلود قبلاً کامل شده است.'
        ]);


        echo json_encode([
            'ok' =>
                true,

            'complete' =>
                true,

            'total' =>
                $size,

            'downloaded' =>
                $size
        ]);

        exit;
    }


    /*
     * Probe remote server
     */

    $probe =
        probeRemoteFile($url);


    if (!$probe['ok']) {

        writeStatus([
            'status'     => 'error',
            'downloaded' => 0,
            'total'      => 0,
            'percent'    => 0,
            'speed'      => 0,
            'message'    =>
                $probe['error']
        ]);


        echo json_encode([
            'ok' =>
                false,

            'error' =>
                $probe['error']
        ]);

        exit;
    }


    $total =
        $probe['total'];


    /*
     * حالت FTP/SFTP: اگر فایل کامل از قبل در مقصد هست، دانلود تکرار نشود
     */

    if ($prepRemote) {

        $prepRemoteFile = remoteFileSize($prepSettings, $filename);

        if (
            $prepRemoteFile['ok'] &&
            !$prepRemoteFile['missing'] &&
            $prepRemoteFile['size'] === (int)$total
        ) {

            writeStatus([
                'status'      => 'complete',
                'mode'        => 'remote',
                'destination' => remoteDestinationLabel($prepSettings, $filename),
                'public_url'  => remotePublicUrl($prepSettings, $filename),
                'downloaded'  => $total,
                'total'       => $total,
                'percent'     => 100,
                'speed'       => 0,
                'message'     => 'فایل از قبل در مقصد کامل موجود است.'
            ]);

            echo json_encode([
                'ok'         => true,
                'complete'   => true,
                'total'      => $total,
                'downloaded' => $total
            ]);

            exit;
        }
    }


    clearstatcache(true);


    $downloaded =
        file_exists($temp)
        ? filesize($temp)
        : 0;


    /*
     * .part بزرگ‌تر از فایل واقعی
     */

    if ($downloaded > $total) {

        @unlink($temp);

        $downloaded = 0;
    }


    $percent =
        $total > 0
        ? min(
            100,
            (
                $downloaded /
                $total
            ) * 100
        )
        : 0;


    writeStatus([
        'status'     => 'prepared',
        'downloaded' => $downloaded,
        'total'      => $total,
        'percent'    => $percent,
        'speed'      => 0,
        'message'    =>
            $downloaded > 0
            ? 'Resume point found.'
            : 'آماده دانلود.'
    ]);


    echo json_encode([
        'ok' =>
            true,

        'complete' =>
            false,

        'total' =>
            $total,

        'downloaded' =>
            $downloaded
    ]);

    exit;
}


/* =========================================================
   DOWNLOAD PROCESS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['download'])) {

    requirePostCsrf();

    header(
        'Content-Type: text/plain; charset=utf-8'
    );

    header(
        'Cache-Control: no-store'
    );


    /*
     * جلوگیری از دو دانلود همزمان
     */

    if (is_dir($lockDir)) {

        $lockAge =
            time() -
            max(
                (int)@filemtime($lockDir),
                (int)@filemtime($statusFile)
            );


        /*
         * lock قدیمی
         */

        if ($lockAge > 900) {

            @rmdir($lockDir);

        } else {

            echo
                "Another download is already running.";

            exit;
        }
    }


    /*
     * mkdir اتمیک
     */

    if (!@mkdir($lockDir, 0700)) {

        echo
            "Another download is already running.";

        exit;
    }


    /*
     * حتی با exit یا خطای مرگبار هم lock آزاد شود
     */

    register_shutdown_function(function () use ($lockDir) {
        if (is_dir($lockDir)) {
            @rmdir($lockDir);
        }
    });


    try {

        $transferSettings = loadTransferSettings(currentUser());
        $remoteMode = ($transferSettings['mode'] === 'remote');
        $failureStreak = 0;


        /*
         * حالت FTP/SFTP: اگر فایل کامل روی همین هاست هست،
         * فقط مرحله ارسال به هاست مقصد انجام می‌شود.
         */

        if ($remoteMode && file_exists($file)) {

            if (deliverToRemote(
                $transferSettings,
                $file,
                $filename,
                filesize($file)
            )) {
                echo "Transfer complete.";
            }

            exit;
        }


        /*
         * Remote probe
         */

        $probe =
            probeRemoteFile($url);


        if (!$probe['ok']) {

            writeStatus([
                'status' =>
                    'error',

                'downloaded' =>
                    0,

                'total' =>
                    0,

                'percent' =>
                    0,

                'speed' =>
                    0,

                'message' =>
                    $probe['error']
            ]);

            echo
                $probe['error'];

            exit;
        }


        $total =
            $probe['total'];


        clearstatcache(true, $temp);


        $startSize =
            file_exists($temp)
            ? filesize($temp)
            : 0;


        /*
         * اگر فایل نهایی همین حالا وجود دارد
         */

        if (file_exists($file)) {

            $finalSize =
                filesize($file);


            writeStatus([
                'status' =>
                    'complete',

                'downloaded' =>
                    $finalSize,

                'total' =>
                    $total,

                'percent' =>
                    100,

                'speed' =>
                    0,

                'message' =>
                    'Download complete.'
            ]);

            exit;
        }


        /*
         * اگر .part بزرگ‌تر از total است
         */

        if ($startSize > $total) {

            @unlink($temp);

            $startSize = 0;
        }


        writeStatus([
            'status' =>
                'downloading',

            'downloaded' =>
                $startSize,

            'total' =>
                $total,

            'percent' =>
                $total > 0
                ? (
                    $startSize /
                    $total
                ) * 100
                : 0,

            'speed' =>
                0,

            'message' =>
                $startSize > 0
                ? 'Resuming download...'
                : 'شروع دانلود...'
        ]);


        /*
         * =====================================================
         * DOWNLOAD LOOP
         * =====================================================
         */

        while (true) {

            clearstatcache(
                true,
                $temp
            );


            $startSize =
                file_exists($temp)
                ? filesize($temp)
                : 0;


            /*
             * تمام شده؟
             */

            if ($startSize >= $total) {
                break;
            }


            /*
             * فایل append
             */

            $fp =
                fopen($temp, 'ab');


            if (!$fp) {

                writeStatus([
                    'status' =>
                        'error',

                    'downloaded' =>
                        $startSize,

                    'total' =>
                        $total,

                    'percent' =>
                        (
                            $startSize /
                            $total
                        ) * 100,

                    'speed' =>
                        0,

                    'message' =>
                        'Cannot open .part file.'
                ]);

                exit;
            }


            $responseCode =
                0;

            $rangeAccepted =
                false;

            $contentRange =
                '';

            $lastStateWrite =
                0;

            $lastStateBytes =
                $startSize;

            $transferStarted =
                microtime(true);


            $ch =
                curl_init($url);


            curl_setopt_array($ch, [

                CURLOPT_FILE =>
                    $fp,

                CURLOPT_FOLLOWLOCATION =>
                    true,

                CURLOPT_MAXREDIRS => 10,
        CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
        CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,

                CURLOPT_HTTP_VERSION =>
                    CURL_HTTP_VERSION_1_1,

                CURLOPT_CONNECTTIMEOUT =>
                    60,

                CURLOPT_TIMEOUT =>
                    0,

                /*
                 * Range واقعی
                 */
                CURLOPT_HTTPHEADER => [
                    'Range: bytes=' .
                    $startSize .
                    '-'
                ],

                CURLOPT_USERAGENT =>
                    'Reliable-Large-File-Downloader/1.0',

                CURLOPT_FAILONERROR =>
                    false,

                CURLOPT_NOPROGRESS =>
                    false,


                /*
                 * Header callback
                 */

                CURLOPT_HEADERFUNCTION =>
                    function (
                        $ch,
                        $header
                    ) use (
                        &$responseCode,
                        &$rangeAccepted,
                        &$contentRange
                    ) {

                        $line =
                            trim($header);


                        /*
                         * HTTP status
                         */

                        if (
                            preg_match(
                                '#^HTTP/\S+\s+(\d+)#i',
                                $line,
                                $m
                            )
                        ) {

                            $responseCode =
                                (int)$m[1];


                            /*
                             * Range پذیرفته شد
                             */

                            if (
                                $responseCode ==
                                206
                            ) {

                                $rangeAccepted =
                                    true;
                            }
                        }


                        /*
                         * Content-Range
                         */

                        if (
                            stripos(
                                $line,
                                'Content-Range:'
                            ) === 0
                        ) {

                            $contentRange =
                                trim(
                                    substr(
                                        $line,
                                        strlen(
                                            'Content-Range:'
                                        )
                                    )
                                );
                        }


                        return strlen(
                            $header
                        );
                    },


                /*
                 * Progress
                 */

                CURLOPT_PROGRESSFUNCTION =>
                    function (
                        $ch,
                        $downloadTotal,
                        $downloadNow,
                        $uploadTotal,
                        $uploadNow
                    ) use (
                        $startSize,
                        $total,
                        &$lastStateWrite,
                        &$lastStateBytes,
                        $transferStarted
                    ) {

                        $current =
                            $startSize +
                            $downloadNow;


                        $now =
                            microtime(true);


                        if (
                            (
                                $now -
                                $lastStateWrite
                            ) >= 1
                            ||
                            (
                                $current -
                                $lastStateBytes
                            ) >=
                            4 * 1024 * 1024
                        ) {


                            $elapsed =
                                max(
                                    0.001,
                                    $now -
                                    $transferStarted
                                );


                            $speed =
                                $downloadNow /
                                $elapsed;


                            $percent =
                                $total > 0
                                ? (
                                    $current /
                                    $total
                                ) * 100
                                : 0;


                            if (
                                $percent > 100
                            ) {
                                $percent =
                                    100;
                            }


                            writeStatus([
                                'status' =>
                                    'downloading',

                                'downloaded' =>
                                    $current,

                                'total' =>
                                    $total,

                                'percent' =>
                                    $percent,

                                'speed' =>
                                    $speed,

                                'message' =>
                                    'در حال دانلود...'
                            ]);


                            $lastStateWrite =
                                $now;

                            $lastStateBytes =
                                $current;
                        }


                        return 0;
                    },


                CURLOPT_TCP_KEEPALIVE =>
                    1,

                CURLOPT_TCP_KEEPIDLE =>
                    60,

                CURLOPT_TCP_KEEPINTVL =>
                    30
            ]);


            $result =
                curl_exec($ch);


            $curlError =
                curl_error($ch);


            curl_close($ch);

            fclose($fp);


            clearstatcache(
                true,
                $temp
            );


            $currentSize =
                file_exists($temp)
                ? filesize($temp)
                : 0;

            if ($currentSize > $startSize) {
                $failureStreak = 0;
            }


            /*
             * -------------------------------------------------
             * اگر Resume لازم بوده ولی Range پذیرفته نشده
             * -------------------------------------------------
             */

            if (
                $startSize > 0 &&
                !$rangeAccepted
            ) {

                writeStatus([
                    'status' =>
                        'error',

                    'downloaded' =>
                        $currentSize,

                    'total' =>
                        $total,

                    'percent' =>
                        min(
                            100,
                            (
                                $currentSize /
                                $total
                            ) * 100
                        ),

                    'speed' =>
                        0,

                    'message' =>
                        'Remote server refused resume (HTTP Range).'
                ]);

                exit;
            }


            /*
             * -------------------------------------------------
             * CURL ERROR
             * -------------------------------------------------
             */

            if ($result === false) {

                writeStatus([
                    'status' =>
                        'retrying',

                    'downloaded' =>
                        $currentSize,

                    'total' =>
                        $total,

                    'percent' =>
                        min(
                            100,
                            (
                                $currentSize /
                                $total
                            ) * 100
                        ),

                    'speed' =>
                        0,

                    'message' =>
                        'ارتباط قطع شد؛ تلاش مجدد...'
                ]);


                /*
                 * .part حفظ می‌شود.
                 */

                if (++$failureStreak > $maxFailureStreak) {

                failDownload(
                    'Download stopped after too many failed attempts.',
                    $currentSize,
                    $total
                );

                exit;
            }

                sleep($retryDelay);

                continue;
            }


            /*
             * -------------------------------------------------
             * HTTP CHECK
             * -------------------------------------------------
             */

            if (
                $startSize == 0 &&
                $responseCode != 200 &&
                $responseCode != 206
            ) {

                if (
                    $responseCode >= 400 &&
                    $responseCode < 500 &&
                    $responseCode != 408 &&
                    $responseCode != 429
                ) {
                    failDownload(
                        'Remote server refused the download (HTTP ' . $responseCode . ').',
                        $currentSize,
                        $total
                    );

                    exit;
                }


                writeStatus([
                    'status' =>
                        'retrying',

                    'downloaded' =>
                        $currentSize,

                    'total' =>
                        $total,

                    'percent' =>
                        min(
                            100,
                            (
                                $currentSize /
                                $total
                            ) * 100
                        ),

                    'speed' =>
                        0,

                    'message' =>
                        'HTTP error. Retrying...'
                ]);


                if (++$failureStreak > $maxFailureStreak) {

                failDownload(
                    'Download stopped after too many failed attempts.',
                    $currentSize,
                    $total
                );

                exit;
            }

                sleep($retryDelay);

                continue;
            }


            /*
             * Resume باید حتماً 206 باشد.
             */

            if (
                $startSize > 0 &&
                $responseCode != 206
            ) {

                writeStatus([
                    'status' =>
                        'error',

                    'downloaded' =>
                        $currentSize,

                    'total' =>
                        $total,

                    'percent' =>
                        min(
                            100,
                            (
                                $currentSize /
                                $total
                            ) * 100
                        ),

                    'speed' =>
                        0,

                    'message' =>
                        'Invalid resume response.'
                ]);

                exit;
            }


            /*
             * -------------------------------------------------
             * بررسی اینکه Content-Range از offset ما شروع شده
             * -------------------------------------------------
             */

            if (
                $startSize > 0 &&
                $rangeAccepted &&
                $contentRange !== ''
            ) {

                /*
                 * مثال:
                 * bytes 1048576-...
                 */

                if (
                    preg_match(
                        '#^bytes\s+(\d+)-#i',
                        $contentRange,
                        $m
                    )
                ) {

                    $rangeStart =
                        (int)$m[1];


                    if (
                        $rangeStart !=
                        $startSize
                    ) {

                        writeStatus([
                            'status' =>
                                'error',

                            'downloaded' =>
                                $currentSize,

                            'total' =>
                                $total,

                            'percent' =>
                                min(
                                    100,
                                    (
                                        $currentSize /
                                        $total
                                    ) * 100
                                ),

                            'speed' =>
                                0,

                            'message' =>
                                'Server returned an unexpected resume offset.'
                        ]);

                        exit;
                    }
                }
            }


            /*
             * -------------------------------------------------
             * هیچ داده‌ای دریافت نشده
             * -------------------------------------------------
             */

            if (
                $currentSize <=
                $startSize
            ) {

                writeStatus([
                    'status' =>
                        'retrying',

                    'downloaded' =>
                        $currentSize,

                    'total' =>
                        $total,

                    'percent' =>
                        min(
                            100,
                            (
                                $currentSize /
                                $total
                            ) * 100
                        ),

                    'speed' =>
                        0,

                    'message' =>
                        'No data received. Retrying...'
                ]);

                if (++$failureStreak > $maxFailureStreak) {

                failDownload(
                    'Download stopped after too many failed attempts.',
                    $currentSize,
                    $total
                );

                exit;
            }

                sleep($retryDelay);

                continue;
            }


            /*
             * -------------------------------------------------
             * آیا کامل شد؟
             * -------------------------------------------------
             */

            if (
                $currentSize >=
                $total
            ) {
                break;
            }


            /*
             * هنوز کامل نشده.
             * حلقه ادامه پیدا می‌کند.
             */

            writeStatus([
                'status' =>
                    'downloading',

                'downloaded' =>
                    $currentSize,

                'total' =>
                    $total,

                'percent' =>
                    min(
                        100,
                        (
                            $currentSize /
                            $total
                        ) * 100
                    ),

                'speed' =>
                    0,

                'message' =>
                        'ادامه دانلود...'
            ]);
        }


        /*
         * =====================================================
         * FINAL VERIFICATION
         * =====================================================
         */

        clearstatcache(
            true,
            $temp
        );


        $finalSize =
            file_exists($temp)
            ? filesize($temp)
            : 0;


        if (
            $finalSize !=
            $total
        ) {

            writeStatus([
                'status' =>
                    'error',

                'downloaded' =>
                    $finalSize,

                'total' =>
                    $total,

                'percent' =>
                    min(
                        100,
                        (
                            $finalSize /
                            $total
                        ) * 100
                    ),

                'speed' =>
                    0,

                'message' =>
                    'Final size verification failed.'
            ]);

            exit;
        }


        /*
         * =====================================================
         * FINAL RENAME
         * =====================================================
         */

        if (file_exists($file)) {
            @unlink($file);
        }


        if (!@rename($temp, $file)) {

            writeStatus([
                'status' =>
                    'error',

                'downloaded' =>
                    $finalSize,

                'total' =>
                    $total,

                'percent' =>
                    100,

                'speed' =>
                    0,

                'message' =>
                    'Download complete, but final rename failed.'
            ]);

            exit;
        }


        /*
         * =====================================================
         * COMPLETE
         * =====================================================
         */

        if ($remoteMode) {

            deliverToRemote(
                $transferSettings,
                $file,
                $filename,
                $finalSize
            );

        } else {

            writeStatus([
                'status'     => 'complete',
                'mode'       => 'direct',
                'downloaded' => $finalSize,
                'total'      => $total,
                'percent'    => 100,
                'speed'      => 0,
                'message'    => 'Download complete.'
            ]);
        }

    } finally {

        /*
         * آزاد کردن lock
         */

        if (is_dir($lockDir)) {
            @rmdir($lockDir);
        }
    }


    echo
        "Finished.";

    exit;
}

?>


<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport"
      content="width=device-width, initial-scale=1.0">

<title>جادوگر انتقال فایل</title>


<style>

* {
    box-sizing: border-box;
}

body {

    margin: 0;

    min-height: 100vh;

    display: flex;

    justify-content: center;

    align-items: center;

    background:
        radial-gradient(
            circle at top,
            #18243d 0%,
            #080c15 70%
        );

    font-family:
        Arial,
        Helvetica,
        sans-serif;

    color: white;
}


.card {

    width: min(700px, 94%);

    background:
        rgba(18, 25, 40, .96);

    border:
        1px solid
        rgba(255,255,255,.07);

    border-radius: 25px;

    padding: 32px;

    box-shadow:
        0 30px 90px
        rgba(0,0,0,.45);
}


.logo {

    width: 68px;
    height: 68px;

    margin: 0 auto 16px;

    border-radius: 20px;

    display: flex;

    justify-content: center;

    align-items: center;

    font-size: 32px;

    background: #1b2c4d;
}


.title {

    text-align: center;
}


.title h1 {

    margin: 0;

    font-size: 26px;
}


.title p {

    margin: 8px 0 28px;

    color: #8490a7;

    font-size: 13px;
}


/* =========================================================
   STEPS
========================================================= */

.steps {

    display: flex;

    margin-bottom: 28px;
}


.step {

    flex: 1;

    text-align: center;

    color: #637087;

    font-size: 12px;

    position: relative;
}


.step:not(:last-child)::after {

    content: "";

    position: absolute;

    top: 16px;

    left: 60%;

    right: -40%;

    height: 2px;

    background: #202a3d;
}


.circle {

    width: 34px;
    height: 34px;

    margin: 0 auto 7px;

    border-radius: 50%;

    display: flex;

    align-items: center;

    justify-content: center;

    background: #111a2a;

    border:
        1px solid
        #26334a;
}


.step.active {

    color: white;
}


.step.active .circle {

    background: #315efb;

    border-color: #315efb;
}


.step.done .circle {

    background: #1c744d;

    border-color: #1c744d;
}


/* =========================================================
   FILE
========================================================= */

.file {

    padding: 17px;

    background: #0c1320;

    border-radius: 14px;

    border:
        1px solid
        #202b40;

    margin-bottom: 22px;
}


.file-name {

    font-weight: bold;

    font-size: 14px;

    word-break: break-all;
}


.file-url {

    margin-top: 7px;

    color: #6f7d94;

    font-size: 11px;

    word-break: break-all;
}


/* =========================================================
   PROGRESS
========================================================= */

.progress-header {

    display: flex;

    justify-content: space-between;

    margin-bottom: 9px;

    font-size: 13px;
}


.progress {

    width: 100%;

    height: 18px;

    border-radius: 20px;

    background: #0a101a;

    overflow: hidden;

    border:
        1px solid
        #202a3c;
}


.bar {

    width: 0%;

    height: 100%;

    background:
        linear-gradient(
            90deg,
            #315efb,
            #6e8cff
        );

    border-radius: 20px;

    transition:
        width .35s ease;
}


.info-grid {

    margin-top: 18px;

    display: grid;

    grid-template-columns:
        repeat(3, 1fr);

    gap: 10px;
}


.info {

    background: #0d1422;

    border-radius: 12px;

    padding: 13px;

    text-align: center;
}


.info-label {

    font-size: 10px;

    color: #68758b;

    margin-bottom: 5px;
}


.info-value {

    font-size: 14px;

    font-weight: bold;
}


.status {

    margin-top: 18px;

    padding: 14px;

    text-align: center;

    border-radius: 12px;

    background: #101a2a;

    color: #9ba7bb;

    font-size: 13px;
}


button {

    width: 100%;

    margin-top: 20px;

    padding: 15px;

    border: 0;

    border-radius: 13px;

    background: #315efb;

    color: white;

    font-size: 15px;

    font-weight: bold;

    cursor: pointer;
}


button:disabled {

    opacity: .5;

    cursor: not-allowed;
}


.done {

    display: none;

    text-align: center;

    margin-top: 22px;
}


.upload-panel {

    margin-top: 28px;

    padding-top: 24px;

    border-top: 1px solid #202b40;
}


.upload-panel h2 {

    margin: 0 0 7px;

    font-size: 18px;
}


.upload-panel p {

    margin: 0 0 16px;

    color: #8490a7;

    font-size: 12px;
}


.upload-panel input[type="text"],
.upload-panel input[type="file"] {

    width: 100%;

    margin-bottom: 12px;

    padding: 12px;

    border: 1px solid #2b3850;

    border-radius: 10px;

    background: #0c1320;

    color: white;
}


.upload-panel button {

    margin-top: 4px;
}


.upload-progress {

    display: none;

    margin-top: 14px;
}


.upload-progress-bar {

    height: 12px;

    overflow: hidden;

    border-radius: 12px;

    background: #0a101a;
}


.upload-progress-fill {

    width: 0;

    height: 100%;

    background: linear-gradient(90deg, #1c9b68, #62d69e);

    transition: width .2s ease;
}


.upload-message {

    margin-top: 10px;

    color: #9ba7bb;

    font-size: 12px;
}


.upload-result {

    display: none;

    margin-top: 14px;
}


.upload-result input {

    margin: 0;

    color: #9fe0bf;

    cursor: text;
}


.done-icon {

    width: 68px;
    height: 68px;

    margin: auto;

    border-radius: 50%;

    background: #173c2b;

    display: flex;

    align-items: center;

    justify-content: center;

    font-size: 30px;
}


.small {

    color: #738198;

    font-size: 11px;

    margin-top: 8px;
}


iframe {

    display: none;
}


body {
    direction: rtl;
}


.main-shell {
    width: min(1180px, 96%);
    display: grid;
    grid-template-columns: 220px minmax(0, 1fr);
    gap: 18px;
}


.dashboard-sidebar {
    padding: 22px 14px;
    border: 1px solid rgba(255,255,255,.07);
    border-radius: 22px;
    background: rgba(18, 25, 40, .96);
}


.dashboard-brand {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 7px 9px 22px;
    font-weight: bold;
}


.dashboard-brand b {
    display: grid;
    width: 36px;
    height: 36px;
    place-items: center;
    border-radius: 11px;
    background: #315efb;
}


.dashboard-nav-label {
    padding: 14px 10px 7px;
    color: #68758b;
    font-size: 10px;
}


.dashboard-nav {
    display: block;
    padding: 11px;
    border-radius: 10px;
    color: #9ba7bb;
    font-size: 13px;
    text-decoration: none;
}


.dashboard-nav:hover,
.dashboard-nav.active {
    background: #1b2c4d;
    color: white;
}


.main-content {
    min-width: 0;
}


.dashboard-section {
    display: none;
}


.dashboard-section.active {
    display: block;
}


.language-box {
    margin-top: 24px;
    padding: 10px;
    border-top: 1px solid #202b40;
}


.language-box label {
    margin-bottom: 7px;
    font-size: 11px;
}


.language-box select {
    width: 100%;
    padding: 9px;
    border: 1px solid #2b3850;
    border-radius: 9px;
    background: #0c1320;
    color: white;
}


.library-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 16px;
}


.library-toolbar h2 {
    margin: 0;
    font-size: 20px;
}


.library-toolbar button {
    width: auto;
    margin: 0;
    padding: 9px 12px;
    font-size: 12px;
}


.library-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
    gap: 12px;
}


.library-card {
    padding: 14px;
    border: 1px solid #202b40;
    border-radius: 13px;
    background: #0c1320;
}


.library-icon {
    margin-bottom: 10px;
    font-size: 28px;
}


.library-name {
    overflow: hidden;
    margin-bottom: 5px;
    font-size: 13px;
    font-weight: bold;
    text-overflow: ellipsis;
    white-space: nowrap;
}


.library-meta {
    margin-bottom: 12px;
    color: #738198;
    font-size: 11px;
}


.library-link {
    width: 100%;
    margin-bottom: 8px;
    padding: 9px;
    border: 1px solid #2b3850;
    border-radius: 8px;
    background: #080c15;
    color: #9fe0bf;
    font-size: 10px;
}


.library-actions {
    display: flex;
    gap: 7px;
}


.library-actions button {
    margin: 0;
    padding: 9px;
    font-size: 11px;
}


.library-empty {
    padding: 38px 16px;
    border: 1px dashed #2b3850;
    border-radius: 13px;
    color: #8490a7;
    text-align: center;
    font-size: 13px;
}


.library-preview {
    display: none;
    margin-bottom: 16px;
    overflow: hidden;
    border: 1px solid #202b40;
    border-radius: 13px;
    background: #0c1320;
}


.library-preview img,
.library-preview video {
    display: none;
    width: 100%;
    max-height: 280px;
    object-fit: contain;
    background: #080c15;
}


.library-preview audio {
    display: none;
    width: 100%;
}


.library-preview-caption {
    padding: 10px 12px;
    color: #9ba7bb;
    font-size: 12px;
}


.preview-box {
    display: none;
    margin: 14px 0;
    overflow: hidden;
    border: 1px solid #202b40;
    border-radius: 13px;
    background: #0c1320;
}


.preview-box img,
.preview-box video {
    display: none;
    width: 100%;
    max-height: 260px;
    object-fit: contain;
    background: #080c15;
}


.preview-box audio {
    display: none;
    width: 100%;
}


.preview-caption {
    padding: 10px 12px;
    color: #9ba7bb;
    font-size: 12px;
}


.preview-document {
    padding: 30px 16px;
    text-align: center;
    color: #9ba7bb;
    font-size: 14px;
}


/* Dashboard visual polish */
body {
    background:
        radial-gradient(circle at 14% 10%, rgba(49,94,251,.18), transparent 30%),
        radial-gradient(circle at 86% 88%, rgba(28,155,104,.12), transparent 28%),
        #080c15;
    font-family: "Segoe UI", Tahoma, sans-serif;
}


.main-shell {
    align-items: stretch;
    gap: 22px;
}


.dashboard-sidebar,
.main-content .card {
    border-color: rgba(132,164,230,.14);
    box-shadow: 0 24px 70px rgba(0,0,0,.28);
}


.dashboard-sidebar {
    background: linear-gradient(165deg, rgba(24,36,61,.98), rgba(14,20,33,.98));
}


.dashboard-brand b {
    box-shadow: 0 10px 24px rgba(49,94,251,.3);
}


.dashboard-nav {
    transition: background .2s ease, color .2s ease, transform .2s ease;
}


.dashboard-nav:hover {
    transform: translateX(3px);
}


.main-content .card {
    background: linear-gradient(145deg, rgba(24,34,53,.98), rgba(14,20,33,.98));
}


button {
    box-shadow: 0 9px 20px rgba(49,94,251,.2);
    transition: transform .2s ease, filter .2s ease, box-shadow .2s ease;
}


button:hover:not(:disabled) {
    transform: translateY(-2px);
    filter: brightness(1.08);
    box-shadow: 0 12px 25px rgba(49,94,251,.28);
}


input:hover,
select:hover {
    border-color: #40567e;
}


input:focus,
select:focus {
    border-color: #5d82ff;
    box-shadow: 0 0 0 3px rgba(49,94,251,.14);
}


input[type="file"] {
    padding: 11px;
    border-style: dashed;
    background: rgba(8,12,21,.7);
}


@media(max-width:600px) {

    .app-shell {
        display: block;
    }

    .sidebar {
        margin-bottom: 14px;
        padding: 10px;
    }

    .brand {
        padding: 4px 8px 10px;
    }

    .nav-title {
        display: none;
    }

    .nav-link {
        display: inline-flex;
        margin: 2px;
    }

    .card {
        padding: 23px;
    }

    .info-grid {
        grid-template-columns: 1fr;
    }

}

.settings-panel label{display:block;margin:14px 0 6px;color:#aab5c8;font-size:13px}
.settings-panel input[type="text"],.settings-panel input[type="password"],.settings-panel input[type="number"],.settings-panel select{width:100%;padding:12px;box-sizing:border-box;border:1px solid #30415f;border-radius:9px;background:#0c1320;color:#fff}
.settings-panel .settings-choice label,.settings-panel .settings-check{display:flex;align-items:center;gap:10px;color:#e6ecf7;cursor:pointer}
.settings-panel input[type="radio"],.settings-panel input[type="checkbox"]{width:auto;margin:0}
.settings-panel small{display:block;margin-top:6px;color:#7f8ca3;font-size:12px;line-height:1.8}
.settings-panel .settings-help{color:#9ba7bb;line-height:1.9}
.settings-remote{display:none}
.settings-remote.active{display:block}
.settings-actions{display:flex;gap:10px;margin-top:22px;flex-wrap:wrap}
.settings-actions button{flex:1;min-width:140px}
.settings-panel .status.error{color:#ff9b9b}.settings-panel .status.success{color:#7ee2a8}
@media(max-width:640px){.settings-actions button{min-width:100%}}
.settings-card{margin-top:18px;padding:18px;border:1px solid #263652;border-radius:14px;background:#0e1626}
.settings-card h3{margin:0 0 6px;font-size:16px;color:#e6ecf7}
.settings-card form{margin-top:14px;padding-top:14px;border-top:1px solid #1d2a42}
.settings-card form button{margin-top:12px}
.settings-panel .status.error,.settings-panel .status.success{margin-top:14px}
</style>

</head>


<body>


<div class="main-shell">

    <aside class="dashboard-sidebar">
        <div class="dashboard-brand"><b>↕</b> <span data-i18n="brand">انتقال فایل</span></div>
        <div class="dashboard-nav-label" data-i18n="manage">مدیریت فایل</div>
        <a class="dashboard-nav active" data-section="upload-section" href="#upload-section" data-i18n="uploadNav">آپلود از سیستم</a>
        <a class="dashboard-nav" data-section="download-section" href="#download-section" data-i18n="downloadNav">دانلود از لینک</a>
        <a class="dashboard-nav" data-section="library-section" href="#library-section" data-i18n="libraryNav">کتابخانه فایل‌ها</a>
        <a class="dashboard-nav" data-section="settings-section" href="#settings-section" data-i18n="settingsNav">تنظیمات مقصد</a>
        <a class="dashboard-nav" data-section="users-section" href="#users-section">کاربران</a>
        <a class="dashboard-nav" href="?logout=1">خروج (<?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8'); ?>)</a>
        <div class="language-box">
            <label for="languageSelect" data-i18n="language">زبان پنل</label>
            <select id="languageSelect">
                <option value="auto">تشخیص خودکار</option>
                <option value="fa">فارسی</option>
                <option value="en">English</option>
            </select>
        </div>
    </aside>

    <main class="main-content">
<?php if (!empty($_SESSION['must_change_password'])): ?>
<div class="status error">هشدار امنیتی: هنوز رمز اولیه یا پیش‌فرض را تغییر نداده‌اید. از بخش «کاربران» رمز خود را عوض کنید.</div>
<?php endif; ?>

<div class="card">


    <div class="logo">
        ↓
    </div>


    <div class="title">

        <h1>
            <span data-i18n="title">جادوگر انتقال فایل</span>
        </h1>

        <p>
            <span data-i18n="subtitle">مدیریت آپلود و دانلود فایل‌ها</span>
        </p>

    </div>


    <section id="download-section" class="dashboard-section">

    <!-- STEPS -->

    <div id="download-panel" class="steps">

        <div
            class="step active"
            id="step1">

            <div class="circle">
                1
            </div>

            آماده‌سازی

        </div>


        <div
            class="step"
            id="step2">

            <div class="circle">
                2
            </div>

            دانلود

        </div>


        <div
            class="step"
            id="step3">

            <div class="circle">
                3
            </div>

            تکمیل

        </div>

    </div>


    <!-- FILE -->

    <div class="file">

        <div class="file-name">

            <?php
            echo htmlspecialchars(
                $filename,
                ENT_QUOTES,
                'UTF-8'
            );
            ?>

        </div>


        <div class="file-url">

            <?php
            echo htmlspecialchars(
                $url,
                ENT_QUOTES,
                'UTF-8'
            );
            ?>

        </div>
        <div class="file-url">
            <?php
            $hintSettings = loadTransferSettings(currentUser());
            echo $hintSettings['mode'] === 'remote'
                ? 'مقصد: ' . htmlspecialchars(remoteDestinationLabel($hintSettings, $filename), ENT_QUOTES, 'UTF-8')
                : 'مقصد: همین هاست (دایرکت)';
            ?>
        </div>

    </div>


    <div id="downloadPreview" class="preview-box">
        <img id="downloadPreviewImage" alt="">
        <video id="downloadPreviewVideo" controls></video>
        <audio id="downloadPreviewAudio" controls></audio>
        <div id="downloadPreviewDocument" class="preview-document"></div>
        <div id="downloadPreviewCaption" class="preview-caption"></div>
    </div>


    <!-- PROGRESS -->

    <div class="progress-header">

        <span id="percent">
            0%
        </span>

        <span id="size">
            0 GB
        </span>

    </div>


    <div class="progress">

        <div
            class="bar"
            id="bar">
        </div>

    </div>


    <!-- INFO -->

    <div class="info-grid">

        <div class="info">

            <div class="info-label">
                دریافت‌شده
            </div>

            <div
                class="info-value"
                id="downloaded">

                0 GB

            </div>

        </div>


        <div class="info">

            <div class="info-label">
                حجم کل
            </div>

            <div
                class="info-value"
                id="total">

                در حال بررسی...

            </div>

        </div>


        <div class="info">

            <div class="info-label">
                سرعت
            </div>

            <div
                class="info-value"
                id="speed">

                —

            </div>

        </div>

    </div>


    <!-- STATUS -->

    <div
        class="status"
        id="status">

        برای شروع دانلود روی دکمه بزنید.

    </div>


    <!-- START -->

    <button
        id="start"
        onclick="startDownload()">

        شروع دانلود

    </button>


    <!-- DONE -->

    <div
        class="done"
        id="done">

        <div class="done-icon">
            ✓
        </div>

        <h2>
            دانلود کامل شد
        </h2>

        <div class="small">

            <?php
            echo htmlspecialchars(
                $filename,
                ENT_QUOTES,
                'UTF-8'
            );
            ?>

            آماده استفاده است.

        </div>

    </div>


    </section>


    <!-- SYSTEM UPLOAD -->

    <section id="upload-section" class="dashboard-section active upload-panel">

        <h2 data-i18n="uploadTitle">آپلود فایل روی هاست</h2>

        <p data-i18n="uploadDescription">ویدئو، تصویر، موسیقی، سند و هر فایل دیگری را تکه‌تکه آپلود کنید.</p>

        <input type="file" id="uploadFile">

        <div id="preview-panel" class="preview-box">
            <img id="previewImage" alt="پیش‌نمایش تصویر">
            <video id="previewVideo" controls></video>
            <audio id="previewAudio" controls></audio>
            <div id="previewDocument" class="preview-document"></div>
            <div id="previewCaption" class="preview-caption"></div>
        </div>

        <input
            type="text"
            id="uploadName"
            placeholder="فقط نام فایل؛ پسوند خودکار اضافه می‌شود">

        <button type="button" id="uploadStart" onclick="startUpload()">
            <span data-i18n="startUpload">شروع آپلود</span>
        </button>

        <div class="upload-progress" id="uploadProgress">
            <div class="upload-progress-bar">
                <div class="upload-progress-fill" id="uploadBar"></div>
            </div>
            <div class="upload-message" id="uploadMessage">در حال آماده‌سازی...</div>
        </div>

        <div class="upload-result" id="uploadResult">
            <input type="text" id="uploadUrl" readonly onclick="this.select()">
            <button type="button" onclick="copyUploadLink()" data-i18n="copyLink">کپی لینک فایل</button>
        </div>

    </section>


    <section id="library-section" class="dashboard-section">
        <div class="library-toolbar">
            <h2 data-i18n="libraryTitle">کتابخانه فایل‌ها</h2>
            <button type="button" onclick="clearLibrary()" data-i18n="clearLibrary">پاک‌کردن فهرست</button>
        </div>
        <div id="libraryPreview" class="library-preview">
            <img id="libraryPreviewImage" alt="">
            <video id="libraryPreviewVideo" controls></video>
            <audio id="libraryPreviewAudio" controls></audio>
            <div id="libraryPreviewCaption" class="library-preview-caption"></div>
        </div>
        <div id="libraryGrid" class="library-grid"></div>
    </section>


    <section id="settings-section" class="dashboard-section settings-panel">
        <h2>تنظیمات</h2>
        <p class="settings-help">همه تنظیمات مقصد فایل، دامنه لینک عمومی و حساب کاربری این‌جاست. اطلاعات یک بار ذخیره می‌شود و دفعه بعد لازم نیست دوباره وارد کنید.</p>

        <div class="settings-card">
            <h3>۱) مقصد ذخیره فایل</h3>
            <div class="settings-choice">
                <label><input type="radio" name="settingsMode" value="direct"> دایرکت: همین هاست، همان پوشه‌ای که اسکریپت در آن است</label>
                <label><input type="radio" name="settingsMode" value="remote"> ارسال به هاست دانلود با FTP / FTPS / SFTP</label>
            </div>
            <div id="settingsRemote" class="settings-remote">
                <label for="settingsProtocol">پروتکل</label>
                <select id="settingsProtocol">
                    <option value="sftp">SFTP</option>
                    <option value="ftp">FTP</option>
                    <option value="ftps">FTPS (FTP با TLS)</option>
                </select>
                <label for="settingsHost">لینک / آدرس سرور</label>
                <input type="text" id="settingsHost" dir="ltr" placeholder="sftp://host.example.com:22" autocomplete="off">
                <label for="settingsPort">پورت (اختیاری)</label>
                <input type="number" id="settingsPort" dir="ltr" min="0" max="65535" placeholder="پیش‌فرض: SFTP ۲۲ و FTP ۲۱">
                <label for="settingsPath">آدرس مقصد روی سرور</label>
                <input type="text" id="settingsPath" dir="ltr" placeholder="domain/myDomain/public_html" autocomplete="off">
                <small>اگر با / شروع شود مسیر مطلق است، وگرنه نسبت به پوشه اصلی کاربر روی سرور مقصد. پوشه‌های ناموجود هنگام ارسال ساخته می‌شوند.</small>
                <label for="settingsUsername">نام کاربری FTP/SFTP</label>
                <input type="text" id="settingsUsername" dir="ltr" autocomplete="off">
                <label for="settingsPassword">رمز عبور FTP/SFTP</label>
                <input type="password" id="settingsPassword" dir="ltr" autocomplete="new-password">
                <small id="settingsPasswordHint"></small>
                <label class="settings-check"><input type="checkbox" id="settingsSslVerify"> بررسی گواهی SSL (برای FTPS)</label>
                <small>فایل بعد از ارسال و تأیید حجم در مقصد، همیشه از این هاست پاک می‌شود. اگر ارسال شکست بخورد، فایل برای تلاش دوباره نگه داشته می‌شود.</small>
            </div>
        </div>

        <div class="settings-card">
            <h3>۲) دامنه و لینک عمومی فایل</h3>
            <label for="settingsDomain">دامنه سایت (اگر خالی بماند خودکار تشخیص داده می‌شود)</label>
            <input type="text" id="settingsDomain" dir="ltr" placeholder="example.com" autocomplete="off">
            <label for="settingsScheme">پروتکل لینک</label>
            <select id="settingsScheme">
                <option value="https">https</option>
                <option value="http">http</option>
            </select>
            <label for="settingsDocroot">نام پوشه ریشه وب (همه چیز تا این پوشه از لینک حذف می‌شود)</label>
            <input type="text" id="settingsDocroot" dir="ltr" placeholder="public_html" autocomplete="off">
            <small id="settingsLinkPreview"></small>
        </div>

        <div class="settings-actions">
            <button type="button" id="settingsSave">ذخیره تنظیمات</button>
            <button type="button" id="settingsTest">تست اتصال</button>
        </div>
        <div id="settingsMessage" class="status" style="display:none"></div>

        <div class="settings-card">
            <h3>۳) حساب کاربری</h3>
            <?php if (!empty($userError)): ?><div class="status error"><?php echo htmlspecialchars($userError, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
            <?php if (!empty($userMessage)): ?><div class="status success"><?php echo htmlspecialchars($userMessage, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
            <form method="post" action="#settings-section">
                <input type="hidden" name="csrf" value="<?php echo htmlspecialchars($_SESSION['csrf'], ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="user_action" value="change_username">
                <label>نام کاربری جدید (فعلی: <?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8'); ?>)</label>
                <input type="text" name="username" dir="ltr" pattern="[A-Za-z0-9_.-]{3,64}" required>
                <button type="submit">تغییر نام کاربری</button>
            </form>
            <form method="post" action="#settings-section">
                <input type="hidden" name="csrf" value="<?php echo htmlspecialchars($_SESSION['csrf'], ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="user_action" value="change_password">
                <label>رمز فعلی</label>
                <input type="password" name="current_password" dir="ltr" autocomplete="current-password" required>
                <label>رمز جدید (حداقل ۸ کاراکتر)</label>
                <input type="password" name="password" dir="ltr" minlength="8" autocomplete="new-password" required>
                <button type="submit">تغییر رمز عبور</button>
            </form>
            <small>تعریف کاربر جدید در بخش «کاربران» است.</small>
        </div>
    </section>
    <section id="users-section" class="dashboard-section">
        <h2>مدیریت کاربران</h2>
        <?php if (!empty($userError)): ?><div class="status error"><?php echo htmlspecialchars($userError, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
        <?php if (!empty($userMessage)): ?><div class="status success"><?php echo htmlspecialchars($userMessage, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
        <form method="post">
            <input type="hidden" name="csrf" value="<?php echo htmlspecialchars($_SESSION['csrf'], ENT_QUOTES, 'UTF-8'); ?>">
            <input type="hidden" name="user_action" value="add">
            <h3>تعریف کاربر</h3>
            <input name="username" placeholder="نام کاربری انگلیسی" pattern="[A-Za-z0-9_.-]{3,64}" required>
            <input type="password" name="password" placeholder="رمز حداقل ۸ کاراکتر" minlength="8" required>
            <button type="submit">افزودن کاربر</button>
        </form>
        <form method="post">
            <input type="hidden" name="csrf" value="<?php echo htmlspecialchars($_SESSION['csrf'], ENT_QUOTES, 'UTF-8'); ?>">
            <input type="hidden" name="user_action" value="change_password">
            <h3>تغییر نام کاربر فعلی</h3>
            <input name="username" placeholder="نام کاربری جدید" pattern="[A-Za-z0-9_.-]{3,64}" required>
            <button type="submit" formaction="" onclick="this.form.user_action.value='change_username'">تغییر نام کاربری</button>
        </form>
        <form method="post">
            <input type="hidden" name="csrf" value="<?php echo htmlspecialchars($_SESSION['csrf'], ENT_QUOTES, 'UTF-8'); ?>">
            <input type="hidden" name="user_action" value="change_password">
            <h3>تغییر رمز کاربر فعلی</h3>
            <input type="password" name="current_password" placeholder="رمز فعلی" autocomplete="current-password" required>
            <input type="password" name="password" placeholder="رمز جدید" minlength="8" autocomplete="new-password" required>
            <button type="submit">تغییر رمز</button>
        </form>
    </section>

    <iframe
        id="worker">
    </iframe>


</div>


<script>

const csrf =
    <?php echo json_encode($_SESSION['csrf']); ?>;


const bar =
    document.getElementById('bar');

const percent =
    document.getElementById('percent');

const downloaded =
    document.getElementById('downloaded');

const total =
    document.getElementById('total');

const speed =
    document.getElementById('speed');

const statusBox =
    document.getElementById('status');

const startButton =
    document.getElementById('start');

const done =
    document.getElementById('done');

const worker =
    document.getElementById('worker');

const step1 =
    document.getElementById('step1');

const step2 =
    document.getElementById('step2');

const step3 =
    document.getElementById('step3');


const remoteDownloadUrl =
    <?php echo json_encode($url, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>;


const remoteDownloadName =
    <?php echo json_encode($filename, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>;


let running = false;


const translations = {
    fa: {
        brand: 'انتقال فایل',
        manage: 'مدیریت فایل',
        uploadNav: 'آپلود از سیستم',
        downloadNav: 'دانلود از لینک',
        libraryNav: 'کتابخانه فایل‌ها',
        language: 'زبان پنل',
        title: 'جادوگر انتقال فایل',
        subtitle: 'مدیریت آپلود و دانلود فایل‌ها',
        uploadTitle: 'آپلود فایل روی هاست',
        uploadDescription: 'ویدئو، تصویر، موسیقی، سند و هر فایل دیگری را تکه‌تکه آپلود کنید.',
        startUpload: 'شروع آپلود',
        copyLink: 'کپی لینک فایل',
        libraryTitle: 'کتابخانه فایل‌ها',
        clearLibrary: 'پاک‌کردن فهرست',
        emptyLibrary: 'هنوز فایلی از این مرورگر آپلود نشده است.',
        open: 'بازکردن',
        remove: 'حذف',
        copied: 'لینک کپی شد.',
        uploadError: 'آپلود ناموفق بود.',
        chooseFile: 'ابتدا یک فایل انتخاب کنید.',
        creatingUpload: 'در حال ساخت نشست آپلود...',
        uploadPartFailed: 'آپلود بخش فایل ناموفق بود.',
        preparingDownload: 'در حال آماده‌سازی دانلود...'
    },
    en: {
        brand: 'File Transfer',
        manage: 'File management',
        uploadNav: 'Upload from computer',
        downloadNav: 'Download from URL',
        libraryNav: 'File library',
        language: 'Panel language',
        title: 'File Transfer Wizard',
        subtitle: 'Manage uploads and host-to-host downloads',
        uploadTitle: 'Upload to this host',
        uploadDescription: 'Upload videos, images, music, documents, and other files in parts.',
        startUpload: 'Start upload',
        copyLink: 'Copy file link',
        libraryTitle: 'File library',
        clearLibrary: 'Clear list',
        emptyLibrary: 'No file has been uploaded from this browser yet.',
        open: 'Open',
        remove: 'Remove',
        copied: 'Link copied.',
        uploadError: 'Upload failed.',
        chooseFile: 'Choose a file first.',
        creatingUpload: 'Creating upload session...',
        uploadPartFailed: 'Upload part failed.',
        preparingDownload: 'Preparing download...'
    }
};


translations.fa.settingsNav = 'تنظیمات مقصد';
translations.en.settingsNav = 'Destination settings';
function getLanguage()
{
    const saved = localStorage.getItem('wizard_language');
    if (saved === 'fa' || saved === 'en') {
        return saved;
    }

    return (navigator.language || '').toLowerCase().startsWith('fa') ? 'fa' : 'en';
}


let currentLanguage = getLanguage();


function tr(key)
{
    return translations[currentLanguage][key] || translations.fa[key] || key;
}


function applyLanguage(language)
{
    currentLanguage = language === 'fa' ? 'fa' : 'en';
    localStorage.setItem('wizard_language', currentLanguage);
    document.documentElement.lang = currentLanguage;
    document.documentElement.dir = currentLanguage === 'fa' ? 'rtl' : 'ltr';

    document.querySelectorAll('[data-i18n]').forEach(function (element) {
        element.textContent = tr(element.dataset.i18n);
    });

    document.getElementById('languageSelect').value = currentLanguage;
    renderLibrary();
}


function showSection(sectionId)
{
    document.querySelectorAll('.dashboard-section').forEach(function (section) {
        section.classList.toggle('active', section.id === sectionId);
    });

    document.querySelectorAll('.dashboard-nav[data-section]').forEach(function (link) {
        link.classList.toggle('active', link.dataset.section === sectionId);
    });
}


document.querySelectorAll('.dashboard-nav[data-section]').forEach(function (link) {
    link.addEventListener('click', function (event) {
        event.preventDefault();
        showSection(link.dataset.section);
        history.replaceState(null, '', link.getAttribute('href'));
    });
});


document.getElementById('languageSelect').addEventListener('change', function () {
    applyLanguage(this.value);
});


let libraryItems = [];


async function libraryRequest(action, values)
{
    const data = new FormData();
    data.append('csrf', csrf);
    data.append('library_action', action);
    Object.keys(values || {}).forEach(function (key) {
        data.append(key, values[key]);
    });
    const response = await fetch('', {method: 'POST', body: data, cache: 'no-store'});
    return response.json();
}


async function saveLibraryItem(item)
{
    await libraryRequest('save', {
        name: item.name,
        url: item.url,
        type: item.type || 'file'
    });
    await loadLibrary();
}


async function loadLibrary()
{
    const data = await libraryRequest('list');
    libraryItems = data.ok && Array.isArray(data.items) ? data.items : [];
    renderLibrary();
}


function renderLibrary()
{
    const grid = document.getElementById('libraryGrid');
    if (!grid) {
        return;
    }

    grid.innerHTML = '';
    const items = libraryItems;
    if (!items.length) {
        const empty = document.createElement('div');
        empty.className = 'library-empty';
        empty.textContent = tr('emptyLibrary');
        grid.appendChild(empty);
        return;
    }

    items.forEach(function (item) {
        const card = document.createElement('article');
        card.className = 'library-card';
        const icon = document.createElement('div');
        icon.className = 'library-icon';
        icon.textContent = item.type && item.type.startsWith('image/') ? '🖼️' :
            item.type && item.type.startsWith('video/') ? '🎬' :
            item.type && item.type.startsWith('audio/') ? '🎵' : '📄';
        const name = document.createElement('div');
        name.className = 'library-name';
        name.textContent = item.name;
        const meta = document.createElement('div');
        meta.className = 'library-meta';
        meta.textContent = formatFileSize(item.size || 0);
        const link = document.createElement('input');
        link.className = 'library-link';
        link.value = item.url;
        link.readOnly = true;
        const actions = document.createElement('div');
        actions.className = 'library-actions';
        const open = document.createElement('button');
        open.type = 'button';
        open.textContent = tr('open');
        open.addEventListener('click', function () {
            previewLibraryItem(item);
        });
        const copy = document.createElement('button');
        copy.type = 'button';
        copy.textContent = tr('copyLink');
        copy.addEventListener('click', function () {
            copyText(item.url);
        });
        const remove = document.createElement('button');
        remove.type = 'button';
        remove.textContent = tr('remove');
        remove.addEventListener('click', function () {
            libraryRequest('remove', {id: item.id}).then(loadLibrary);
        });
        actions.append(open, copy, remove);
        card.append(icon, name, meta, link, actions);
        grid.appendChild(card);
    });
}


function previewLibraryItem(item)
{
    const box = document.getElementById('libraryPreview');
    const image = document.getElementById('libraryPreviewImage');
    const video = document.getElementById('libraryPreviewVideo');
    const audio = document.getElementById('libraryPreviewAudio');
    const caption = document.getElementById('libraryPreviewCaption');
    image.style.display = 'none';
    video.style.display = 'none';
    audio.style.display = 'none';
    if (item.type && item.type.startsWith('image/')) {
        image.src = item.url;
        image.style.display = 'block';
    } else if (item.type && item.type.startsWith('video/')) {
        video.src = item.url;
        video.style.display = 'block';
    } else if (item.type && item.type.startsWith('audio/')) {
        audio.src = item.url;
        audio.style.display = 'block';
    }
    caption.textContent = item.name + ' | ' + item.url;
    box.style.display = 'block';
}


function copyText(value)
{
    if (navigator.clipboard) {
        navigator.clipboard.writeText(value);
    } else {
        const helper = document.createElement('textarea');
        helper.value = value;
        document.body.appendChild(helper);
        helper.select();
        document.execCommand('copy');
        helper.remove();
    }
    document.getElementById('uploadMessage').textContent = tr('copied');
}


function clearLibrary()
{
    Promise.all(libraryItems.map(function (item) {
        return libraryRequest('remove', {id: item.id});
    })).then(loadLibrary);
}


applyLanguage(currentLanguage);
showSection(location.hash === '#download-section' ? 'download-section' :
    location.hash === '#library-section' ? 'library-section' :
    location.hash === '#settings-section' ? 'settings-section' :
    location.hash === '#users-section' ? 'users-section' : 'upload-section');
showRemoteDownloadPreview();
loadLibrary();


const uploadFileInput =
    document.getElementById('uploadFile');


if (uploadFileInput) {
    uploadFileInput.addEventListener('change', showFilePreview);
}


function showFilePreview()
{
    const file = uploadFileInput.files[0];
    const box = document.getElementById('preview-panel');
    const image = document.getElementById('previewImage');
    const video = document.getElementById('previewVideo');
    const audio = document.getElementById('previewAudio');
    const documentBox = document.getElementById('previewDocument');
    const caption = document.getElementById('previewCaption');

    if (!file || !box) {
        return;
    }

    image.style.display = 'none';
    video.style.display = 'none';
    audio.style.display = 'none';
    documentBox.style.display = 'none';

    const source = URL.createObjectURL(file);
    if (file.type.startsWith('image/')) {
        image.src = source;
        image.style.display = 'block';
    } else if (file.type.startsWith('video/')) {
        video.src = source;
        video.style.display = 'block';
    } else if (file.type.startsWith('audio/')) {
        audio.src = source;
        audio.style.display = 'block';
    } else {
        documentBox.innerText = 'فایل انتخاب‌شده پیش‌نمایش مستقیم ندارد.';
        documentBox.style.display = 'block';
    }

    caption.innerText = file.name + ' | ' + formatFileSize(file.size);
    box.style.display = 'block';
}


function formatFileSize(bytes)
{
    if (bytes < 1024 * 1024) {
        return (bytes / 1024).toFixed(1) + ' کیلوبایت';
    }

    return (bytes / 1024 / 1024).toFixed(2) + ' مگابایت';
}


function showRemoteDownloadPreview()
{
    const box = document.getElementById('downloadPreview');
    const image = document.getElementById('downloadPreviewImage');
    const video = document.getElementById('downloadPreviewVideo');
    const audio = document.getElementById('downloadPreviewAudio');
    const documentBox = document.getElementById('downloadPreviewDocument');
    const caption = document.getElementById('downloadPreviewCaption');
    const extension = remoteDownloadName.toLowerCase().split('.').pop();
    const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif'];
    const videoTypes = ['mp4', 'webm', 'ogg', 'mov'];
    const audioTypes = ['mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac'];

    image.style.display = 'none';
    video.style.display = 'none';
    audio.style.display = 'none';
    documentBox.style.display = 'none';

    if (imageTypes.includes(extension)) {
        image.src = remoteDownloadUrl;
        image.style.display = 'block';
    } else if (videoTypes.includes(extension)) {
        video.src = remoteDownloadUrl;
        video.style.display = 'block';
    } else if (audioTypes.includes(extension)) {
        audio.src = remoteDownloadUrl;
        audio.style.display = 'block';
    } else {
        documentBox.innerText = 'این نوع فایل پیش‌نمایش مستقیم ندارد.';
        documentBox.style.display = 'block';
    }

    caption.innerText = remoteDownloadName;
    box.style.display = 'block';
}


/* =========================================================
   FORMAT
========================================================= */

function bytesToGB(bytes)
{
    return (
        bytes /
        1024 /
        1024 /
        1024
    ).toFixed(2) + ' GB';
}


function bytesToSpeed(bytes)
{
    if (!bytes || bytes <= 0) {
        return '—';
    }


    if (
        bytes >=
        1024 *
        1024 *
        1024
    ) {

        return (
            bytes /
            1024 /
            1024 /
            1024
        ).toFixed(2) +
        ' GB/s';
    }


    return (
        bytes /
        1024 /
        1024
    ).toFixed(1) +
    ' MB/s';
}


/* =========================================================
   CHUNKED UPLOAD WORKER
========================================================= */

async function startUpload()
{
    const fileInput = document.getElementById('uploadFile');
    const nameInput = document.getElementById('uploadName');
    const uploadButton = document.getElementById('uploadStart');
    const progressBox = document.getElementById('uploadProgress');
    const progressBar = document.getElementById('uploadBar');
    const message = document.getElementById('uploadMessage');
    const result = document.getElementById('uploadResult');
    const urlBox = document.getElementById('uploadUrl');
    const file = fileInput.files[0];

    if (!file) {
        message.innerText = tr('chooseFile');
        progressBox.style.display = 'block';
        return;
    }

    const filename = nameInput.value.trim() || file.name;
    const chunkSize = 1 * 1024 * 1024;
    const totalChunks = Math.max(1, Math.ceil(file.size / chunkSize));

    uploadButton.disabled = true;
    progressBox.style.display = 'block';
    result.style.display = 'none';
    progressBar.style.width = '0%';
    message.innerText = tr('creatingUpload');

    try {
        const initData = new FormData();
        initData.append('csrf', csrf);
        initData.append('upload_action', 'init');
        initData.append('filename', filename);
        initData.append('original_filename', file.name);
        initData.append('size', file.size);

        const initResponse = await fetch('', {
            method: 'POST',
            body: initData,
            cache: 'no-store'
        });
        const init = await initResponse.json();

        if (!init.ok) {
            throw new Error(init.error || 'ساخت نشست آپلود ممکن نیست.');
        }

        for (let index = 0; index < totalChunks; index++) {
            const start = index * chunkSize;
            const chunk = file.slice(start, start + chunkSize);
            const chunkData = new FormData();
                chunkData.append('csrf', csrf);
            chunkData.append('upload_action', 'chunk');
            chunkData.append('upload_id', init.upload_id);
            chunkData.append('chunk_index', index);
            chunkData.append('total_chunks', totalChunks);
            chunkData.append('chunk', chunk, filename);

            message.innerText = 'در حال آپلود بخش ' + (index + 1) + ' از ' + totalChunks + '...';
            const chunkResponse = await fetch('', {
                method: 'POST',
                body: chunkData,
                cache: 'no-store'
            });
            const chunkResult = await chunkResponse.json();

            if (!chunkResult.ok) {
                throw new Error(chunkResult.error || tr('uploadPartFailed'));
            }

            progressBar.style.width = ((index + 1) / totalChunks * 100).toFixed(2) + '%';
        }

        message.innerText = 'در حال نهایی‌سازی فایل...';
        const finishData = new FormData();
        finishData.append('csrf', csrf);
        finishData.append('upload_action', 'finish');
        finishData.append('upload_id', init.upload_id);
        const finishResponse = await fetch('', {
            method: 'POST',
            body: finishData,
            cache: 'no-store'
        });
        const finished = await finishResponse.json();

        if (!finished.ok) {
            throw new Error(finished.error || 'نهایی‌سازی فایل ممکن نیست.');
        }

        if (finished.destination && !finished.url) {
            message.innerText = 'به مقصد FTP/SFTP منتقل شد: ' + finished.destination;
            return;
        }

        urlBox.value = finished.url;
        result.style.display = 'block';
        saveLibraryItem({
            name: finished.filename || filename,
            url: finished.url,
            size: Number(finished.size || file.size),
            type: file.type || 'application/octet-stream',
            created: Date.now()
        });
        message.innerText = 'آپلود با موفقیت انجام شد.';
    } catch (error) {
        message.innerText = error.message || tr('uploadError');
    } finally {
        uploadButton.disabled = false;
    }
}


async function copyUploadLink()
{
    const urlBox = document.getElementById('uploadUrl');
    copyText(urlBox.value);
    document.getElementById('uploadMessage').innerText = 'لینک کپی شد.';
}


/* =========================================================
   UPDATE STATUS
========================================================= */

async function updateStatus()
{
    try {

        const response =
            await fetch(
                '?status=1&_=' +
                Date.now(),
                {
                    cache:
                        'no-store'
                }
            );


        const data =
            await response.json();


        const current =
            Number(
                data.downloaded ||
                0
            );


        const remoteTotal =
            Number(
                data.total ||
                0
            );


        /*
         * Downloaded
         */

        downloaded.innerText =
            bytesToGB(
                current
            );


        /*
         * Total
         */

        if (
            remoteTotal > 0
        ) {

            total.innerText =
                bytesToGB(
                    remoteTotal
                );


            const p =
                Math.min(
                    100,
                    (
                        current /
                        remoteTotal
                    ) *
                    100
                );


            bar.style.width =
                p.toFixed(2) +
                '%';


            percent.innerText =
                p.toFixed(2) +
                '%';
        }


        /*
         * Speed
         */

        speed.innerText =
            bytesToSpeed(
                Number(
                    data.speed ||
                    0
                )
            );


        /*
         * Message
         */

        if (
            data.message
        ) {

            statusBox.innerText =
                data.message;
        }


        /*
         * Prepared
         */

        if (
            data.status ===
            'prepared'
        ) {

            step1.classList.add(
                'done'
            );
        }


        /*
         * Downloading
         */

        if (
            data.status ===
                'downloading'
            ||
            data.status ===
                'uploading'
            ||
            data.status ===
                'retrying'
        ) {

            step1.classList.add(
                'done'
            );

            step2.classList.add(
                'active'
            );
        }


        /*
         * Complete
         */

        if (
            data.status ===
            'complete'
        ) {

            running = false;


            bar.style.width =
                '100%';

            percent.innerText =
                '100%';

            speed.innerText =
                '—';


            statusBox.innerText =
                data.destination
                ? ('انتقال کامل شد: ' + data.destination)
                : 'دانلود با موفقیت کامل شد.';
            if (data.public_url && !window.publicLinkShown) {
                window.publicLinkShown = true;
                const linkBox = document.createElement('div');
                linkBox.className = 'small';
                const anchor = document.createElement('a');
                anchor.href = data.public_url;
                anchor.target = '_blank';
                anchor.rel = 'noopener';
                anchor.textContent = data.public_url;
                anchor.style.wordBreak = 'break-all';
                linkBox.append('لینک فایل: ', anchor);
                done.appendChild(linkBox);
                if (typeof saveLibraryItem === 'function') {
                    saveLibraryItem({name: remoteDownloadName, url: data.public_url, type: 'application/octet-stream'});
                }
            }


            step1.classList.add(
                'done'
            );

            step2.classList.add(
                'done'
            );

            step3.classList.add(
                'active'
            );


            startButton.style.display =
                'none';


            done.style.display =
                'block';
        }


        /*
         * Error
         */

        if (
            data.status ===
            'error'
        ) {

            running = false;


            startButton.disabled =
                false;


            startButton.innerText =
                'تلاش دوباره برای دانلود';


            statusBox.innerText =
                data.message ||
                'Download error.';
        }

    } catch (e) {

        console.log(e);
    }
}


/* =========================================================
   START DOWNLOAD
========================================================= */

async function startDownload()
{
    if (running) {
        return;
    }


    running = true;


    startButton.disabled =
        true;


    startButton.innerText =
        tr('preparingDownload');


    statusBox.innerText =
        'در حال بررسی فایل مقصد...';


    try {

        /*
         * Prepare
         */

        const response =
            await fetch(
                '?prepare=1&_=' +
                Date.now(),
                {
                    cache:
                        'no-store'
                }
            );


        const data =
            await response.json();


        /*
         * Prepare error
         */

        if (!data.ok) {

            running = false;


            startButton.disabled =
                false;


            startButton.innerText =
                'تلاش دوباره برای دانلود';


            statusBox.innerText =
                data.error ||
                'آماده‌سازی ناموفق بود.';


            return;
        }


        /*
         * Total
         */

        total.innerText =
            bytesToGB(
                Number(
                    data.total ||
                    0
                )
            );


        /*
         * Existing .part
         */

        downloaded.innerText =
            bytesToGB(
                Number(
                    data.downloaded ||
                    0
                )
            );


        /*
         * Already complete
         */

        if (
            data.complete
        ) {

            await updateStatus();

            return;
        }


        /*
         * Message
         */

        statusBox.innerText =
            data.downloaded > 0
            ? 'ادامه از فایل نیمه‌کاره...'
            : 'شروع دانلود...';


        /*
         * Steps
         */

        step1.classList.remove(
            'active'
        );

        step1.classList.add(
            'done'
        );

        step2.classList.add(
            'active'
        );


        /*
         * Start REAL download
         *
         * iframe مخفی است و درخواست سنگین
         * را نگه می‌دارد.
         */

        const downloadForm = document.createElement('form');
        downloadForm.method = 'post';
        downloadForm.action = '';
        downloadForm.target = 'download-worker';
        downloadForm.style.display = 'none';
        const downloadAction = document.createElement('input');
        downloadAction.name = 'download';
        downloadAction.value = '1';
        const downloadCsrf = document.createElement('input');
        downloadCsrf.name = 'csrf';
        downloadCsrf.value = csrf;
        downloadForm.append(downloadAction, downloadCsrf);
        worker.name = 'download-worker';
        document.body.appendChild(downloadForm);
        downloadForm.submit();


        startButton.innerText =
            'در حال دانلود...';

    } catch (e) {

        console.log(e);


        running = false;


        startButton.disabled =
            false;


        startButton.innerText =
            'تلاش دوباره برای دانلود';


        statusBox.innerText =
            'اجرای دانلودر ممکن نیست.';
    }
}


/* =========================================================
   DESTINATION SETTINGS
========================================================= */
const settingsMessage = document.getElementById('settingsMessage');
const settingsRemote = document.getElementById('settingsRemote');
const settingsModeInputs = document.querySelectorAll('input[name="settingsMode"]');
function settingsShow(text, type)
{
    settingsMessage.textContent = text;
    settingsMessage.className = 'status ' + (type || '');
    settingsMessage.style.display = text ? 'block' : 'none';
    if (text && settingsMessage.scrollIntoView) {
        settingsMessage.scrollIntoView({behavior: 'smooth', block: 'nearest'});
    }
}
function settingsCurrentMode()
{
    const checked = document.querySelector('input[name="settingsMode"]:checked');
    return checked ? checked.value : 'direct';
}
function settingsUpdateVisibility()
{
    settingsRemote.classList.toggle('active', settingsCurrentMode() === 'remote');
}
function settingsShowPreview(data)
{
    const box = document.getElementById('settingsLinkPreview');
    if (!box) {
        return;
    }
    const parts = [];
    if (data.detected_domain) {
        parts.push('دامنه تشخیص‌داده‌شده: ' + data.detected_domain);
    }
    if (data.public_url_example) {
        parts.push('نمونه لینک فایل: ' + data.public_url_example);
    } else {
        parts.push('هنوز دامنه‌ای مشخص نیست؛ دامنه را وارد کنید تا لینک عمومی ساخته شود.');
    }
    box.textContent = parts.join(' | ');
}
async function settingsRequest(action, values)
{
    const data = new FormData();
    data.append('csrf', csrf);
    data.append('settings_action', action);
    Object.keys(values || {}).forEach(function (key) {
        data.append(key, values[key]);
    });
    const response = await fetch('', {method: 'POST', body: data, cache: 'no-store', credentials: 'same-origin'});
    const text = await response.text();
    try {
        return JSON.parse(text);
    } catch (e) {
        return {
            ok: false,
            error: 'پاسخ نامعتبر از سرور (HTTP ' + response.status + '): ' +
                text.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 200)
        };
    }
}
function settingsCollect()
{
    return {
        mode: settingsCurrentMode(),
        protocol: document.getElementById('settingsProtocol').value,
        host: document.getElementById('settingsHost').value,
        port: document.getElementById('settingsPort').value,
        remote_path: document.getElementById('settingsPath').value,
        username: document.getElementById('settingsUsername').value,
        password: document.getElementById('settingsPassword').value,
        ssl_verify: document.getElementById('settingsSslVerify').checked ? '1' : '0',
        public_domain: document.getElementById('settingsDomain').value,
        public_scheme: document.getElementById('settingsScheme').value,
        docroot: document.getElementById('settingsDocroot').value
    };
}
async function settingsLoad()
{
    try {
        const data = await settingsRequest('get');
        if (!data.ok) {
            return;
        }
        const s = data.settings;
        settingsModeInputs.forEach(function (input) {
            input.checked = input.value === s.mode;
        });
        document.getElementById('settingsProtocol').value = s.protocol;
        document.getElementById('settingsHost').value = s.host;
        document.getElementById('settingsPort').value = s.port > 0 ? s.port : '';
        document.getElementById('settingsPath').value = s.remote_path;
        document.getElementById('settingsUsername').value = s.username;
        document.getElementById('settingsPassword').value = '';
        document.getElementById('settingsSslVerify').checked = !!s.ssl_verify;
        document.getElementById('settingsDomain').value = s.public_domain || '';
        document.getElementById('settingsScheme').value = s.public_scheme || 'https';
        document.getElementById('settingsDocroot').value = s.docroot || 'public_html';
        document.getElementById('settingsPasswordHint').textContent = s.has_password
            ? 'رمز ذخیره شده است. فقط برای تغییر آن، رمز جدید را وارد کنید.'
            : (s.crypto_available ? '' : 'هشدار: افزونه openssl برای ذخیره امن رمز فعال نیست.');
        if (!s.sftp_available) {
            settingsShow('هشدار: cURL این هاست از SFTP پشتیبانی نمی‌کند؛ از FTP یا FTPS استفاده کنید.', 'error');
        }
        settingsShowPreview(s);
        settingsUpdateVisibility();
    } catch (e) {
        console.log(e);
    }
}
async function settingsSubmit(action)
{
    const saveButton = document.getElementById('settingsSave');
    const testButton = document.getElementById('settingsTest');
    saveButton.disabled = true;
    testButton.disabled = true;
    settingsShow(action === 'test' ? 'در حال تست اتصال...' : 'در حال ذخیره...', '');
    try {
        const data = await settingsRequest(action, settingsCollect());
        if (!data.ok) {
            settingsShow(data.error || 'عملیات ناموفق بود.', 'error');
        } else if (action === 'test') {
            settingsShow(data.warning ? data.warning : 'اتصال و ورود با موفقیت انجام شد.', 'success');
            settingsShowPreview(data);
        } else {
            await settingsLoad();
            settingsShow('تنظیمات ذخیره شد.', 'success');
        }
    } catch (e) {
        settingsShow('ارتباط با سرور برقرار نشد. صفحه را تازه کنید و دوباره تلاش کنید.', 'error');
    } finally {
        saveButton.disabled = false;
        testButton.disabled = false;
    }
}
settingsModeInputs.forEach(function (input) {
    input.addEventListener('change', settingsUpdateVisibility);
});
document.getElementById('settingsSave').addEventListener('click', function () {
    settingsSubmit('save');
});
document.getElementById('settingsTest').addEventListener('click', function () {
    settingsSubmit('test');
});
settingsLoad();

/* =========================================================
   LIVE STATUS
========================================================= */

setInterval(
    updateStatus,
    1000
);


/*
 * وضعیت اولیه
 */

updateStatus();

</script>

</main>

</div>

</body>

</html>