<?php
// Database connection
$db = new SQLite3('./api/.db.db');

// Table name
$table_name = "qrcode_studiolivecode";

// Current file var
$base_file = basename($_SERVER["SCRIPT_NAME"]);

// Create table if not exists with all required columns
$db->exec("CREATE TABLE IF NOT EXISTS {$table_name}(
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
    title TEXT,
    url TEXT,
    type TEXT,
    filepath TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)");

// Check if filepath column exists, if not add it
$tableInfo = $db->query("PRAGMA table_info({$table_name})");
$hasFilepath = false;
while ($column = $tableInfo->fetchArray(SQLITE3_ASSOC)) {
    if ($column['name'] === 'filepath') {
        $hasFilepath = true;
        break;
    }
}

if (!$hasFilepath) {
    $db->exec("ALTER TABLE {$table_name} ADD COLUMN filepath TEXT");
}

// Directory for uploads
$upload_dir = 'public/qrcodes/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

// Handle QR code generation
if (isset($_POST['generate_qr'])) {
    $phone_number = $_POST['phone_number'];
    
    // Validate phone number
    if (!preg_match('/^[0-9]+$/', $phone_number)) {
        $error = "Número de telefone inválido. Use apenas números.";
    } else {
        // Format the WhatsApp URL
        $whatsapp_url = "https://wa.me/" . $phone_number;
        
        // Generate QR code using an external API
        $qr_content = file_get_contents("https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=" . urlencode($whatsapp_url));
        
        if ($qr_content) {
            // Define file path - sempre com o nome qr.png
            $filename = 'qr.png';
            $filepath = $upload_dir . $filename;
            
            // Save QR code image
            if (file_put_contents($filepath, $qr_content)) {
                // Delete previous generated QR codes from database
                $db->exec("DELETE FROM {$table_name} WHERE type = 'generated'");
                
                // Insert into database
                $stmt = $db->prepare("INSERT INTO {$table_name}(title, url, type, filepath) VALUES(:title, :url, :type, :filepath)");
                if ($stmt) {
                    $stmt->bindValue(':title', 'WhatsApp QR Code', SQLITE3_TEXT);
                    $stmt->bindValue(':url', $whatsapp_url, SQLITE3_TEXT);
                    $stmt->bindValue(':type', 'generated', SQLITE3_TEXT);
                    $stmt->bindValue(':filepath', $filepath, SQLITE3_TEXT);
                    
                    if ($stmt->execute()) {
                        $success = "QR Code gerado com sucesso!";
                    } else {
                        $error = "Erro ao salvar no banco de dados.";
                    }
                } else {
                    $error = "Erro ao preparar a declaração SQL.";
                }
            } else {
                $error = 'Erro: Falha ao salvar a imagem do QR Code.';
            }
        } else {
            $error = 'Erro: Falha ao gerar o QR Code.';
        }
    }
}

// Handle image upload
if (isset($_POST['upload_qr'])) {
    if (isset($_FILES['qr_image']) && $_FILES['qr_image']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['qr_image'];
        
        // Validate file type - apenas PNG
        $allowed_types = ['image/png'];
        $file_info = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($file_info, $file['tmp_name']);
        finfo_close($file_info);
        
        // Validate file extension
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (!in_array($mime_type, $allowed_types) || $ext !== 'png') {
            $error = 'Erro: Apenas arquivos PNG são permitidos.';
        } else {
            // Define file name - sempre com o nome qr.png
            $filename = 'qr.png';
            $filepath = $upload_dir . $filename;
            
            // Delete any existing qr.png file
            if (file_exists($filepath)) {
                unlink($filepath);
            }
            
            // Move uploaded file
            if (move_uploaded_file($file['tmp_name'], $filepath)) {
                // Delete previous uploaded QR codes from database
                $db->exec("DELETE FROM {$table_name} WHERE type = 'uploaded'");
                
                // Insert into database
                $stmt = $db->prepare("INSERT INTO {$table_name}(title, url, type, filepath) VALUES(:title, :url, :type, :filepath)");
                if ($stmt) {
                    $stmt->bindValue(':title', 'QR Code Carregado', SQLITE3_TEXT);
                    $stmt->bindValue(':url', $filepath, SQLITE3_TEXT);
                    $stmt->bindValue(':type', 'uploaded', SQLITE3_TEXT);
                    $stmt->bindValue(':filepath', $filepath, SQLITE3_TEXT);
                    
                    if ($stmt->execute()) {
                        $success = 'QR Code carregado com sucesso!';
                    } else {
                        $error = "Erro ao salvar no banco de dados.";
                        // Clean up file if DB insert failed
                        if (file_exists($filepath)) {
                            unlink($filepath);
                        }
                    }
                } else {
                    $error = "Erro ao preparar a declaração SQL.";
                    if (file_exists($filepath)) {
                        unlink($filepath);
                    }
                }
            } else {
                $error = 'Erro: Falha ao mover o arquivo.';
            }
        }
    } else {
        $error = 'Erro: Nenhum arquivo enviado ou erro no upload.';
    }
}

