oazaSrdceWeb / admin / mainphoto.php
mainphoto.php
Raw
<?php

/**
 * @file mainphoto.php
 * @brief Správa úvodních fotografií webu.
 *
 * Tento skript umožňuje administrátorovi:
 *  - Zobrazit všechny nahrané úvodní fotky.
 *  - Nastavit jednu z fotek jako hlavní (úvodní).
 *  - Smazat existující fotku (včetně fyzického souboru na serveru).
 *  - Nahrát novou fotku a zvolit, zda ji nastavit jako aktuální.
 * Přístup je povolen pouze přihlášeným uživatelům.
 */

include '../db_connection.php'; ///< Připojení k databázi.
$conn->set_charset("utf8mb4");
session_start();

/**
 * Kontrola, zda je uživatel přihlášen.
 * Pokud není, přesměruje na přihlašovací stránku.
 */
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: login.php');
    exit();
}

?>
<!DOCTYPE html>
<html lang="cs">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nastavení úvodní fotky</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="../admin.css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css" rel="stylesheet">
    <style>
        #cropContainer {
            position: relative;
            width: 100%;
            height: 0;
            padding-bottom: 56.25%;
            /* 16:9 aspect ratio */
            display: none;
        }

        #image {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .photo-container {
            position: relative;
            display: inline-block;
            margin: 10px;
        }

        .delete-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 50%;
            width: 25px;
            height: 25px;
            cursor: pointer;
            font-size: 14px;
            line-height: 1;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .delete-btn:hover {
            background: #c82333;
        }
    </style>
    <script>
        /**
         * Vyprázdní pole pro výběr souboru po úspěšném nahrání.
         */
        function refreshFileInput() {
            document.getElementById('fileToUpload').value = '';
        }

        /**
         * Zpracuje odpověď serveru po nahrání fotky.
         * @param {Object} response - Odpověď serveru ve formátu JSON.
         */

        function handleUploadResponse(response) {
            if (response.success) {
                refreshFileInput();
                // Zobrazí úspěšnou hlášku a obnoví stránku
                alert('Úspěch: ' + (response.message || 'Obrázek byl úspěšně nahrán.'));
                window.location.href = 'mainphoto.php?status=success';
            } else {
                alert('Chyba: ' + response.error);
            }
        }

        /**
         * Odeslání formuláře pro nahrání nové fotky AJAXem.
         * Provádí základní validaci a pošle data na server.
         */
        function uploadFile(event) {
            event.preventDefault();

            var fileInput = document.getElementById('fileToUpload');
            var photoName = document.getElementById('photoName');
            var newRadio = document.querySelector('input[name="new"]:checked');

            if (!fileInput.files[0]) {
                alert('Vyberte prosím soubor.');
                return;
            }

            if (!photoName.value.trim()) {
                alert('Zadejte prosím název fotky.');
                return;
            }

            if (!newRadio) {
                alert('Vyberte prosím, zda nastavit jako aktuální.');
                return;
            }

            // Změna stavu tlačítka na "Nahrávám..."
            var submitBtn = document.querySelector('#uploadForm input[type="submit"]');
            var originalText = submitBtn.value;
            submitBtn.value = 'Nahrávám...';
            submitBtn.disabled = true;

            var formData = new FormData(document.getElementById('uploadForm'));
            fetch('upload.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    submitBtn.value = originalText;
                    submitBtn.disabled = false;
                    handleUploadResponse(data);
                })
                .catch(error => {
                    console.error('Error:', error);
                    submitBtn.value = originalText;
                    submitBtn.disabled = false;
                    alert('Došlo k neočekávané chybě při nahrávání.');
                });
        }
        /**
         * Odeslání formuláře pro změnu hlavní fotky AJAXem.
         * Po úspěchu obnoví stránku.
         */
        function updateMainPhoto(event) {
            event.preventDefault();
            var selectedPhoto = document.querySelector('input[name="photo"]:checked');
            if (!selectedPhoto) {
                alert('Vyberte prosím fotku.');
                return;
            }
            fetch('update_mainphoto.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        photo_link: selectedPhoto.value
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.href = 'mainphoto.php?status=updated';
                    } else {
                        alert('Error: ' + data.error);
                    }
                })
                .catch(error => console.error('Error:', error));
        }

        /**
         * Smazání fotky AJAXem po potvrzení uživatelem.
         * @param {number} photoId - ID fotky v databázi.
         * @param {string} photoName - Název fotky pro potvrzovací dialog.
         */
        function deletePhoto(photoId, photoName) {
            if (confirm('Opravdu chcete smazat fotku "' + photoName + '"? Tato akce je nevratná.')) {
                fetch('delete_photo.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            photo_id: photoId
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            window.location.href = 'mainphoto.php?status=deleted';
                        } else {
                            alert('Error: ' + data.error);
                        }
                    })
                    .catch(error => console.error('Error:', error));
            }
        }
    </script>
