<?php

//  MP3-Player 1.1
//  © S.G.Schiffer 2025 - sgs-visual.de
//
// Dieses Script darf nur mit der Quellenangabe (sgs-visual.de) genutzt werden!
// Dieses Script darf nicht auf anderen Domains angeboten oder verkauft werden!
// 
// Ich übernehme keine Haftung für die Funktionalität meines Scriptes oder Korrektheit der ausgegeben Daten.
// Es gibt keinen Anspruch auf Schadens- oder Ersatzansprüche durch die Nutzung des Scriptes.
// Es gibt keinen Support für Probleme, die bei der Anpassung des Scriptes entstehen können.
// -----------------------------------------------------------------------

session_start();
$password = "passwort"; // Ersetzen Sie hier das "passwort" in Ihr eigenes Passwort. Groß- Kleinschreibung beachten.

// MP3 Player V. 1.1 - © S.G.Schiffer 2025 - sgs-visual.de
// Bitte beachten Sie die Informationen Nutzungshinweise und Uhrheberrecht im Ordner ''docs''

// Password validation
if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
        if ($_POST['password'] === $password) {
            $_SESSION['authenticated'] = true;
        } else {
            $error = "Falsches Passwort!";
        }
    }

    if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
        ?>
        <!DOCTYPE html>
        <html lang="de">
        <head>
            <meta charset="UTF-8">
            <title>MP3 Player V. 1.1 - Upload & Titel-Verwaltung Login</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background-color: #333;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    height: 100vh;
                    margin: 0;
                }
                .container {
                    width: 600px;
                    background-color: #333;
                    color: #FFF;
                    padding: 20px;
                    border-radius: 5px;
                    text-align: center;
                }
                h1 {
                    font-size: 16px;
                    font-weight: 600;
                }
                p {
                    font-size: 14px;
                }
                .error {
                    color: #ff0000;
                }
                .login-btn {
                    background-color: #ff0000;
                    color: #fff;
                    border: none;
                    padding: 8px 15px;
                    border-radius: 4px;
                    cursor: pointer;
                    font-size: 14px;
                    display: inline-flex;
                    align-items: center;
                }
                .login-btn img {
                    margin-right: 5px;
                }
                input[type="password"] {
                    padding: 8px;
                    width: 200px;
                    margin-right: 10px;
                }
            </style>
        </head>
        <body>
            <div class="container">
                 <img src="icons/mp3_player_icon.png" width="80" height="89" alt="Login"><br>
                <h1>MP3 Player V. 1.1 - Upload & Titel-Verwaltung<br>Login</h1>
                <?php if (isset($error)): ?>
                    <p class="error"><?php echo $error; ?></p>
                <?php endif; ?>
                <form method="post">
                    <input type="password" name="password" placeholder="Passwort eingeben">
                    <button type="submit" class="login-btn">
                        <img src="icons/login.png" width="16" height="16" alt="Login">
                        Login
                    </button>
        <p style='font-size: 9px;text-align: center;'>
           &copy; S.G.Schiffer 2025 -
           <a style='text-decoration:none;color:#FF0000;font-weight:600;' href='https://www.sgs-visual.de' target='_blank'>sgs-visual.de</a>
       </p>

                </form>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
}

// Handle file upload
$message = '';
$messageColor = '';

// Check if this is an AJAX request
$isAjax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['musicFile'])) {
    $targetDir = "sounds/";
    $fileName = basename($_FILES["musicFile"]["name"]);
    $targetFile = $targetDir . $fileName;
    $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
    $maxFileSize = 10 * 1024 * 1024; // 10MB

    // Check if file is mp3 or ogg
    if ($fileType != "mp3" && $fileType != "ogg") {
        $message = "Nur MP3 und OGG Dateien sind erlaubt.";
        $messageColor = "red";
    }
    // Check file size
    elseif ($_FILES["musicFile"]["size"] > $maxFileSize) {
        $message = "Die Datei ist zu groß (max 10MB).";
        $messageColor = "red";
    }
    // Upload file
    else {
        if (move_uploaded_file($_FILES["musicFile"]["tmp_name"], $targetFile)) {
            $message = "Die Datei $fileName wurde erfolgreich hochgeladen.";
            $messageColor = "lightgreen";

            // For AJAX requests, return success status
            if ($isAjax) {
                echo json_encode(['status' => 'success']);
                exit;
            }
        } else {
            $message = "Die Datei $fileName konnte nicht hochgeladen werden.";
            $messageColor = "red";

            // For AJAX requests, return error status
            if ($isAjax) {
                echo json_encode(['status' => 'error']);
                exit;
            }
        }
    }

    // If not an AJAX request, but still a POST request that we've handled,
    // redirect to avoid form resubmission issues
    if (!$isAjax) {
        header('Location: ' . $_SERVER['PHP_SELF'] . '?message=' . urlencode($message) . '&color=' . $messageColor);
        exit;
    }
}