// Delete QR code
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    
    // Get QR code info
    $res = $db->query("SELECT * FROM {$table_name} WHERE id = $id");
    if ($row = $res->fetchArray()) {
        // Delete the file if it exists
        if (!empty($row['filepath']) && file_exists($row['filepath'])) {
            unlink($row['filepath']);
        }
        
        // Delete from database
        $db->exec("DELETE FROM {$table_name} WHERE id = $id");
        $success = "QR Code excluído com sucesso!";
    }
    
    header("Location: {$base_file}");
    exit();
}

include ('includes/studiolivheaderecode.php');

// Get current QR codes
$generated_qr = null;
$uploaded_qr = null;

$res = $db->query("SELECT * FROM {$table_name} ORDER BY created_at DESC");
while ($row = $res->fetchArray()) {
    if ($row['type'] === 'generated' && !$generated_qr) {
        $generated_qr = $row;
    } elseif ($row['type'] === 'uploaded' && !$uploaded_qr) {
        $uploaded_qr = $row;
    }
}
?>

<!-- Delete confirmation modal -->
<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">
            <div class="modal-header">
                <h2>Confirmar</h2>
            </div>
            <div class="modal-body">
                Tem certeza que deseja excluir este QR Code?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok">Excluir</a>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-12 col-lg-10 col-xl-8">
            <div class="card bg-primary shadow-lg">
                <div class="card-header card-header-warning py-3">
                    <h2 class="h4 mb-0 text-center"><i class="fa fa-qrcode mr-2"></i>Gerenciamento de QR Code</h2>
                </div>
                
                <div class="card-body p-4">
                    <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?= $error ?>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?= $success ?>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Current QR Codes Section -->
                    <div class="row mb-5">
                        <div class="col-12 mb-3">
                            <h4 class="text-white border-bottom pb-2">QR Codes Atuais</h4>
                        </div>
                        
                        <?php if (($generated_qr && !empty($generated_qr['filepath']) && file_exists($generated_qr['filepath'])) || (file_exists($upload_dir . 'qr.png') && filesize($upload_dir . 'qr.png') > 0)): ?>
                        <div class="col-12 col-md-6 mb-4">
                            <div class="card h-100 bg-light-primary border-0">
                                <div class="card-body text-center p-3">
                                    <h5 class="card-title text-white mb-3">QR Code Disponível</h5>
                                    
                                    <?php if ($generated_qr && !empty($generated_qr['filepath']) && file_exists($generated_qr['filepath'])): ?>
                                        <img src="<?= $generated_qr['filepath'] ?>?t=<?= time() ?>" class="img-fluid rounded shadow" style="max-height: 180px;">
                                        <p class="mt-3 mb-1 text-white-50 small">
                                            <i class="fa fa-calendar mr-1"></i>Criado: <?= date('d/m/Y H:i', strtotime($generated_qr['created_at'])) ?>
                                        </p>
                                        <p class="mb-3 text-white-50 small">
                                            <i class="fa fa-link mr-1"></i>Link: WhatsApp
                                        </p>
                                    <?php elseif (file_exists($upload_dir . 'qr.png') && filesize($upload_dir . 'qr.png') > 0): ?>
                                        <img src="<?= $upload_dir ?>qr.png?t=<?= time() ?>" class="img-fluid rounded shadow" style="max-height: 180px;">
                                        <p class="mt-3 mb-3 text-white-50 small">
                                            <i class="fa fa-file-image-o mr-1"></i>Arquivo: qr.png
                                        </p>
                                    <?php endif; ?>
                                    
                                    <a href="#" class="btn btn-sm btn-danger mt-2" data-href="./<?= $base_file ?>?delete=<?= $generated_qr['id'] ?? 'all' ?>" data-toggle="modal" data-target="#confirm-delete">
                                        <i class="fa fa-trash-o mr-1"></i> Excluir
                                    </a>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($uploaded_qr && !empty($uploaded_qr['filepath']) && file_exists($uploaded_qr['filepath'])): ?>
                        <div class="col-12 col-md-6 mb-4">
                            <div class="card h-100 bg-light-primary border-0">
                                <div class="card-body text-center p-3">
                                    <h5 class="card-title text-white mb-3">QR Code Carregado</h5>
                                    <img src="<?= $uploaded_qr['filepath'] ?>?t=<?= time() ?>" class="img-fluid rounded shadow" style="max-height: 180px;">
                                    <p class="mt-3 mb-1 text-white-50 small">
                                        <i class="fa fa-calendar mr-1"></i>Carregado: <?= date('d/m/Y H:i', strtotime($uploaded_qr['created_at'])) ?>
                                    </p>
                                    <p class="mb-3 text-white-50 small">
                                        <i class="fa fa-upload mr-1"></i>Origem: Upload
                                    </p>
                                    <a href="#" class="btn btn-sm btn-danger mt-2" data-href="./<?= $base_file ?>?delete=<?= $uploaded_qr['id'] ?>" data-toggle="modal" data-target="#confirm-delete">
                                        <i class="fa fa-trash-o mr-1"></i> Excluir
                                    </a>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if (!(($generated_qr && !empty($generated_qr['filepath']) && file_exists($generated_qr['filepath'])) || (file_exists($upload_dir . 'qr.png') && filesize($upload_dir . 'qr.png') > 0) || ($uploaded_qr && !empty($uploaded_qr['filepath']) && file_exists($uploaded_qr['filepath'])))): ?>
                        <div class="col-12">
                            <div class="alert alert-info text-center">
                                <i class="fa fa-info-circle mr-2"></i>Nenhum QR Code disponível. Gere ou carregue um QR Code.
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Mode Selection Section -->
                    <div class="row mb-4">
                        <div class="col-12 mb-3">
                            <h4 class="text-white border-bottom pb-2">Selecionar Ação</h4>
                            <p class="text-white-50 mb-4">Escolha como deseja adicionar um QR Code:</p>
                        </div>
                        
                        <div class="col-12 col-md-6 mb-4">
                            <div class="card mode-selection-card h-100 bg-light-primary border-primary shadow-sm" id="qr-generate-card" style="cursor: pointer; transition: all 0.3s;">
                                <div class="card-body text-center p-4">
                                    <div class="icon-wrapper bg-primary rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 70px; height: 70px;">
                                        <span style="font-size: 2rem;">🔗</span>
                                    </div>
                                    <h5 class="text-white">Gerar QR Code</h5>
                                    <p class="text-white-70 mb-0">Crie um QR Code a partir de um número de celular.</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-12 col-md-6 mb-4">
                            <div class="card mode-selection-card h-100 bg-light-primary border-light shadow-sm" id="qr-upload-card" style="cursor: pointer; transition: all 0.3s;">
                                <div class="card-body text-center p-4">
                                    <div class="icon-wrapper bg-primary rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 70px; height: 70px;">
                                        <span style="font-size: 2rem;">🖼️</span>
                                    </div>
                                    <h5 class="text-white">Carregar QR Code</h5>
                                    <p class="text-white-70 mb-0">Faça upload de uma imagem PNG do seu QR Code.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- QR Code Generation Form -->
                    <div class="row mb-4" id="qr-generate-form" style="display: none;">
                        <div class="col-12">
                            <div class="card bg-light-primary border-0">
                                <div class="card-body p-4">
                                    <h5 class="text-white mb-4"><i class="fa fa-link mr-2"></i>Gerar QR Code</h5>
                                    <form method="post">
                                        <div class="form-group">
                                            <label for="phone_number" class="text-white">Número de celular</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text bg-light text-dark">+</span>
                                                </div>
                                                <input type="text" class="form-control" id="phone_number" name="phone_number" placeholder="Ex: 5511996200241" required>
                                            </div>
                                            <small class="form-text text-white-60">
                                                Digite o número completo com código do país e área (sem espaços ou caracteres especiais).
                                            </small>
                                        </div>
                                        <div class="form-group text-center mt-4">
                                            <button class="btn btn-info px-4 py-2" name="generate_qr" type="submit">
                                                <i class="fa fa-qrcode mr-2"></i> Gerar QR Code
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- QR Code Upload Form -->
                    <div class="row mb-4" id="qr-upload-form" style="display: none;">
                        <div class="col-12">
                            <div class="card bg-light-primary border-0">
                                <div class="card-body p-4">
                                    <h5 class="text-white mb-4"><i class="fa fa-upload mr-2"></i>Carregar QR Code</h5>
                                    <div class="alert alert-info bg-info-light border-info">
                                        <strong><i class="fa fa-info-circle mr-2"></i>Atenção:</strong> Apenas arquivos no formato PNG são aceitos. O arquivo será salvo como <strong>qr.png</strong>.
                                    </div>
                                    <form method="post" enctype="multipart/form-data">
                                        <div class="form-group">
                                            <label for="qr_image" class="text-white">Selecione a imagem</label>
                                            <div class="custom-file">
                                                <input type="file" class="custom-file-input" id="qr_image" name="qr_image" accept=".png" required>
                                                <label class="custom-file-label bg-light text-dark" for="qr_image">Selecionar arquivo PNG</label>
                                            </div>
                                            <small class="form-text text-white-60">
                                                Formatos aceitos: <strong>PNG</strong> apenas. Tamanho máximo: <?= ini_get('upload_max_filesize') ?>B
                                            </small>
                                        </div>
                                        <div class="form-group text-center mt-4">
                                            <button class="btn btn-info px-4 py-2" name="upload_qr" type="submit">
                                                <i class="fa fa-upload mr-2"></i> Carregar QR Code
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include ('includes/studifooterolivecode.php'); ?>

