<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Configurações de conexão com o banco de dados
$servername = "localhost"; // Endereço do servidor
$username = "digupdog_FEEDadmin"; // Nome de usuário do banco de dados
$password = "Raimundinho1"; // Senha do banco de dados
$dbname = "digupdog_FEED"; // Nome do banco de dados

try {
    // Conectar ao banco de dados usando PDO
    $pdo = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

session_start();

$results = [];
$message = "";
$errorMsg = "";

// Definições de colunas e rótulos para exibição
$columns = [
    "website_base", "website_feed", "main_category_id", "subcategory_id", 
    "subcategory_name", "subsubcategory_id", "subsubcategory_name", 
    "date_added", "last_updated", "is_active"
];
$displayColumns = [
    "Website Base", "Website Feed", "Main Category ID", "Subcategory ID", 
    "Subcategory Name", "Subsubcategory ID", "Subsubcategory Name", 
    "Date Added", "Last Updated", "Is Active"
];
$selectedColumns = $columns;
$limit = isset($_POST['resultsCount']) ? $_POST['resultsCount'] : 10;

// Redirecionamento para a edição em massa
if (isset($_POST['edit']) && isset($_POST['selected_ids'])) {
    $_SESSION['selected_ids'] = $_POST['selected_ids'];
    header('Location: websource_manager.php');
    exit();
}

// Exclusão de registros selecionados
if (isset($_POST['delete']) && isset($_POST['selected_ids'])) {
    $idsToDelete = implode(',', array_map('intval', $_POST['selected_ids']));
    $stmt = $pdo->prepare("DELETE FROM feed_data WHERE id IN ($idsToDelete)");
    $stmt->execute();
    $message = "Registros deletados com sucesso!";
}

// Busca de registros com base no termo de pesquisa
if (isset($_POST['search'])) {
    $searchTerm = $_POST['searchTerm'];
    $searchColumn = $_POST['searchColumn'];
    $customLimit = $_POST['customLimit'];
    $selectedColumns = isset($_POST['displayColumns']) ? $_POST['displayColumns'] : $columns;
    
    if ($customLimit) {
        $limit = intval($customLimit);
    } elseif ($limit == "all") {
        $limit = 9999999; // Um número grande para pegar todos os resultados
    }

    if (in_array($searchColumn, $columns)) {
        $stmt = $pdo->prepare("SELECT * FROM feed_data WHERE $searchColumn LIKE ? LIMIT $limit");
        $stmt->execute(["%$searchTerm%"]);
        $results = $stmt->fetchAll();
        if (empty($results)) {
            $message = "Nenhum registro encontrado.";
        }
    } else {
        $message = "Coluna inválida.";
    }
}

// Exclusão de um registro individual
if (isset($_GET['delete_id'])) {
    $idToDelete = intval($_GET['delete_id']);
    $stmt = $pdo->prepare("DELETE FROM feed_data WHERE id = ?");
    $stmt->execute([$idToDelete]);
    $message = "Registro deletado com sucesso!";
}

// Lógica para edição em massa
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update'])) {
    if (isset($_SESSION['selected_ids'])) {
        $selected_ids = $_SESSION['selected_ids'];
        $inQuery = implode(',', array_fill(0, count($selected_ids), '?'));

        $stmt = $pdo->prepare("SELECT * FROM feed_data WHERE id IN ($inQuery)");
        $stmt->execute($selected_ids);
        $records = $stmt->fetchAll();

        unset($_SESSION['selected_ids']);
    }

    foreach ($_POST['ids'] as $index => $id) {
        try {
            $stmt = $pdo->prepare("UPDATE feed_data SET website_base = ?, website_feed = ?, main_category_id = ?, subcategory_id = ?, subcategory_name = ?, subsubcategory_id = ?, subsubcategory_name = ?, date_added = ?, last_updated = ?, is_active = ? WHERE id = ?");
            $stmt->execute([
                $_POST['website_bases'][$index], $_POST['website_feeds'][$index], $_POST['main_category_ids'][$index],
                $_POST['subcategory_ids'][$index], $_POST['subcategory_names'][$index], $_POST['subsubcategory_ids'][$index],
                $_POST['subsubcategory_names'][$index], $_POST['date_addeds'][$index], $_POST['last_updateds'][$index],
                $_POST['is_actives'][$index], $id
            ]);
        } catch (PDOException $e) {
            $errorMsg = "Error updating record: " . $e->getMessage();
            break;
        }
    }

    if (empty($errorMsg)) {
        header('Location: websource_manager.php');
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSource Manager</title>
    <!-- Bootstrap 4 CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            document.getElementById("selectAll").addEventListener("click", function() {
                let checkboxes = document.querySelectorAll('input[name="delete_ids[]"]');
                for (let checkbox of checkboxes) {
                    checkbox.checked = this.checked;
                }
            });

            let bulkEditors = document.querySelectorAll(".bulk-edit");
            for(let editor of bulkEditors) {
                editor.addEventListener("change", function(e) {
                    let columnName = this.getAttribute("data-column");
                    let inputs = document.querySelectorAll(`input[name="${columnName}[]"], textarea[name="${columnName}[]"]`);
                    for(let input of inputs) {
                        input.value = this.value;
                    }
                });
            }
        });
    </script>
</head>
<body>

