<?php 
include ('includes/header.php');

$table_name = "ads";
$base_file = basename($_SERVER["SCRIPT_NAME"]);
$upload_dir = "img/ads/";

// Criar diretório de upload se não existir
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

$adb->exec("CREATE TABLE IF NOT EXISTS {$table_name}(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title VARCHAR(100), url TEXT)");

// Função para processar upload único ou múltiplo
function handleUploads($files) {
    global $upload_dir;
    $uploaded_paths = [];
    
    // Se for um único arquivo (não múltiplo)
    if (!is_array($files['name'])) {
        if ($files['error'] === UPLOAD_ERR_OK) {
            $ext = pathinfo($files['name'], PATHINFO_EXTENSION);
            $new_name = uniqid() . '.' . $ext;
            $dest = $upload_dir . $new_name;
            if (move_uploaded_file($files['tmp_name'], $dest)) {
                $uploaded_paths[] = $dest;
            }
        }
    } else {
        // Se for múltiplo
        foreach ($files['name'] as $key => $name) {
            if ($files['error'][$key] === UPLOAD_ERR_OK) {
                $ext = pathinfo($name, PATHINFO_EXTENSION);
                $new_name = uniqid() . '_' . $key . '.' . $ext;
                $dest = $upload_dir . $new_name;
                if (move_uploaded_file($files['tmp_name'][$key], $dest)) {
                    $uploaded_paths[] = $dest;
                }
            }
        }
    }
    return $uploaded_paths;
}

// Lógica de exclusão (Corrigida)
if(isset($_GET['delete_id'])){
    $id = intval($_GET['delete_id']);
    $res = $adb->query("SELECT url FROM {$table_name} WHERE id=$id");
    $row = $res->fetchArray();
    if ($row && file_exists($row['url'])) {
        unlink($row['url']);
    }
    $adb->exec("DELETE FROM {$table_name} WHERE id=$id");
    echo "<script>window.location.href='mRTXBGads.php';</script>";
    exit;
}

// Lógica de inserção/atualização
if (isset($_POST['submit_ad'])) {
    $title = $_POST['title'];
    $url = $_POST['url']; // Link manual
    $id = isset($_POST['id']) ? $_POST['id'] : null;

    // Processar uploads
    if (isset($_FILES['ad_files']) && !empty($_FILES['ad_files']['name'][0])) {
        $uploaded_paths = handleUploads($_FILES['ad_files']);
        
        if ($id) {
            // Se for edição, só pega o primeiro upload se houver
            if (!empty($uploaded_paths)) {
                $url = $uploaded_paths[0];
                $adb->exec("UPDATE {$table_name} SET title='$title', url='$url' WHERE id=$id");
            } else {
                $adb->exec("UPDATE {$table_name} SET title='$title', url='$url' WHERE id=$id");
            }
        } else {
            // Se for novo e múltiplo, cria um registro para cada
            if (!empty($uploaded_paths)) {
                foreach ($uploaded_paths as $idx => $path) {
                    $current_title = (count($uploaded_paths) > 1) ? $title . " (" . ($idx + 1) . ")" : $title;
                    $adb->exec("INSERT INTO {$table_name}(title, url) VALUES('$current_title', '$path')");
                }
            } else if (!empty($url)) {
                $adb->exec("INSERT INTO {$table_name}(title, url) VALUES('$title', '$url')");
            }
        }
    } else {
        // Sem upload, usa o link manual
        if ($id) {
            $adb->exec("UPDATE {$table_name} SET title='$title', url='$url' WHERE id=$id");
        } else if (!empty($url)) {
            $adb->exec("INSERT INTO {$table_name}(title, url) VALUES('$title', '$url')");
        }
    }
    echo "<script>window.location.href='mRTXBGads.php';</script>";
    exit;
}

$res = $adb->query("SELECT * FROM {$table_name} ORDER BY id DESC");
$update_data = null;
if (isset($_GET['update'])) {
    $update_res = $adb->query("SELECT * FROM {$table_name} WHERE id='{$_GET['update']}'");
    $update_data = $update_res->fetchArray();
}
?>