<style>
.bg-light-primary {
    background-color: rgba(255, 255, 255, 0.1) !important;
}
.bg-info-light {
    background-color: rgba(23, 162, 184, 0.2) !important;
}
.text-white-60 {
    color: rgba(255, 255, 255, 0.6) !important;
}
.text-white-70 {
    color: rgba(255, 255, 255, 0.7) !important;
}
/*.card-header-warning {*/
/*    background: linear-gradient(60deg, #ab47bc, #8e24aa);*/
/*}*/
.mode-selection-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.1) !important;
}
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Mode selection functionality
        const generateCard = document.getElementById('qr-generate-card');
        const uploadCard = document.getElementById('qr-upload-card');
        const generateForm = document.getElementById('qr-generate-form');
        const uploadForm = document.getElementById('qr-upload-form');
        
        generateCard.addEventListener('click', function() {
            generateForm.style.display = 'block';
            uploadForm.style.display = 'none';
            generateCard.classList.add('border-primary');
            uploadCard.classList.remove('border-primary');
            uploadCard.classList.add('border-light');
            generateCard.classList.remove('border-light');
        });
        
        uploadCard.addEventListener('click', function() {
            generateForm.style.display = 'none';
            uploadForm.style.display = 'block';
            uploadCard.classList.add('border-primary');
            generateCard.classList.remove('border-primary');
            generateCard.classList.add('border-light');
            uploadCard.classList.remove('border-light');
        });
        
        // Delete confirmation modal
        $('#confirm-delete').on('show.bs.modal', function(e) {
            $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
        });
        
        // File input validation and label update
        document.getElementById('qr_image').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const label = this.nextElementSibling;
            
            if (file) {
                const fileName = file.name;
                const fileExt = fileName.split('.').pop().toLowerCase();
                
                if (fileExt !== 'png') {
                    alert('Apenas arquivos PNG são permitidos. Por favor, selecione um arquivo com extensão .png');
                    e.target.value = '';
                    label.textContent = 'Selecionar arquivo PNG';
                } else {
                    label.textContent = fileName;
                }
            } else {
                label.textContent = 'Selecionar arquivo PNG';
            }
        });
        
        // Add hover effects to mode selection cards
        const modeCards = document.querySelectorAll('.mode-selection-card');
        modeCards.forEach(card => {
            card.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-5px)';
                this.style.boxShadow = '0 10px 20px rgba(0,0,0,0.1)';
            });
            
            card.addEventListener('mouseleave', function() {
                if (!this.classList.contains('border-primary')) {
                    this.style.transform = 'translateY(0)';
                    this.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)';
                }
            });
        });
    });
</script>