<?php
include 'categoryMap.php';

// Database connection settings
$host = 'localhost';
$db = 'digupdog_FEED';
$user = 'digupdog_FEEDadmin';
$pass = 'Raimundinho1';
$charset = 'utf8mb4';

// Connect to the database
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

// Function to check for duplicates in a specific column and count existing items, ignoring the current record being edited
function isDuplicateForEdit($pdo, $column, $value, $id = null) {
    $query = "SELECT COUNT(*) FROM content_categories WHERE $column = :value";
    if ($id !== null) {
        $query .= " AND id != :id";
    }
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':value', $value, PDO::PARAM_STR);
    if ($id !== null) {
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    }
    $stmt->execute();
    return $stmt->fetchColumn() > 0;
}

// Function to generate random titles
function generateRandomTitle($wordList, $numWords) {
    shuffle($wordList);
    return implode(' ', array_slice($wordList, 0, $numWords));
}

// Columns available for search and display
$columns = ["id", "category_name", "title_id", "title", "description_id", "description", "tag_id", "tag"];
$displayColumns = ["ID", "Category Name", "Title ID", "Title", "Description ID", "Description", "Tag ID", "Tag"];
$selectedColumns = $columns; // Default selection for displaying results

$searchPerformed = false;

// Process search query
$results = [];
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['search_term'])) {
    $search_term = "%" . $_POST['search_term'] . "%";
    $searchColumns = isset($_POST['searchColumns']) ? $_POST['searchColumns'] : $columns;

    // Defina a flag de que a busca foi realizada
    $searchPerformed = true;

    // Build the SQL query based on selected columns
    $searchClauses = [];
    foreach ($searchColumns as $column) {
        $searchClauses[] = "$column LIKE ?";
    }
    $searchQuery = implode(" OR ", $searchClauses);

    // Prepare and execute the query
    $stmt = $pdo->prepare("SELECT * FROM content_categories WHERE $searchQuery");
    $params = array_fill(0, count($searchColumns), $search_term);
    $stmt->execute($params);
    $results = $stmt->fetchAll();
}

// Função para separar por vírgula ou barra vertical e remover espaços extras
function splitInput($input) {
    return array_map('trim', preg_split('/[|,]+/', $input));
}

