<?php
session_start();
require 'config.php'; // Inclua sua configuração de banco de dados aqui

// Verifica se o usuário está logado
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Função para gerar slug
function slugify($text) {
    $text = mb_strtolower($text, 'UTF-8');
    $text = preg_replace('~[^\p{L}\p{N}]+~u', '-', $text);
    $text = preg_replace('~-+~', '-', $text);
    return trim($text, '-');
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $page_title = $_POST['page_title'];
    $id_ifood = $_POST['id_ifood'];
    $custom_slug = trim($_POST['slug']);
    $link_restaurante = $_POST['link_restaurante'];
    $id_gtm = $_POST['id_gtm'];
    $mensagem_personalizada = $_POST['mensagem_personalizada'];
    $redirect_time = intval($_POST['redirect_time']);
    $button_active = isset($_POST['button_active']) ? 1 : 0;
    $button_text = $_POST['button_text'];
    $button_color = $_POST['button_color'];
    $button_outline = isset($_POST['button_outline']) ? 1 : 0;
    $button_border_color = $_POST['button_border_color'];
    $logo_height = $_POST['logo_height'];
    $logo_position = $_POST['logo_position'];
    $disable_redirect = isset($_POST['disable_redirect']) ? 1 : 0;
    $user_id = $_SESSION['user_id'];

    // Gera slug
    $slug = !empty($custom_slug) ? slugify($custom_slug) : slugify($page_title);

    // Lógica de upload de arquivo
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] == UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['logo']['tmp_name'];
        $fileName = $_FILES['logo']['name'];
        $restaurantDirectory = 'restaurante/' . $user_id;

        if (!file_exists($restaurantDirectory)) {
            mkdir($restaurantDirectory, 0755, true);
        }
        
        $destPath = $restaurantDirectory . '/' . basename($fileName);

        if (move_uploaded_file($fileTmpPath, $destPath)) {
            // Insere os dados do restaurante no banco de dados
            $sql = "INSERT INTO restaurantes (page_title, logo, link_restaurante, id_gtm, mensagem_personalizada, usuario_id, slug, id_ifood, redirect_time, button_text, disable_redirect) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->execute([$page_title, $destPath, $link_restaurante, $id_gtm, $mensagem_personalizada, $user_id, $slug, $id_ifood, $redirect_time, $button_text, $disable_redirect]);

            // Captura o ID do restaurante recém-adicionado
            $id_restaurante = $conn->lastInsertId();

            // Insere os dados de design na nova tabela
            $sql = "INSERT INTO designs (id_restaurante, logo_height, logo_position, button_color, button_outline, button_border_color) VALUES (?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->execute([$id_restaurante, $logo_height, $logo_position, $button_color, $button_outline, $button_border_color]);

            header("Location: dashboard.php");
            exit();
        } else {
            $error = "Ocorreu um erro ao mover o arquivo para o diretório de upload.";
        }
    } else {
        $error = "Erro no upload do arquivo.";
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Adicionar Restaurante</title>

    <!-- Bootstrap CSS -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="css/styles-add-restaurante.css" rel="stylesheet">
</head>
<body>

    <div class="container">
        <div class="card shadow-sm">
            <h1 class="h3 mb-4">Adicionar Restaurante</h1>
            <?php if (isset($error)) { echo "<div class='alert alert-danger'>$error</div>"; } ?>
            <form action="" method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="page_title">Título da Página</label>
                    <input type="text" class="form-control" id="page_title" name="page_title" required>
                </div>
                <div class="form-group">
                    <label for="slug">Slug Personalizado (opcional)</label>
                    <input type="text" class="form-control" id="slug" name="slug">
                    <small class="form-text text-muted">Se não preencher, será gerado automaticamente a partir do título.</small>
                </div>
                <div class="form-group">
                    <label for="id_ifood">ID do iFood</label>
                    <input type="text" class="form-control" id="id_ifood" name="id_ifood" required>
                </div>
                <div class="form-group">
                    <label for="logo">Logo (upload)</label>
                    <input type="file" class="form-control-file" id="logo" name="logo" accept="image/*" required>
                </div>
                <div class="form-group">
                    <label for="link_restaurante">Link do Restaurante</label>
                    <input type="text" class="form-control" id="link_restaurante" name="link_restaurante" required>
                </div>
                <div class="form-group">
                    <label for="id_gtm">ID GTM</label>
                    <input type="text" class="form-control" id="id_gtm" name="id_gtm" required>
                </div>
                <div class="form-group">
                    <label for="mensagem_personalizada">Mensagem Personalizada</label>
                    <textarea class="form-control" id="mensagem_personalizada" name="mensagem_personalizada" rows="3" required></textarea>
                </div>
                <div class="form-group">
                    <label for="redirect_time">Tempo de Redirecionamento (em segundos)</label>
                    <input type="number" class="form-control" id="redirect_time" name="redirect_time" value="7" required>
                </div>
                <div class="form-group">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="disable_redirect" name="disable_redirect">
                        <label class="form-check-label" for="disable_redirect">Desativar redirecionamento automático</label>
                    </div>
                </div>
                <div class="form-group">
                    <label for="button_text">Texto e Cor do Botão</label>
                    <div class="row">
                        <div class="col-md-8">
                            <input type="text" class="form-control" id="button_text" name="button_text" value="Visitar Restaurante" required>
                        </div>
                        <div class="col-md-4">
                            <input type="color" class="form-control" id="button_color" name="button_color" value="#5cb85c" required>
                        </div>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">Adicionar</button>
                <a href="dashboard.php" class="btn btn-secondary ml-2">Voltar</a>
            </form>
        </div>
    </div>

    <!-- Bootstrap JS and dependencies -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script>
        document.getElementById('button_color').addEventListener('input', function() {
            document.querySelector('.btn-primary').style.backgroundColor = this.value;
            document.querySelector('.btn-primary').style.borderColor = this.value;
        });
    </script>
    
</body>
</html>