</head>

<body>
    <div class="container">
        <a href="../admin.php" class="backbtn">Zpět na panel</a>
        <?php if (isset($_GET['status']) && $_GET['status'] == 'success'): ?>
            <div class="alert alert-success" role="alert">
                Obrázek se podařilo nahrát.
            </div>
        <?php endif; ?>
        <?php if (isset($_GET['status']) && $_GET['status'] == 'updated'): ?>
            <div class="alert alert-success" role="alert">
                Úvodní fotka byla úspěšně aktualizována.
            </div>
        <?php endif; ?>
        <?php if (isset($_GET['status']) && $_GET['status'] == 'deleted'): ?>
            <div class="alert alert-success" role="alert">
                Fotka byla úspěšně smazána.
            </div>
        <?php endif; ?>
        <div class="row justify-content-center">
            <div class="col-8">
                <h2>Změna úvodní fotky</h2>
            </div>
            <div class="col-8">
                <form id="editForm" onsubmit="updateMainPhoto(event)">
                    <?php
                    // Výpis všech fotek z databáze s možností nastavit jako hlavní nebo smazat
                    include '../db_connection.php'; ///< Připojení k databázi.
                    $conn->set_charset("utf8mb4");
                    $sql = "SELECT * FROM mainphoto";
                    $result = $conn->query($sql);
                    if ($result->num_rows > 0) {
                        while ($row = $result->fetch_assoc()) {
                            echo '<div class="photo-container">';
                            echo '<img src="../' . $row["photo_link"] . '" alt="" width="250px">';
                            echo '<button type="button" class="delete-btn" onclick="deletePhoto(' . $row["id"] . ', \'' . htmlspecialchars($row["name"], ENT_QUOTES) . '\')" title="Smazat fotku">×</button>';
                            echo '</div>';
                            echo '<br>';
                            echo '<label for="photo_' . $row["id"] . '"><b>' . $row["name"] . '</b></label>';
                            echo '<input type="radio" id="photo_' . $row["id"] . '" name="photo" value="' . $row["photo_link"] . '"';
                            if ($row["ismain"] == 1) {
                                echo ' checked';
                            }
                            echo '> <br><br>';
                        }
                    }
                    ?>
                    <input type="submit" name="" id="" class="btn btn-primary mt-3" value="Upravit">
                </form>
            </div>
        </div>
    </div>
    <div class="spacer50"></div>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-8">
                <h2>Přidat novou možnost</h2>
            </div>
            <div class="col-8">
                <form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data" onsubmit="uploadFile(event)">
                    <h5>Nastavit jako aktuální:</h5>
                    <label for="yes">Ano</label>
                    <input type="radio" name="new" value="1" id="yes">
                    <br>

                    <label for="no">Ne</label>
                    <input type="radio" name="new" value="2" id="no">
                    <br>
                    <label for="photoName">Název</label>
                    <input type="text" name="photoName" id="photoName"> <br>
                    <input type="file" name="fileToUpload" id="fileToUpload" accept="image/*" class="mt-2"> <br>
                    <input type="submit" value="Nahrát" name="submit" class="btn btn-primary mt-3">
                </form>
            </div>
        </div>
    </div>

</body>

</html>