// Processamento do formulário: Adicionar novo conteúdo
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['title_id'])) {
    // Sanitizar e dividir os dados de entrada em arrays
    $title_ids = splitInput($_POST['title_id']);
    $titles = splitInput($_POST['title']);
    $description_ids = splitInput($_POST['description_id']);
    $descriptions = splitInput($_POST['description']);
    $tag_ids = splitInput($_POST['tag_id']);
    $tags = splitInput($_POST['tag']);
    $category_name = trim($_POST['category_name']);

    // Preencher IDs para títulos e descrições se houver apenas um valor
    if (count($title_ids) === 1) {
        $title_ids = array_fill(0, count($titles), $title_ids[0]);
    }
    if (count($description_ids) === 1) {
        $description_ids = array_fill(0, count($descriptions), $description_ids[0]);
    }

    // Preencher IDs para tags se houver apenas um valor
    if (count($tag_ids) === 1) {
        $tag_ids = array_fill(0, count($tags), $tag_ids[0]);
    }

    // Completar arrays curtos com valores padrão
    function fillArray(&$array, $size, $defaultValue = null) {
        while (count($array) < $size) {
            $array[] = $defaultValue;
        }
    }

    // Completar os arrays curtos com IDs e outros valores
    fillArray($title_ids, count($titles), 0);
    fillArray($description_ids, count($descriptions), 0);
    fillArray($tag_ids, count($tags), 0);

    // Contadores
    $titles_added = 0;
    $titles_existing = 0;
    $descriptions_added = 0;
    $descriptions_existing = 0;
    $tags_added = 0;
    $tags_existing = 0;

    try {
        // Inserir títulos na tabela
        if (!empty($titles)) {
            foreach ($titles as $index => $title) {
                if ($title && !isDuplicateForEdit($pdo, 'title', $title, 0)) {
                    $stmt = $pdo->prepare("INSERT INTO content_categories (title_id, title, category_name) VALUES (?, ?, ?)");
                    $stmt->execute([$title_ids[$index], $title, $category_name]);
                    $titles_added++;
                } else {
                    $titles_existing++;
                }
            }
        }

        // Inserir descrições na tabela
        if (!empty($descriptions)) {
            foreach ($descriptions as $index => $description) {
                if ($description && !isDuplicateForEdit($pdo, 'description', $description, 0)) {
                    $stmt = $pdo->prepare("INSERT INTO content_categories (description_id, description, category_name) VALUES (?, ?, ?)");
                    $stmt->execute([$description_ids[$index], $description, $category_name]);
                    $descriptions_added++;
                } else {
                    $descriptions_existing++;
                }
            }
        }

        // Inserir tags na tabela
        if (!empty($tags)) {
            foreach ($tags as $index => $tag) {
                if ($tag && !isDuplicateForEdit($pdo, 'tag', $tag, 0)) {
                    $stmt = $pdo->prepare("INSERT INTO content_categories (tag_id, tag, category_name) VALUES (?, ?, ?)");
                    $stmt->execute([$tag_ids[$index], $tag, $category_name]);
                    $tags_added++;
                } else {
                    $tags_existing++;
                }
            }
        }

    } catch (Exception $e) {
        echo "<p>Error: " . $e->getMessage() . "</p>";
        exit;
    }

    // Exibir resultados
    echo "
    <div class='results-container' style='max-width: 1600px; margin: 0.5rem auto;'>
        <div class='results-card' style='border-radius: 8px; background-color: #ffffff; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); transition: all 0.2s ease; overflow: hidden; padding: 0.5rem 1rem;'>
            <div class='results-header' style='background: linear-gradient(135deg, #3498db, #2ecc71); color: white; padding: 0.8rem; text-align: center; border-radius: 4px;'>
                <h2 style='font-family: Arial, sans-serif; font-size: 1.2rem;'>🎉 Content Processed Successfully! 🎉</h2>
            </div>
            <div class='results-content' style='padding: 0.5rem 0.5rem; background-color: #f4f7fc;'>

                <div class='results-section' style='border: 1px solid #2ecc71; background-color: #e9f7ef; border-radius: 6px; padding: 0.5rem; margin-bottom: 0.8rem;'>
                    <h3 style='color: #2ecc71; font-family: Arial, sans-serif; font-size: 1.1rem;'>✅ Added Items</h3>
                    <ul style='font-size: 0.9rem; list-style-type: none; padding-left: 0; line-height: 1.2; margin: 0;'>
                        <li style='margin-bottom: 0.2rem;'><i class='fas fa-file-alt' style='color: #27ae60; margin-right: 6px;'></i> <strong>Titles added:</strong> $titles_added</li>
                        <li style='margin-bottom: 0.2rem;'><i class='fas fa-align-left' style='color: #27ae60; margin-right: 6px;'></i> <strong>Descriptions added:</strong> $descriptions_added</li>
                        <li style='margin-bottom: 0.2rem;'><i class='fas fa-tags' style='color: #27ae60; margin-right: 6px;'></i> <strong>Tags added:</strong> $tags_added</li>
                    </ul>
                </div>

                <div class='results-section' style='border: 1px solid #e74c3c; background-color: #f9ebea; border-radius: 6px; padding: 0.5rem;'>
                    <h3 style='color: #e74c3c; font-family: Arial, sans-serif; font-size: 1.1rem;'>⚠️ Existing Items</h3>
                    <ul style='font-size: 0.9rem; list-style-type: none; padding-left: 0; line-height: 1.2; margin: 0;'>
                        <li style='margin-bottom: 0.2rem;'><i class='fas fa-file-alt' style='color: #c0392b; margin-right: 6px;'></i> <strong>Titles already existing:</strong> $titles_existing</li>
                        <li style='margin-bottom: 0.2rem;'><i class='fas fa-align-left' style='color: #c0392b; margin-right: 6px;'></i> <strong>Descriptions already existing:</strong> $descriptions_existing</li>
                        <li style='margin-bottom: 0.2rem;'><i class='fas fa-tags' style='color: #c0392b; margin-right: 6px;'></i> <strong>Tags already existing:</strong> $tags_existing</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    ";
}

