<?php

include("../conexao.php");

// Remover vídeo
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $id = (int)$_POST['delete_id'];
    $stmt = $con->prepare("DELETE FROM pasta_de_videos WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->close();
}

// Buscar todos os vídeos
$query = "SELECT id, caminho FROM pasta_de_videos WHERE id_tabela_digital_programacao = " . $_GET["id"];
$result = $con->query($query);
$videos = $result->fetch_all(MYSQLI_ASSOC);
$result->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar Pasta de Vídeos</title>
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
	<link href="css/styles.css" rel="stylesheet">
	<link rel="shortcut icon" href="images/syspan.ico">
	<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
	<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
	<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
	<script src="js/jquery.js"></script>
	<link rel="stylesheet" href="css/jquery-ui.css">
	<link href="css/font-awesome.css" rel="stylesheet">
	<link href="vendors/form-helpers/css/bootstrap-formhelpers.min.css" rel="stylesheet">
	<link href="vendors/select/bootstrap-select.min.css" rel="stylesheet">
	<link href="vendors/tags/css/bootstrap-tags.css" rel="stylesheet">
	<link href="css/forms.css" rel="stylesheet">
	<script src="js/jquery-ui.js"></script>
    <style>
        /* Estilo do loader */
        #loader {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            z-index: 9999;
        }
        #loader .spinner {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: white;
            font-size: 24px;
        }
    </style>
</head>
<body>
<div id="loader">
    <div class="spinner">Carregando...</div>
</div>
<div class="header">
    <div class="container">
        <div class="row">
            <div class="col-md-5">
                <!-- Logo -->
                <div class="logo">
                    <h5><img alt="Logo Syspan" src="images/logo_syspan_17_rodape.png"
                            style="max-height:40px;margin-bottom:5px;"> TABELA DIGITAL PROGRAMAÇÃO</h5>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="container">
    <h2>Gerenciar Pasta de Vídeos</h2>

    <!-- Formulário para upload de vídeo -->
    <form id="videoForm" class="form-inline">
        <div class="form-group">
            <label for="video">Selecionar Vídeo:</label>
            <input type="file" name="arquivo_video" id="arquivo_video" class="form-control" accept=".mp4" required>
        </div>
        <br>
        <button type="button" id="uploadButton" class="btn btn-primary" style="margin-top: 15px;">Adicionar Vídeo</button>
    </form>

    <hr>

    <a href="./" class='btn btn-primary' style="position: fixed; right: 5%; top:15%; box-shadow: 1px 1px 10px black;">Voltar</a>

    <!-- Lista de vídeos -->
    <h3>Lista de Vídeos</h3>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Pré-visualização</th>
                <th>Caminho</th>
                <th>Ação</th>
            </tr>
        </thead>
        <tbody id="videoTable">
            <?php foreach ($videos as $video): ?>
                <tr data-id="<?= $video['id'] ?>">
                    <td>
                        <video width="150" controls>
                            <source src="<?= htmlspecialchars($video['caminho']) ?>" type="video/mp4">
                            Seu navegador não suporta a tag de vídeo.
                        </video>
                    </td>
                    <td><?= htmlspecialchars($video['caminho']) ?></td>
                    <td>
                        <button class="btn btn-danger btn-sm deleteButton">Remover</button>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<script>



$(document).ready(function() {

    function toggleLoader(show) {
        if (show) {
            $('#loader').fadeIn();
        } else {
            $('#loader').fadeOut();
        }
    }
    // Manipular o upload do vídeo
    $('#uploadButton').click(function() {
        toggleLoader(true);
        let formData = new FormData();
        let videoFile = $('#arquivo_video')[0].files[0];

        if (!videoFile) {
            alert('Por favor, selecione um vídeo.');

            toggleLoader(false);
            return;
        }

        formData.append('arquivo_video', videoFile);

        // Enviar o vídeo via AJAX
        $.ajax({
            url: 'enviar_videos.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                let caminho = JSON.parse(response).msg;
                if (caminho) {
                    // Salvar no banco de dados
                    $.post('salvar_video_pasta.php', { caminho: caminho }, function(data) {
                        toggleLoader(false);
                        // Atualizar a tabela com o novo vídeo
                        let newRow = `
                            <tr>
                                <td>
                                    <video width="150" controls>
                                        <source src="${caminho}" type="video/mp4">
                                        Seu navegador não suporta a tag de vídeo.
                                    </video>
                                </td>
                                <td>${caminho}</td>
                                <td>
                                    <button class="btn btn-danger btn-sm deleteButton">Remover</button>
                                </td>
                            </tr>`;
                        $('#videoTable').append(newRow);
                        $('#arquivo_video').val('');
                    });
                } else {
                    toggleLoader(false);
                    alert('Erro ao salvar o vídeo.');
                }
            },
            error: function() {
                toggleLoader(false);
                alert('Erro ao enviar o vídeo.');
            }
        });
    });

    // Remover vídeo
    $(document).on('click', '.deleteButton', function() {
        let row = $(this).closest('tr');
        let videoId = row.data('id');

        if (confirm('Tem certeza de que deseja remover este vídeo?')) {
            $.post('', { delete_id: videoId }, function() {
                row.remove();
            });
        }
    });
});
</script>

<script src="bootstrap/js/bootstrap.min.js"></script>

	<script src="vendors/form-helpers/js/bootstrap-formhelpers.min.js"></script>
	<script src="vendors/select/bootstrap-select.min.js"></script>
	<script src="vendors/tags/js/bootstrap-tags.min.js"></script>
	<script src="vendors/mask/jquery.maskedinput.min.js"></script>
	<script src="vendors/moment/moment.min.js"></script>
	<script src="vendors/wizard/jquery.bootstrap.wizard.min.js"></script>
	<link href="vendors/bootstrap-datetimepicker/datetimepicker.css" rel="stylesheet">
	<script src="vendors/bootstrap-datetimepicker/bootstrap-datetimepicker.js"></script>

	<script src="js/custom.js"></script>
	<script type="text/javascript" src="js/jquery.mask.min.js"></script>
	<script src="js/jquery.form.js" type="text/javascript"></script>
</body>
</html>

<?php $con->close(); ?>