<div class="container mt-5">
    <h2 class="mb-4">Search and Edit</h2>
    <form method="post" action="websource_manager.php">
        <div class="row">
            <div class="col-md-2">
                <select name="searchColumn" class="form-control">
                    <?php foreach ($columns as $key => $column): ?>
                        <option value="<?= htmlspecialchars($column) ?>"><?= $displayColumns[$key] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <input type="text" name="searchTerm" class="form-control" placeholder="Search...">
            </div>
            <div class="col-md-2">
                <select name="resultsCount" class="form-control">
                    <option value="10">10</option>
                    <option value="20">20</option>
                    <option value="40">40</option>
                    <option value="100">100</option>
                    <option value="all">All</option>
                </select>
            </div>
            <div class="col-md-2">
                <input type="number" name="customLimit" class="form-control" placeholder="Or type...">
            </div>
            <div class="col-md-2">
                <input type="submit" name="search" value="Search" class="btn btn-primary">
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-md-12">
                <label>Select Columns to Display:</label><br>
                <?php foreach ($columns as $key => $column): ?>
                    <input type="checkbox" name="displayColumns[]" value="<?= htmlspecialchars($column) ?>" <?= in_array($column, $selectedColumns) ? 'checked' : '' ?>>
                    <?= $displayColumns[$key] ?>&nbsp;&nbsp;
                <?php endforeach; ?>
            </div>
        </div>
    </form>

    <?php if ($message): ?>
        <div class="alert alert-info mt-4">
            <?= htmlspecialchars($message) ?>
        </div>
    <?php endif; ?>

    <?php 
    if (!empty($results)) {
        echo "<div class='alert alert-info mt-4'>Total de resultados: " . count($results) . "</div>";
    }
    ?>

    <?php if (!empty($results)): ?>
        <form method='post' action='websource_manager.php' class="mt-4">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th><input type='checkbox' id='selectAll'></th>
                        <?php foreach ($selectedColumns as $selected): ?>
                            <th><?= $displayColumns[array_search($selected, $columns)] ?></th>
                        <?php endforeach; ?>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($results as $row): ?>
                        <tr>
                            <td><input type='checkbox' name='selected_ids[]' value='<?= $row['id'] ?>'></td>
                            <?php foreach ($selectedColumns as $selected): ?>
                                <td><?= htmlspecialchars($row[$selected]) ?></td>
                            <?php endforeach; ?>
                            <td>
                                <a href="websource_manager.php?delete_id=<?= $row['id'] ?>" onclick="return confirm('Are you sure?')" class="btn btn-danger btn-sm">Delete</a>
                                <button type="submit" name="edit" value="<?= $row['id'] ?>" class="btn btn-warning btn-sm">Edit</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <input type='submit' name='edit' value='Edit Selected' class="btn btn-warning">
            <input type='submit' name='delete' value='Delete Selected' class="btn btn-danger">
        </form>
    <?php endif; ?>
</div>

<?php if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit'])): ?>
    <form method="post" action="websource_manager.php">
        <table border="1">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Website Base</th>
                    <th>Website Feed</th>
                    <th>Main Category ID</th>
                    <th>Subcategory ID</th>
                    <th>Subcategory Name</th>
                    <th>Subsubcategory ID</th>
                    <th>Subsubcategory Name</th>
                    <th>Date Added</th>
                    <th>Last Updated</th>
                    <th>Is Active</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($records as $row): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($row['id']); ?><input type="hidden" name="ids[]" value="<?php echo $row['id']; ?>"></td>
                        <td><input type="text" name="website_bases[]" value="<?php echo htmlspecialchars($row['website_base']); ?>"></td>
                        <td><input type="text" name="website_feeds[]" value="<?php echo htmlspecialchars($row['website_feed']); ?>"></td>
                        <td><input type="text" name="main_category_ids[]" value="<?php echo htmlspecialchars($row['main_category_id']); ?>"></td>
                        <td><input type="text" name="subcategory_ids[]" value="<?php echo htmlspecialchars($row['subcategory_id']); ?>"></td>
                        <td><input type="text" name="subcategory_names[]" value="<?php echo htmlspecialchars($row['subcategory_name']); ?>"></td>
                        <td><input type="text" name="subsubcategory_ids[]" value="<?php echo htmlspecialchars($row['subsubcategory_id']); ?>"></td>
                        <td><input type="text" name="subsubcategory_names[]" value="<?php echo htmlspecialchars($row['subsubcategory_name']); ?>"></td>
                        <td><input type="datetime" name="date_addeds[]" value="<?php echo htmlspecialchars($row['date_added']); ?>"></td>
                        <td><input type="datetime" name="last_updateds[]" value="<?php echo htmlspecialchars($row['last_updated']); ?>"></td>
                        <td><input type="text" name="is_actives[]" value="<?php echo htmlspecialchars($row['is_active']); ?>"></td>
                        <td>
                            <button type="submit" name="delete_single" value="<?php echo $row['id']; ?>">Delete</button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <input type="submit" name="update" value="Save Changes">
    </form>
<?php endif; ?>

<!-- JS for the "Select All" functionality -->
<script>
document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("selectAll").addEventListener("click", function() {
        let checkboxes = document.querySelectorAll('input[name="selected_ids[]"]');
        for (let checkbox of checkboxes) {
            checkbox.checked = this.checked;
        }
    });
});
</script>

<!-- Optional JavaScript -->
<!-- Bootstrap 4 JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</body>
</html>
