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

<head>
    <meta charset="UTF-8">
    <title><?= isset($player) ? 'Editar Jugador' : 'Crear Jugador' ?></title>
    <link rel="stylesheet" href="../public/css/style.css">
</head>

<body>
    <div class="wb">
        <div class="head">
            <div class="tittle"><?= isset($player) ? 'Editar Jugador' : 'Crear Jugador' ?></div>
            <a href="../public/player.php">
                <div class="pic iClose"></div>
            </a>
        </div>

        <?php if (isset($player)): ?>
            <div class="picSection" id="picSection">
                <div class="player_Pic img iUser" id="player_Pic" style="background-image: url('../../app/style/img/user/<?= isset($player['pic']) ? 'player_' . $player['pic'] . '.webp' : 'user.png' ?>');"></div>
                <div class="buttons">
                    <div id="takePhoto" class="button iCamera img"></div>
                    <div id="uploadPhoto" class="button iUpImg img"></div>
                </div>
            </div>
        <?php endif; ?>
        <form action="../public/player.php?action=<?= isset($player) ? 'update&id='. htmlspecialchars($player['id']) : 'store' ?>" method="POST" id="mainForm" class="form">
            <div class="formItem">
                <input type="text" id="pNombre" name="pNombre" required value="<?= $player['pNombre'] ?? '' ?>" class="formInput" autocomplete="off">
                <label for="pNombre" class="formLabel">Primer Nombre</label>
            </div>

            <div class="formItem">
                <input type="text" id="sNombre" name="sNombre" value="<?= $player['sNombre'] ?? '' ?>" class="formInput" autocomplete="off">
                <label for="sNombre" class="formLabel">Segundo Nombre</label>
            </div>

            <div class="formItem">
                <input type="text" id="pApellido" name="pApellido" required value="<?= $player['pApellido'] ?? '' ?>" class="formInput" autocomplete="off">
                <label for="pApellido" class="formLabel">Apellido Paterno</label>
            </div>

            <div class="formItem">
                <input type="text" id="mApellido" name="mApellido" value="<?= $player['mApellido'] ?? '' ?>" class="formInput" autocomplete="off">
                <label for="mApellido" class="formLabel">Apellido Materno</label>
            </div>

            <div class="formItem">
                <input type="text" id="categoria" name="categoria" required value="<?= $player['categoria'] ?? '' ?>" class="formInput">
                <label for="categoria" class="formLabel">Categoría</label>
            </div>

            <div class="formItem">
                <input type="text" id="instagram" name="instagram" value="<?= $player['instagram'] ?? '' ?>" class="formInput">
                <label for="instagram" class="formLabel">Instagram</label>
            </div>

            <?php if (isset($player)): ?>
                <input type="hidden" name="id" value="<?= $player['id'] ?>" class="formInput">
            <?php endif; ?>

            <button class="button-85" role="button" value="Submit" type="submit">Guardar</button>
        </form>

        <a href="../public/player.php" class="button">Volver a la lista</a>
    </div>

    <?php if (isset($player)): ?>
        <script>
            document.addEventListener('DOMContentLoaded', () => {
                const playerPic = document.getElementById('player_Pic');
                const takePhotoButton = document.getElementById('takePhoto');
                const uploadPhotoButton = document.getElementById('uploadPhoto');
                const picSection = document.getElementById('picSection');

                let stream;
                let cameraActive = false;
                const videoContainer = document.createElement('div');
                videoContainer.className = 'video-container';
                videoContainer.innerHTML = `
                <video id="video" autoplay class="video"></video>
                <canvas id="canvas" style="display:none;"></canvas>
                <div class="buttons">
                    <button id="capture" class="button">Capturar Imagen</button>
                </div>
            `;

                function stopStream() {
                    if (stream) {
                        stream.getTracks().forEach(track => track.stop());
                    }
                    cameraActive = false;
                }

                // Tomar una foto con la cámara
                takePhotoButton.addEventListener('click', () => {
                    if (cameraActive) {
                        stopStream();
                        videoContainer.remove();
                        cameraActive = false;
                        return;
                    }

                    cameraActive = true;
                    picSection.appendChild(videoContainer);
                    navigator.mediaDevices.getUserMedia({
                            video: true
                        })
                        .then((mediaStream) => {
                            stream = mediaStream;
                            document.getElementById('video').srcObject = mediaStream;
                        })
                        .catch((err) => {
                            alert("No se pudo acceder a la cámara: " + err.message);
                        });

                    document.getElementById('capture').addEventListener('click', () => {
                        const canvas = document.getElementById('canvas');
                        const video = document.getElementById('video');
                        const context = canvas.getContext('2d');
                        canvas.width = 300;
                        canvas.height = 300;

                        context.drawImage(video, 0, 0, 300, 300);

                        canvas.toBlob((blob) => {
                            if (blob) {
                                const file = new File([blob], 'photo.webp', {
                                    type: 'image/webp'
                                });
                                sendImageToServer(file);
                            }
                        }, 'image/webp');

                        stopStream();
                        videoContainer.remove();
                        cameraActive = false;
                    });
                });

                uploadPhotoButton.addEventListener('click', () => {
                    const uploadInput = document.createElement('input');
                    uploadInput.type = 'file';
                    uploadInput.accept = 'image/*';
                    uploadInput.style.display = 'none';
                    document.body.appendChild(uploadInput);

                    uploadInput.click();

                    uploadInput.addEventListener('change', (event) => {
                        const file = event.target.files[0];
                        if (file) {
                            sendImageToServer(file);
                        }
                    });
                });

                function sendImageToServer(file) {
                    const formData = new FormData();
                    formData.append('image', file);
                    formData.append('id', '<?= $player['id'] ?>');

                    fetch('../controllers/ImageUploadController.php', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .then(data => {
                            console.log(data)
                            if (data.success) {
                                alert('Imagen subida correctamente');
                            } else {
                                alert('Error al subir la imagen: ' + data.message);
                            }
                        })
                        .catch((error) => {
                            console.error('Error:', error);
                            alert('Error en la solicitud de subida de imagen');
                        });
                }
            });
        </script>
    <?php endif; ?>
</body>

</html>