<div class="container-fluid">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Gerenciamento de Anúncios</h1>
    </div>

    <div class="row">
        <!-- Formulário -->
        <div class="col-lg-4">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-plus-circle mr-2"></i>
                        <?php echo $update_data ? 'Editar Anúncio' : 'Novo Anúncio'; ?>
                    </h6>
                </div>
                <div class="card-body">
                    <form method="post" enctype="multipart/form-data">
                        <?php if($update_data): ?>
                            <input type="hidden" name="id" value="<?php echo $update_data['id']; ?>">
                        <?php endif; ?>
                        
                        <div class="form-group">
                            <label>Título do Anúncio</label>
                            <input type="text" name="title" class="form-control" value="<?php echo $update_data ? $update_data['title'] : ''; ?>" required>
                        </div>

                        <div class="form-group">
                            <label>Link da Imagem (URL)</label>
                            <input type="text" name="url" class="form-control" placeholder="http://..." value="<?php echo $update_data ? $update_data['url'] : ''; ?>">
                        </div>

                        <div class="form-group">
                            <label>Subir Imagens (Múltiplas)</label>
                            <div class="custom-file">
                                <input type="file" name="ad_files[]" class="custom-file-input" id="adFiles" accept="image/*,video/*" multiple>
                                <label class="custom-file-label" for="adFiles">Escolher arquivos...</label>
                            </div>
                            <small class="text-muted">Você pode selecionar várias imagens de uma vez.</small>
                        </div>

                        <button type="submit" name="submit_ad" class="btn btn-primary btn-block mt-4">
                            <i class="fas fa-save mr-2"></i> Salvar Anúncio
                        </button>
                        <?php if($update_data): ?>
                            <a href="mRTXBGads.php" class="btn btn-secondary btn-block">Cancelar</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        </div>

        <!-- Lista -->
        <div class="col-lg-8">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-list mr-2"></i> Anúncios Ativos</h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Preview</th>
                                    <th>Título</th>
                                    <th>Origem</th>
                                    <th class="text-center">Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($row = $res->fetchArray()): ?>
                                    <tr>
                                        <td style="width: 120px;">
                                            <?php 
                                            $is_video = preg_match('/\.(mp4|webm|ogg)$/i', $row['url']);
                                            if ($is_video): ?>
                                                <video src="<?php echo $row['url']; ?>" width="100" muted></video>
                                            <?php else: ?>
                                                <img src="<?php echo $row['url']; ?>" width="100" class="img-thumbnail">
                                            <?php endif; ?>
                                        </td>
                                        <td class="align-middle font-weight-bold"><?php echo $row['title']; ?></td>
                                        <td class="align-middle small text-truncate" style="max-width: 200px;">
                                            <?php echo $row['url']; ?>
                                        </td>
                                        <td class="align-middle text-center">
                                            <a href="mRTXBGads.php?update=<?php echo $row['id']; ?>" class="btn btn-sm btn-info btn-circle">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="#" data-href="mRTXBGads.php?delete_id=<?php echo $row['id']; ?>" data-toggle="modal" data-target="#confirm-delete" class="btn btn-sm btn-danger btn-circle">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Deletar -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Confirmar Exclusão</h5>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body text-center py-4">
                <i class="fas fa-trash-alt fa-3x text-danger mb-3"></i>
                <p>Deseja realmente excluir este anúncio?</p>
            </div>
            <div class="modal-footer bg-light">
                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-sm btn-ok">Excluir</a>
            </div>
        </div>
    </div>
</div>

<?php include ('includes/footer.php');?>
<script>
    // Mostrar nome do arquivo no upload (suporta múltiplos)
    $('.custom-file-input').on('change', function() {
        let files = $(this)[0].files;
        let label = $(this).next('.custom-file-label');
        if (files.length > 1) {
            label.addClass("selected").html(files.length + " arquivos selecionados");
        } else {
            label.addClass("selected").html(files[0].name);
        }
    });

    // Script para o modal de exclusão
    $('#confirm-delete').on('show.bs.modal', function(e) {
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    });
</script>