// Handle message from redirect
if (isset($_GET['message']) && isset($_GET['color'])) {
    $message = $_GET['message'];
    $messageColor = $_GET['color'];
}
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>MP3 Player V. 1.1 - Upload & Titel-Verwaltung</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #333;
            display: flex;
            justify-content: center;
            padding: 30px 0;
            margin: 0;
        }
        .container {
            width: 600px;
            background-color: #333;
            color: #FFF;
            padding: 20px;
            border-radius: 5px;
        }
        h1 {
            font-size: 16px;
            font-weight: 600;
            text-align: center;
        }
        p {
            font-size: 14px;
        }
        .message {
            font-size: 18px;
            font-weight: 600;
            margin: 15px 0;
            text-align: center;
        }
        .success {
            color: #4CAF50;
        }
        .error {
            color: #ff0000;
        }
        .btn {
            background-color: #ff0000;
            color: #fff;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            display: inline-flex;
            align-items: center;
            text-decoration: none;
            margin: 10px 0;
        }
        .btn img {
            margin-right: 5px;
        }
        .button-group {
            display: flex;
            justify-content: center;
            margin-top: 30px;
            gap: 30px;
        }
        #uploadForm {
            text-align: center;
            margin-top: 20px;
        }
        #loadingAnimation {
            display: none;
            text-align: center;
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>MP3 Player V. 1.1 - Upload & Titel-Verwaltung</h1>

        <?php if ($message): ?>
            <p class="message" style="color: <?php echo $messageColor; ?>;"><?php echo $message; ?></p>
        <?php endif; ?>

        <form id="uploadForm" enctype="multipart/form-data" method="post">
            <input type="file" id="musicFile" name="musicFile" accept=".mp3,.ogg">
            <div id="loadingAnimation">
                <img src="icons/datei_laden.gif" alt="Datei wird hochgeladen...">
            </div>
            <button type="submit" class="btn" id="uploadBtn">
                <img src="icons/upload.png" width="16" height="16" alt="Hochladen">
                Hochladen
            </button>
        </form>

        <div class="button-group">
            <a href="titel_bearbeiten.php" class="btn">
                Titel bearbeiten
            </a>
            <a href="?logout=1" class="btn">
                <img src="icons/logout.png" width="16" height="16" alt="Logout">
                Logout
            </a>
        </div>
    </div>

    <script>
        document.getElementById('uploadForm').addEventListener('submit', function(e) {
            var fileInput = document.getElementById('musicFile');
            if (fileInput.files.length > 0) {
                // Prevent the default form submission
                e.preventDefault();

                var loadingAnimation = document.getElementById('loadingAnimation');
                var uploadBtn = document.getElementById('uploadBtn');

                // Show loading animation and disable upload button
                loadingAnimation.style.display = 'block';
                uploadBtn.disabled = true;

                // Create and configure the AJAX request
                var xhr = new XMLHttpRequest();
                var formData = new FormData(this);

                // Add a header to identify this as an AJAX request
                xhr.open('POST', window.location.href);
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

                // Handle the completed request
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            if (response.status === 'success') {
                                // Use proper GET redirect instead of reload
                                window.location.href = window.location.pathname + '?message=' +
                                    encodeURIComponent('Die Datei wurde erfolgreich hochgeladen.') +
                                    '&color=lightgreen';
                            } else {
                                // Error handling
                                loadingAnimation.style.display = 'none';
                                uploadBtn.disabled = false;
                                alert('Fehler beim Upload. Bitte versuchen Sie es erneut.');
                            }
                        } catch (e) {
                            // Redirect to the page without query params if response is not JSON
                            window.location.href = window.location.pathname;
                        }
                    }
                };

                // Handle errors
                xhr.onerror = function() {
                    loadingAnimation.style.display = 'none';
                    uploadBtn.disabled = false;
                    alert('Fehler beim Upload. Bitte versuchen Sie es erneut.');
                };

                // Send the form data
                xhr.send(formData);
            }
        });
    </script>
</body>
</html>

<?php
// Logout functionality
if (isset($_GET['logout'])) {
    session_unset();
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}
?>