<?php
// backup.php
session_start();
require_once 'includes/db.php';

// Apenas Admin
if (!isset($_SESSION['logged_in_fxtream']) || $_SESSION['role'] !== 'admin') { 
    header('Location: dashboard.php'); exit; 
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Backup & Restauração</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/style.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/dark-theme.css">
    
    <style>
        body { background-color: #1a1c23; color: #fff; font-family: 'Segoe UI', sans-serif; overflow-x: hidden;}
        .card { background-color: #232730; border: 1px solid #333; }
        .form-control, .custom-file-label { background-color: #1a1c23; border: 1px solid #444; color: #fff; }
        
        @media (min-width: 992px) {
            #sidebar { display: block !important; width: 240px; position: fixed; top: 0; left: 0; height: 100vh; z-index: 1000; overflow-y: auto; }
            .right-column { margin-left: 240px; width: calc(100% - 240px); padding: 0; }
            .btn-voltar-mobile { display: none; }
        }
        @media (max-width: 991px) {
            #sidebar { display: none !important; }
            .right-column { margin-left: 0 !important; width: 100% !important; padding: 0; }
            .btn-voltar-mobile { display: inline-block; margin-right: 10px; color: #fff; font-size: 1.2rem; }
        }
        .page-header { padding: 15px 20px; border-bottom: 1px solid #333; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; background-color: #1a1c23; }
    </style>
</head>
<body>

<div class="container-fluid p-0">
    <div class="row no-gutters">
        <?php include 'includes/sidebar.php'; ?>
        
        <div class="right-column">
            <div class="page-header sticky-top">
                <div class="d-flex align-items-center">
                    <a href="dashboard.php" class="btn-voltar-mobile"><i class="fa fa-arrow-left"></i></a>
                    <h4 class="mb-0 font-weight-bold text-white"><i class="fa fa-database text-warning mr-2"></i> Backup & Restore</h4>
                </div>
                <a href="dashboard.php" class="btn btn-secondary btn-sm d-none d-lg-inline-block">Voltar</a>
            </div>

            <div class="container px-4 pb-5">
                
                <div class="card shadow mb-4">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0"><i class="fa fa-download"></i> Fazer Backup (Exportar)</h5>
                    </div>
                    <div class="card-body">
                        <p>Clique no botão abaixo para baixar uma cópia completa do seu banco de dados (usuários, canais, configurações, etc).</p>
                        <a href="api/backup_api.php?action=export" class="btn btn-success btn-lg font-weight-bold">
                            <i class="fa fa-file-download"></i> BAIXAR BACKUP AGORA
                        </a>
                    </div>
                </div>

                <div class="card shadow border-danger">
                    <div class="card-header bg-danger text-white">
                        <h5 class="mb-0"><i class="fa fa-upload"></i> Restaurar Backup (Importar)</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-warning">
                            <i class="fa fa-exclamation-triangle"></i> <b>CUIDADO:</b> Isso irá substituir seus dados atuais pelos dados do arquivo. Faça um backup antes!
                        </div>
                        
                        <form id="formRestore" enctype="multipart/form-data">
                            <input type="hidden" name="action" value="import">
                            <div class="form-group">
                                <label>Selecione o arquivo <b>.sql</b></label>
                                <div class="custom-file">
                                    <input type="file" class="custom-file-input" name="backup_file" id="backupFile" accept=".sql" required>
                                    <label class="custom-file-label" for="backupFile">Escolher arquivo...</label>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-danger btn-block font-weight-bold" id="btnRestore">
                                <i class="fa fa-sync"></i> INICIAR RESTAURAÇÃO
                            </button>
                        </form>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
    // Nome do arquivo no input
    $('.custom-file-input').on('change', function() {
        var fileName = $(this).val().split('\\').pop();
        $(this).next('.custom-file-label').addClass("selected").html(fileName);
    });

    // Processo de Restauração
    $('#formRestore').submit(function(e){
        e.preventDefault();
        if(!confirm("ATENÇÃO: Você tem certeza que deseja restaurar o banco? Os dados atuais serão substituídos!")) return;

        let formData = new FormData(this);
        let btn = $('#btnRestore');
        let originalText = btn.html();

        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Restaurando... Aguarde...');

        $.ajax({
            url: 'api/backup_api.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(res){
                if(res.status) {
                    toastr.success(res.msg);
                    setTimeout(() => location.reload(), 2000);
                } else {
                    toastr.error(res.msg);
                }
                btn.prop('disabled', false).html(originalText);
            },
            error: function(){
                toastr.error('Erro de conexão com o servidor.');
                btn.prop('disabled', false).html(originalText);
            }
        });
    });
</script>
</body>
</html>