<?php

header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
include ('includes/header.php');

// Função para fazer o upload do arquivo
function uploadFile($file) {
    if ($file["size"] == 0) {
        // Nenhum arquivo selecionado, retornar null
        return null;
    }
    
    $targetDir = "img/"; // Diretório onde a imagem será salva
    $fixedFileName = "bg.jpg"; // Nome fixo do arquivo
    
    // Caminho completo para o arquivo de destino
    $targetFile = $targetDir . $fixedFileName;
    
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));

    // Verifica o tipo de arquivo
    if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "png" && $imageFileType != "gif") {
        echo "Desculpe, apenas arquivos JPG, JPEG, PNG e GIF são permitidos.";
        $uploadOk = 0;
    }

    // Tenta fazer o upload do arquivo se tudo estiver ok
    if ($uploadOk == 0) {
        echo "Desculpe, seu arquivo não foi enviado.";
    } else {
        if (move_uploaded_file($file["tmp_name"], $targetFile)) {
            return $targetFile; // Retorna o caminho do arquivo salvo
        } else {
            echo "Desculpe, ocorreu um erro ao fazer o upload do arquivo.";
            return null;
        }
    }
}

// Função para deletar o arquivo de imagem
function deleteFile($url) {
    if (file_exists($url)) {
        unlink($url);
    }
}

// Nome da tabela
$table_name = "ads";

// Variável do arquivo atual
$base_file = basename($_SERVER["SCRIPT_NAME"]);

// Criar tabela se não existir
$adb4->exec("CREATE TABLE IF NOT EXISTS {$table_name}(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title VARCHAR(100), caminho TEXT)");

// Consulta à tabela
$res = $adb4->query("SELECT * FROM {$table_name}");

// Consulta de atualização
@$resU = $adb4->query("SELECT * FROM {$table_name} WHERE id='{$_GET['update']}'");
@$rowU = $resU->fetchArray();

if (isset($_POST['submitU'])) {
    $file_path = null;
    $newFileUploaded = !empty($_FILES["fileToUpload"]["name"]);
    
    if ($newFileUploaded) {
        // Obter o URL do arquivo atual
        $updateQuery = $adb4->query("SELECT caminho FROM {$table_name} WHERE id={$_POST['id']}");
        $updateRow = $updateQuery->fetchArray();
        $currentFileUrl = $updateRow['caminho'];
        $existingFileName = basename($currentFileUrl);

        // Fazer o upload do novo arquivo com o nome do arquivo existente
        $file_path = uploadFile($_FILES["fileToUpload"], $existingFileName);

        // Se um novo arquivo foi enviado, excluir o arquivo atual
        if ($file_path !== null && $file_path != $currentFileUrl) {
            deleteFile($currentFileUrl);
        }
    }
    
    if (isset($_POST['id']) && (isset($_POST['title']) || $file_path !== null)) {
        $title = isset($_POST['title']) ? $_POST['title'] : $rowU['title'];
        $caminho = $file_path !== null ? $file_path : $updateRow['caminho'];
        
        $adb4->exec("UPDATE {$table_name} SET title='{$title}', caminho='{$caminho}' WHERE id='{$_POST['id']}'");
        $adb4->close();
        echo "<script>window.location.href='bg.php';</script>";
        exit;
    } else {
        echo "Nenhum dado enviado.";
    }
}

// Função para adicionar um novo registro
if (isset($_POST['submit'])) {
    $file_path = null;
    if (!empty($_FILES["fileToUpload"]["name"])) {
        $file_path = uploadFile($_FILES["fileToUpload"]);
    }
    if ($file_path !== null || isset($_POST['title'])) {
        $title = isset($_POST['title']) ? $_POST['title'] : "";
        $caminho = $file_path !== null ? $file_path : "";
        
        $adb4->exec("INSERT INTO {$table_name}(title, caminho) VALUES('{$title}', '{$caminho}')");
        echo "<script>window.location.href='bg.php';</script>";
        exit;
    } else {
        echo "Nenhum dado enviado.";
    }
}

// Deletar registro
if (isset($_GET['delete'])) {
    // Busca o URL do arquivo a ser deletado
    $deleteQuery = $adb4->query("SELECT caminho FROM {$table_name} WHERE id={$_GET['delete']}");
    $deleteRow = $deleteQuery->fetchArray();
    $deleteUrl = $deleteRow['caminho'];
    
    // Deleta o arquivo de imagem correspondente
    deleteFile($deleteUrl);
    
    // Deleta o registro do banco de dados
    $adb4->exec("DELETE FROM {$table_name} WHERE id={$_GET['delete']}");
    
    // Redireciona para a página principal
    echo "<script>window.location.href='bg.php';</script>";
    exit;
}