// Form processing: Edit content
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_ids'])) {
    foreach ($_POST['edit_ids'] as $id) {
        // Collect the new values
        $new_title_id = $_POST["title_id_$id"];
        $new_title = $_POST["title_$id"];
        $new_description_id = $_POST["description_id_$id"];
        $new_description = $_POST["description_$id"];
        $new_tag_id = $_POST["tag_id_$id"];
        $new_tag = $_POST["tag_$id"];
        $new_category_name = $_POST["category_name_$id"];

        // Collect the original values for comparison
        $original_title = $_POST["original_title_$id"];
        $original_description = $_POST["original_description_$id"];
        $original_tag = $_POST["original_tag_$id"];

        // Create a base query for updating
        $update_fields = [];
        $update_values = [];

        // Check if the new title is different and not a duplicate
        if (!empty($new_title) && $new_title !== $original_title) {
            if (!isDuplicateForEdit($pdo, 'title', $new_title, $id)) {
                $update_fields[] = "title = ?";
                $update_values[] = $new_title;
            } else {
                echo "
                <div class='results-container' style='max-width: 1200px; margin: 1rem auto;'>
                    <div class='results-card' style='border-radius: 8px; background-color: #ffffff; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); padding: 1.5rem;'>
                        <div class='results-header' style='background: linear-gradient(135deg, #e74c3c, #c0392b); color: white; padding: 1rem; text-align: center;'>
                            <h2 style='font-family: Arial, sans-serif; font-size: 1.5rem;'>⚠️ Error: Duplicate Title</h2>
                        </div>
                        <div class='results-content' style='padding: 1rem;'>
                            <p style='font-size: 1.1rem; color: #e74c3c;'>The title '<strong>$new_title</strong>' already exists for another record.</p>
                        </div>
                    </div>
                </div>
                ";
                continue; // Skip this record
            }
        }

        if (!empty($new_title_id)) {
            $update_fields[] = "title_id = ?";
            $update_values[] = $new_title_id;
        }

        // Check if the new description is different and not a duplicate
        if (!empty($new_description) && $new_description !== $original_description) {
            if (!isDuplicateForEdit($pdo, 'description', $new_description, $id)) {
                $update_fields[] = "description = ?";
                $update_values[] = $new_description;
            } else {
                echo "
                <div class='results-container' style='max-width: 1200px; margin: 1rem auto;'>
                    <div class='results-card' style='border-radius: 8px; background-color: #ffffff; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); padding: 1.5rem;'>
                        <div class='results-header' style='background: linear-gradient(135deg, #e74c3c, #c0392b); color: white; padding: 1rem; text-align: center;'>
                            <h2 style='font-family: Arial, sans-serif; font-size: 1.5rem;'>⚠️ Error: Duplicate Description</h2>
                        </div>
                        <div class='results-content' style='padding: 1rem;'>
                            <p style='font-size: 1.1rem; color: #e74c3c;'>The description '<strong>$new_description</strong>' already exists for another record.</p>
                        </div>
                    </div>
                </div>
                ";
                continue; // Skip this record
            }
        }

        if (!empty($new_description_id)) {
            $update_fields[] = "description_id = ?";
            $update_values[] = $new_description_id;
        }

        // Check if the new tag is different and not a duplicate
        if (!empty($new_tag) && $new_tag !== $original_tag) {
            if (!isDuplicateForEdit($pdo, 'tag', $new_tag, $id)) {
                $update_fields[] = "tag = ?";
                $update_values[] = $new_tag;
            } else {
                echo "
                <div class='results-container' style='max-width: 1200px; margin: 1rem auto;'>
                    <div class='results-card' style='border-radius: 8px; background-color: #ffffff; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); padding: 1.5rem;'>
                        <div class='results-header' style='background: linear-gradient(135deg, #e74c3c, #c0392b); color: white; padding: 1rem; text-align: center;'>
                            <h2 style='font-family: Arial, sans-serif; font-size: 1.5rem;'>⚠️ Error: Duplicate Tag</h2>
                        </div>
                        <div class='results-content' style='padding: 1rem;'>
                            <p style='font-size: 1.1rem; color: #e74c3c;'>The tag '<strong>$new_tag</strong>' already exists for another record.</p>
                        </div>
                    </div>
                </div>
                ";
                continue; // Skip this record
            }
        }

        if (!empty($new_tag_id)) {
            $update_fields[] = "tag_id = ?";
            $update_values[] = $new_tag_id;
        }

        if (!empty($new_category_name)) {
            $update_fields[] = "category_name = ?";
            $update_values[] = $new_category_name;
        }

        // Only update if there are changes
        if (!empty($update_fields)) {
            $update_values[] = $id;  // Add ID to the end for the WHERE clause

            $sql = "UPDATE content_categories SET " . implode(", ", $update_fields) . " WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($update_values);

            echo "
            <div class='results-container' style='max-width: 1200px; margin: 1rem auto;'>
                <div class='results-card' style='border-radius: 8px; background-color: #ffffff; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); padding: 1.5rem;'>
                    <div class='results-header' style='background: linear-gradient(135deg, #2ecc71, #27ae60); color: white; padding: 1rem; text-align: center;'>
                        <h2 style='font-family: Arial, sans-serif; font-size: 1.5rem;'>🎉 Update Successful!</h2>
                    </div>
                    <div class='results-content' style='padding: 1rem;'>
                        <p style='font-size: 1.1rem; color: #34495e;'>The item with ID <strong>$id</strong> has been updated successfully. Here are the changes made:</p>
                        <div style='margin-bottom: 1rem;'>
                            <h3 style='color: #2ecc71; font-size: 1.1rem;'>✅ Fields Updated:</h3>
                            <ul style='font-size: 1rem; list-style-type: none; padding-left: 0; line-height: 1.6;'>
            ";

            foreach ($update_fields as $index => $field) {
                $field_name = ucfirst(explode(" = ", $field)[0]);
                $new_value = htmlspecialchars($update_values[$index]);
                echo "<li style='margin-bottom: 0.6rem;'><i class='fas fa-check-circle' style='color: #2ecc71; margin-right: 6px;'></i><strong>$field_name:</strong> $new_value</li>";
            }

            echo "
                            </ul>
                        </div>
            ";

            $all_fields = ['title', 'title_id', 'description', 'description_id', 'tag', 'tag_id', 'category_name'];
            $unchanged_fields = array_diff($all_fields, array_map(function($field) {
                return explode(" = ", $field)[0];
            }, $update_fields));

            if (!empty($unchanged_fields)) {
                echo "
                        <div>
                            <h3 style='color: #e74c3c; font-size: 1.1rem;'>⚠️ Fields Not Modified:</h3>
                            <ul style='font-size: 1rem; list-style-type: none; padding-left: 0; line-height: 1.6;'>
                ";
                foreach ($unchanged_fields as $field) {
                    echo "<li style='margin-bottom: 0.6rem;'><i class='fas fa-exclamation-circle' style='color: #e74c3c; margin-right: 6px;'></i><strong>" . ucfirst($field) . ":</strong> No changes</li>";
                }
                echo "
                            </ul>
                        </div>
                ";
            }

            echo "
                    </div>
                </div>
            </div>
            ";
        } else {
            echo "
            <div class='no-changes-container' style='padding: 1rem; background-color: #f9f9f9; border: 1px solid #e0e0e0; border-radius: 8px; text-align: center; max-width: 1200px; margin: 1rem auto; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);'>
                <p style='color: #e74c3c; font-size: 1.1rem; font-family: Arial, sans-serif;'>No changes detected for item with ID <strong>$id</strong>.</p>
            </div>
            ";
        }
    }
}

