<?php
// Código PHP para processar o formulário quando submetido
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $host = 'localhost';
    $db = 'digupdog_FEED';
    $user = 'digupdog_FEEDadmin';
    $pass = 'Raimundinho1';
    $charset = 'utf8mb4';

    // Configuração da conexão PDO
    $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) {
        die("Database connection failed: " . $e->getMessage());
    }

    // Recebe os dados do formulário
    $websiteFeeds = $_POST['websiteFeeds'];

    // Função para extrair o domínio base da URL
    function getBaseURL($url) {
        $parsedUrl = parse_url($url);
        if (isset($parsedUrl['scheme']) && isset($parsedUrl['host'])) {
            return $parsedUrl['scheme'] . '://' . $parsedUrl['host'];
        }
        return null;
    }

    // Separar URLs por nova linha ou vírgula
    $feedsArray = preg_split('/[\r\n,]+/', $websiteFeeds, -1, PREG_SPLIT_NO_EMPTY);

    $successCount = 0;
    $errorCount = 0;
    $errorMessages = [];

    foreach ($feedsArray as $websiteFeed) {
        $websiteFeed = trim($websiteFeed); // Remove espaços em branco

        // Extrai o website base automaticamente
        $websiteBase = getBaseURL($websiteFeed);

        // Verifica se a extração do website base foi bem-sucedida
        if ($websiteBase === null) {
            $errorCount++;
            $errorMessages[] = "Failed to extract the base URL from: $websiteFeed";
            continue;
        }

        $mainCategoryId = $_POST['mainCategoryId'];
        $subcategoryId = $_POST['subcategoryId'];
        $subcategoryName = $_POST['subcategoryName'];
        $subsubcategoryId = $_POST['subsubcategoryId'];
        $subsubcategoryName = $_POST['subsubcategoryName'];

        try {
            // Verifica se o website_base e website_feed já existem
            $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM feed_data WHERE website_base = :website_base AND website_feed = :website_feed");
            $stmtCheck->execute([
                'website_base' => $websiteBase,
                'website_feed' => $websiteFeed
            ]);

            $count = $stmtCheck->fetchColumn();

            if ($count > 0) {
                $errorCount++;
                $errorMessages[] = "Duplicate entry for feed: $websiteFeed.";
                continue; // Pula para o próximo feed
            }

            // Insere os dados na tabela feed_data
            $stmt = $pdo->prepare("INSERT INTO feed_data (website_base, website_feed, main_category_id, subcategory_id, subcategory_name, subsubcategory_id, subsubcategory_name) VALUES (:website_base, :website_feed, :main_category_id, :subcategory_id, :subcategory_name, :subsubcategory_id, :subsubcategory_name)");
            $stmt->execute([
                'website_base' => $websiteBase,
                'website_feed' => $websiteFeed,
                'main_category_id' => $mainCategoryId,
                'subcategory_id' => $subcategoryId,
                'subcategory_name' => $subcategoryName,
                'subsubcategory_id' => $subsubcategoryId,
                'subsubcategory_name' => $subsubcategoryName
            ]);

            $successCount++;
        } catch (\PDOException $e) {
            $errorCount++;
            $errorMessages[] = "Failed to add feed: $websiteFeed. Error: " . $e->getMessage();
        }
    }

    if ($successCount > 0) {
        $successMessage = "$successCount feed(s) added successfully!";
    }
    if ($errorCount > 0) {
        $errorMessage = implode('<br>', $errorMessages);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Website Feed Manager</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            padding: 20px;
        }
        .form-section {
            margin-bottom: 20px;
        }
        .form-section label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-section input[type="text"],
        .form-section textarea,
        .form-section select {
            width: 100%;
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .button {
            padding: 10px 20px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .button:hover {
            background-color: #218838;
        }
        .checkbox-container {
            margin-top: 10px;
        }
        .checkbox-label {
            margin-right: 15px;
        }
        .message {
            margin-bottom: 20px;
            font-weight: bold;
        }
        .success {
            color: green;
        }
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <h1>Website Feed Manager</h1>

    <?php if (!empty($successMessage)): ?>
        <div class="message success"><?php echo $successMessage; ?></div>
    <?php endif; ?>
    
    <?php if (!empty($errorMessage)): ?>
        <div class="message error"><?php echo $errorMessage; ?></div>
    <?php endif; ?>

    <form id="feedForm" method="post">
        <!-- Section for adding website URL and base URL -->
        <div class="form-section">
            <label for="websiteFeeds">Enter Website Feed URLs (separated by commas or new lines):</label>
            <textarea id="websiteFeeds" name="websiteFeeds" placeholder="https://example.com/rss, https://example2.com/feed" rows="4" required></textarea>
        </div>

        <!-- Section for selecting main category -->
        <div class="form-section">
            <label for="mainCategoryId">Select Main Category ID (1, 2, 3, ...):</label>
            <select id="mainCategoryId" name="mainCategoryId">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
                <!-- Continue adding more main categories as needed -->
            </select>
        </div>

        <!-- Section for selecting subcategories -->
        <div class="form-section">
            <label for="subcategoryId">Select Subcategory ID:</label>
            <select id="subcategoryId" name="subcategoryId">
                <option value="1">1 - Sport</option>
                <option value="2">2 - Entertainment</option>
                <option value="3">3 - NSFW</option>
                <!-- Add more subcategories as needed -->
            </select>
        </div>

        <!-- Section for entering subcategory name -->
        <div class="form-section">
            <label for="subcategoryName">Enter Subcategory Name:</label>
            <input type="text" id="subcategoryName" name="subcategoryName" placeholder="e.g., Sport" required>
        </div>

        <!-- Section for selecting sub-subcategories -->
        <div class="form-section">
            <label for="subsubcategoryId">Select Sub-Subcategory ID:</label>
            <select id="subsubcategoryId" name="subsubcategoryId">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <!-- Add more sub-subcategories as needed -->
            </select>
        </div>

        <!-- Section for entering sub-subcategory name -->
        <div class="form-section">
            <label for="subsubcategoryName">Enter Sub-Subcategory Name:</label>
            <input type="text" id="subsubcategoryName" name="subsubcategoryName" placeholder="e.g., Movies" required>
        </div>

        <!-- Button to submit the form -->
        <div class="form-section">
            <button type="submit" class="button">Add Feed</button>
        </div>
    </form>
</body>
</html>