?>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background-color: black;">
            <div class="modal-header">
                <h2 style="color: white;">CONFIRMAR</h2>
            </div>
            <div class="modal-body" style="color: white;">
                QUER MESMO DELETAR?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">CANCELAR</button>
                <a style="color: white;" class="btn btn-danger btn-ok">DELETAR</a>
            </div>
        </div>
    </div>
</div>

<?php
if (isset($_GET['create'])) {

// Formulário de criação
?>
<div class="col-md-8 mx-auto">
   
    <div class="card">
        <div class="card-header">
            </center>
             <center>
        <h2 class="colorboard"></i>NOVO FUNDO</h2>
    </center>
        </div>
        <div class="card-body">
            <form method="post" enctype="multipart/form-data">
                <br>
                <div class="form-group">
                    <input class="form-control" type="text" name="title">
                    <label>NOME DO FUNDO</label>
                </div>
                <br>
                <div class="form-group">
                    <input type="file" name="fileToUpload" id="fileToUpload">
                </div>
                <br>
                <div class="col-12">
                   <button type="submit" name="submit" class="btn btn-primary mr-2"><i class="bx bx-check mr-1"></i>Salvar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php 
} else if (isset($_GET['update'])) { 

// Formulário de atualização
?>
<div class="col-md-8 mx-auto">
  
    <div class="card">
        <div class="card-header">
              <center>
        <h2 class="colorboard"></i>EDITAR FUNDO</h2>
    </center>
            </center>
        </div>
        <div class="card-body">
            <form method="post" enctype="multipart/form-data">
                 <label>NOME DO FUNDO</label>
                <input type="hidden" class="form-control" name="id" value="<?=$_GET['update'] ?>">
                <div class="user-box">
                    <input type="text" name="title" class="form-control" value="<?=$rowU['title'] ?>">
                   
                </div>
                <br>
                <div class="user-box">
                    <input type="file" name="fileToUpload" id="fileToUpload">
                    <br><br>
                </div>
                <br>
                <div class="col-12">
                  <button type="submit" name="submitU" class="btn btn-primary mr-2"><i class="bx bx-check mr-1"></i>Salvar</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php
} else {

// Tabela principal
?>
    <div class="card radius-10">
        <div class="card-header border-bottom-0 bg-transparent">
            <div class="d-flex align-items-center">
                <div>
                   
                   
                </div>
                &nbsp;
                <div>
                    <h5 class="font-weight-bold mb-0">Fundos</h5>
                </div>
                <div class="ms-auto">
                    <a href="bg.php?create">
                        <button type="button" class="btn btn-white radius-10">Adicionar Fundo</button>
                    </a>
                </div>
            </div>
            <br>
            <div class="d-flex align-items-center">
                <div>
                    <h5 class="font-weight-bold mb-0">Fundos cadastrados</h5>
                </div>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table mb-0 align-middle table-sm">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>Nome</th>
                        <th>Prévia</th>
                        <th>Editar Deletar</th>
                    </tr>
                    </thead>
                  <?php while ($row = $res->fetchArray()) { ?>
<tbody>
    <tr>
        <td><?= $row['id'] ?></td>
        <td><?= $row['title'] ?></td>
        <td>
            <img src="img/bg.jpg?<?php echo time(); ?>" alt="Fundo" style="width:100px; height:auto;">
        </td>
        <td>
            <a href="./<?php echo $base_file ?>?update=<?= $row['id'] ?>" class="btn btn-warning">EDITAR</a>
            <a href="#" class="btn btn-danger" data-href="./<?php echo $base_file ?>?delete=<?= $row['id'] ?>" data-toggle="modal" data-target="#confirm-delete">DELETAR</a>
        </td>
    </tr>
</tbody>
<?php } ?>


                </table>
            </div>
        </div>
    </div>
<?php } ?>

<?php include ('includes/footer.php'); ?>
<script type="text/javascript">
// Alerta de sucesso
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
    $("#success-alert").alert('close');
});

// Modal de confirmação de deleção
$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
</script>
</body>
</html>