// Generate and insert random titles into the database
if (isset($_POST['generate_titles'])) {
    $numberOfTitles = intval($_POST['number_of_titles']);
    $wordsPerTitle = intval($_POST['words_per_title']);
    $category_name = $_POST['category_name'];
    $titles_added = 0;
    $duplicates_found = 0;

    // Use the category to get the relevant word list and title_id
    if (array_key_exists($category_name, $categoryMap)) {
        $wordList = $categoryMap[$category_name]['words'];
        $title_id = $categoryMap[$category_name]['title_id'];

        for ($i = 0; $i < $numberOfTitles; $i++) {
            $randomTitle = generateRandomTitle($wordList, $wordsPerTitle);

            // Check for duplicates before inserting
            if (!isDuplicateForEdit($pdo, 'title', $randomTitle)) {
                $stmt = $pdo->prepare("INSERT INTO content_categories (title_id, title, category_name) VALUES (?, ?, ?)");
                $stmt->execute([$title_id, $randomTitle, $category_name]);
                $titles_added++;
            } else {
                $duplicates_found++;
            }
        }

        echo "
        <div class='results-container' style='max-width: 1600px; margin: 0.5rem auto;'>
            <div class='results-card' style='border-radius: 8px; background-color: #ffffff; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); transition: all 0.2s ease; overflow: hidden; padding: 0.5rem 1rem;'>
                <div class='results-header' style='background: linear-gradient(135deg, #3498db, #2ecc71); color: white; padding: 0.8rem; text-align: center; border-radius: 4px;'>
                    <h2 style='font-family: Arial, sans-serif; font-size: 1.2rem;'>🎉 $titles_added Titles Added! $duplicates_found Duplicates Skipped! 🎉</h2>
                </div>
            </div>
        </div>";
    } else {
        echo "Invalid category selected.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search, Edit, and Generate Titles</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Global Styles */
        *, *::before, *::after {
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f7fc;
            margin: 0;
            padding: 0; /* Ajustando para garantir que o body use toda a largura */
            color: #333;
        }

        .container {
            background: linear-gradient(135deg, #ffffff, #f4f7fc);
            padding: 2rem;
            border-radius: 16px;
            width: 98%;
            max-width: 1600px;
            margin: 2rem auto;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
            transition: box-shadow 0.3s ease, background-color 0.3s ease; /* Transições suaves */
        }

        .container:hover {
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2); /* Leve aumento na sombra, sem elevação */
            background-color: #eef2f9; /* Leve mudança na cor de fundo */
            transition: box-shadow 0.3s ease, background-color 0.3s ease; /* Transições suaves */
        }

        /* Responsividade aprimorada */
        @media (max-width: 1200px) {
            .container {
                padding: 1.5rem;
                max-width: 95%; /* Ocupa até 95% da largura em telas intermediárias */
            }
        }

        @media (max-width: 768px) {
            .container {
                padding: 1rem;
                max-width: 95%; /* Garante 95% da largura no celular */
            }
        }

        h1 {
            text-align: center;
            color: #2c3e50;
            font-size: 3rem;
            margin-bottom: 2.5rem;
            font-weight: bold;
            letter-spacing: 1px;
        }

        h2 {
            font-size: 2rem;
            margin-bottom: 1.5rem;
            color: #34495e;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: bold;
            color: #34495e;
            font-size: 1.1rem;
        }

        input[type="text"], textarea, select {
            width: 100%; /* Ajusta para usar toda a largura disponível */
            padding: 0.85rem;
            margin-bottom: 1rem;
            border: 1px solid #d1d3e2;
            border-radius: 8px;
            font-size: 1.1rem;
            background-color: #f9fafc;
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
        }

        input[type="text"]:focus, textarea:focus, select:focus {
            border-color: #3498db;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.25);
            outline: none;
        }

        textarea {
            resize: vertical;
            height: 130px;
        }

        /* Botões */
        input[type="submit"], .btn-primary, .btn-secondary {
            background-color: #3498db;
            color: white;
            padding: 0.85rem 1.5rem;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 1.1rem;
            transition: background-color 0.3s ease, transform 0.3s ease, box-shadow 0.3s ease;
            width: 100%;
        }

        input[type="submit"]:hover, .btn-primary:hover {
            background-color: #2980b9;
            transform: translateY(-0.125rem);
            box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
        }

        .btn-secondary {
            background-color: #e74c3c;
        }

        .btn-secondary:hover {
            background-color: #c0392b;
            transform: translateY(-0.125rem);
            box-shadow: 0 4px 12px rgba(231, 76, 60, 0.2);
        }

        .form-section {
            margin-bottom: 3rem;
        }

        .btn-container {
            display: flex;
            justify-content: space-between;
            margin-top: 1.5rem;
        }

        .btn-container .btn-primary, .btn-container .btn-secondary {
            width: 48%;
        }

        /* Checkbox Container */
        .checkbox-container {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .checkbox-container div {
            display: flex;
            align-items: center;
            padding: 0.75rem;
            background-color: #f9fafc;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
            transition: background-color 0.3s ease;
        }

        .checkbox-container div:hover {
            background-color: #e9eef7;
        }

        input[type="checkbox"] {
            margin-right: 0.75rem;
        }

        /* Responsive Columns */
        .result-card .row {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin: 0 auto;
        }

        .result-card .col-container {
            flex: 1 1 300px;
            max-width: 100%;
            padding: 1rem;
            background-color: #f9fafc;
            border-radius: 8px;
            box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
            transition: background-color 0.3s ease, box-shadow 0.3s ease;
        }

        @media (max-width: 768px) {
            .result-card .col-container {
                width: 98%;
                margin-bottom: 1rem;
                margin-left: auto;
                margin-right: auto;
            }
        }

        .result-card .col-container:hover {
            background-color: #ecf0f1;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
            transform: translateY(-0.25rem);
        }

        @media (max-width: 768px) {
            .results-container {
                padding: 1rem;
                max-width: 95%; /* Garante 95% da largura no celular */
            }

            .results-card {
                padding: 1rem;
                max-width: 100%; /* Ocupa toda a largura em telas menores */
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* Sombra mais sutil */
            }

            .results-content {
                padding: 1.5rem; /* Reduzido o padding interno para telas pequenas */
            }
        }
    </style>
</head>
<body>

<div class="container">
    <h1>Search, Edit, and Generate Titles</h1>

    <!-- Form Section -->
    <h2>Search and Edit</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" class="form-section">
        <div class="form-group">
            <label for="search_term">Search by Term:</label>
            <input type="text" id="search_term" name="search_term" placeholder="Enter search term" required>
        </div>

        <div class="form-group">
            <label for="searchColumns">Select Columns for Search:</label>
            <div class="checkbox-container">
                <?php foreach ($columns as $key => $column): ?>
                    <div>
                        <input type="checkbox" name="searchColumns[]" value="<?= htmlspecialchars($column) ?>" id="<?= $column ?>">
                        <label for="<?= $column ?>"><?= $displayColumns[$key] ?></label>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <input type="submit" value="Search" class="btn-primary">
    </form>

<?php if ($searchPerformed && empty($results)): ?>
    <div class="no-results-container" style="padding: 1.5rem; background-color: #fce4e4; border: 1px solid #e74c3c; border-radius: 8px; text-align: center; max-width: 1200px; margin: 1.5rem auto; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);">
        <i class="fas fa-search" style="font-size: 2rem; color: #e74c3c; margin-bottom: 0.5rem;"></i>
        <p style="color: #e74c3c; font-size: 1.3rem; font-weight: bold; margin-top: 0.5rem;">No results found</p>
        <p style="font-size: 1rem; color: #e74c3c;">Please try another search term.</p>
    </div>
<?php elseif (!empty($results)): ?>
    <!-- Exibir os resultados da busca -->
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" class="form-section">
        <div class="result-card">
            <h2 style="color: #3498db; text-align: center;">🔍 Search Results</h2>
            <div class="row">
                <?php foreach ($results as $row): ?>
                    <div class="col-container" style="background-color: #f9fafc; border: 1px solid #d1d3e2; border-radius: 10px; padding: 1.5rem; margin-bottom: 1.5rem; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); transition: box-shadow 0.3s ease, transform 0.3s ease;">
                        <h4 style="color: #2c3e50;">📝 ID: <span style="color: #3498db;"><?php echo $row['id']; ?></span></h4>
                        
                        <label for="edit_ids_<?php echo $row['id']; ?>">Select:</label>
                        <input type="checkbox" name="edit_ids[]" value="<?php echo $row['id']; ?>">

                        <label for="title_id_<?php echo $row['id']; ?>">📑 Title ID:</label>
                        <input type="text" name="title_id_<?php echo $row['id']; ?>" value="<?php echo htmlspecialchars($row['title_id']); ?>" style="width: 100%; padding: 0.5rem; margin-bottom: 0.75rem;">

                        <label for="title_<?php echo $row['id']; ?>">📄 Title:</label>
                        <input type="text" name="title_<?php echo $row['id']; ?>" value="<?php echo htmlspecialchars($row['title']); ?>" style="width: 100%; padding: 0.5rem; margin-bottom: 0.75rem;">
                        <input type="hidden" name="original_title_<?php echo $row['id']; ?>" value="<?php echo htmlspecialchars($row['title']); ?>">

                        <label for="description_id_<?php echo $row['id']; ?>">📘 Description ID:</label>
                        <input type="text" name="description_id_<?php echo $row['id']; ?>" value="<?php echo htmlspecialchars($row['description_id']); ?>" style="width: 100%; padding: 0.5rem; margin-bottom: 0.75rem;">

                        <label for="description_<?php echo $row['id']; ?>">🖋️ Description:</label>
                        <input type="text" name="description_<?php echo $row['id']; ?>" value="<?php echo htmlspecialchars($row['description']); ?>" style="width: 100%; padding: 0.5rem; margin-bottom: 0.75rem;">
                        <input type="hidden" name="original_description_<?php echo $row['id']; ?>" value="<?php echo htmlspecialchars($row['description']); ?>">

                        <label for="tag_id_<?php echo $row['id']; ?>">🏷️ Tag ID:</label>
                        <input type="text" name="tag_id_<?php echo $row['id']; ?>" value="<?php echo htmlspecialchars($row['tag_id']); ?>" style="width: 100%; padding: 0.5rem; margin-bottom: 0.75rem;">

                        <label for="tag_<?php echo $row['id']; ?>">🏷️ Tag:</label>
                        <input type="text" name="tag_<?php echo $row['id']; ?>" value="<?php echo htmlspecialchars($row['tag']); ?>" style="width: 100%; padding: 0.5rem; margin-bottom: 0.75rem;">
                        <input type="hidden" name="original_tag_<?php echo $row['id']; ?>" value="<?php echo htmlspecialchars($row['tag']); ?>">

                        <label for="category_name_<?php echo $row['id']; ?>">📂 Category:</label>
                        <select name="category_name_<?php echo $row['id']; ?>" style="width: 100%; padding: 0.5rem;">
                            <option value="politics" <?php echo ($row['category_name'] === 'politics') ? 'selected' : ''; ?>>Politics</option>
                            <option value="sports" <?php echo ($row['category_name'] === 'sports') ? 'selected' : ''; ?>>Sports</option>
                            <option value="news" <?php echo ($row['category_name'] === 'news') ? 'selected' : ''; ?>>News</option>
                            <option value="entertainment" <?php echo ($row['category_name'] === 'entertainment') ? 'selected' : ''; ?>>Entertainment</option>
                            <option value="technology" <?php echo ($row['category_name'] === 'technology') ? 'selected' : ''; ?>>Technology</option>
                        </select>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="btn-container">
            <input type="submit" value="Edit Selected" class="btn-primary" style="width: 48%; background-color: #2ecc71;">
            <input type="reset" value="Clear Selection" class="btn-secondary" style="width: 48%; background-color: #e74c3c;">
        </div>
    </form>
<?php endif; ?>


    <!-- Form to Add New Content -->
    <h2>Add New Content</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" class="form-section">
        <div class="form-group">
            <label for="title_id">Title ID (separate multiple values with commas):</label>
            <input type="text" id="title_id" name="title_id" placeholder="e.g., 1, 2, 3">
        </div>

        <div class="form-group">
            <label for="title">Title (separate multiple values with commas):</label>
            <input type="text" id="title" name="title" placeholder="e.g., Donald Trump, Joe Biden">
        </div>

        <div class="form-group">
            <label for="description_id">Description ID (separate multiple values with commas):</label>
            <input type="text" id="description_id" name="description_id" placeholder="e.g., 1, 2, 3">
        </div>

        <div class="form-group">
            <label for="description">Description (separate multiple values with commas):</label>
            <textarea id="description" name="description" placeholder="e.g., President of the USA, Prime Minister of Canada"></textarea>
        </div>

        <div class="form-group">
            <label for="tag_id">Tag ID (separate multiple values with commas):</label>
            <input type="text" id="tag_id" name="tag_id" placeholder="e.g., 1, 2, 3">
        </div>

        <div class="form-group">
            <label for="tag">Tag (separate multiple values with commas):</label>
            <input type="text" id="tag" name="tag" placeholder="e.g., Politics, Economy, Sports">
        </div>

        <div class="form-group">
            <label for="category_name">Category Name:</label>
            <select id="category_name" name="category_name" required>
                <option value="politics">Politics</option>
                <option value="sports">Sports</option>
                <option value="news">News</option>
                <option value="entertainment">Entertainment</option>
                <option value="technology">Technology</option>
            </select>
        </div>

        <input type="submit" value="Add Content" class="btn-primary">
    </form>

<!-- Form to Generate Random Titles -->
<h2 style="color: #34495e; font-size: 2.2rem; margin-bottom: 1.5rem;">Generate Random Titles</h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" class="form-section">
    <div class="form-group">
        <label for="number_of_titles" style="font-size: 1.2rem; color: #34495e;">Number of Titles to Generate:</label>
        <input type="number" id="number_of_titles" name="number_of_titles" min="1" max="1000000" value="5000" required
               style="width: 100%; padding: 0.75rem; font-size: 1.1rem; border: 1px solid #d1d3e2; border-radius: 6px; background-color: #f9fafc;">
        <small style="color: #7f8c8d;">Choose how many random titles you want to generate.</small>
    </div>

    <div class="form-group">
        <label for="words_per_title" style="font-size: 1.2rem; color: #34495e;">Number of Words per Title:</label>
        <input type="number" id="words_per_title" name="words_per_title" min="1" max="5" value="3" required
               style="width: 100%; padding: 0.75rem; font-size: 1.1rem; border: 1px solid #d1d3e2; border-radius: 6px; background-color: #f9fafc;">
        <small style="color: #7f8c8d;">Select how many words should be in each title (e.g., 1 to 5 words).</small>
    </div>

    <div class="form-group">
        <label for="category_name" style="font-size: 1.2rem; color: #34495e;">Category Name:</label>
        <select id="category_name" name="category_name" required
                style="width: 100%; padding: 0.75rem; font-size: 1.1rem; border: 1px solid #d1d3e2; border-radius: 6px; background-color: #f9fafc;">
            <option value="" disabled selected>Select a category</option>
            <?php 
                foreach ($categoryMap as $key => $value) {
                    echo "<option value='$key'>" . ucfirst($key) . "</option>";
                }
            ?>
        </select>
        <small style="color: #7f8c8d;">Choose a category for the titles (e.g., Politics, Sports).</small>
    </div>

    <input type="submit" name="generate_titles" value="Generate Titles"
           style="background-color: #3498db; color: white; padding: 0.85rem; border: none; border-radius: 6px; cursor: pointer; font-size: 1.2rem; width: 100%; margin-top: 1rem; transition: background-color 0.3s ease, box-shadow 0.3s ease;">
</form>

<!-- Hover effect for the button -->
<style>
    input[type="submit"]:hover {
        background-color: #2980b9;
        box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
    }
</style>


</div>

</body>
</html>
