<?php

/**
 * Author: Kıvanç Ağaoğlu
 * Düzenleme: Spintax Fix by Onur
 */

require_once __DIR__ . '/functions.php';

// Spintax parser fonksiyonları
if (!function_exists('parseSpintax')) {
    function parseSpintax($text)
    {
        return preg_replace_callback(
            '/\{([^{}]+)\}/',
            function ($matches) {
                $parts = explode('|', $matches[1]);
                return $parts[array_rand($parts)];
            },
            $text
        );
    }

    function fullSpin($text)
    {
        while (preg_match('/\{[^{}]+\}/', $text)) {
            $text = parseSpintax($text);
        }
        return $text;
    }
}

if ($_POST) {

    $titlesRaw = $_POST['titles'];
    $contentsRaw = $_POST['contents'];
    $beforeRaw = $_POST['before_html'];
    $afterRaw = $_POST['after_html'];

    $urls = explode(PHP_EOL, trim($_POST['urls']));

    $postList = [];

    foreach ($urls as $url) {

        $title = fullSpin($titlesRaw);
        $content = fullSpin($contentsRaw);
        $before = fullSpin($beforeRaw);
        $after = fullSpin($afterRaw);

        $postList[] = [
            'title' => $title,
            'content' => htmlspecialchars($before . '<br>' . $content . '<br>' . $after),
            'url' => trim($url),
        ];
    }

    $response = [
        'status' => 'success',
        'message' => 'Gönderime hazır',
        'data' => [
            'postList' => $postList,
            'report_date' => date('d.m.Y H:i:s'),
        ]
    ];

    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

?>
<!doctype html>
<html lang="tr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="robots" content="noindex">

    <script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

    <title>Multi Article</title>
</head>
<body>

<script>
$(document).ready(function () {

    $('button[name="submit"]').on('click', function () {

        $('#posts_tbody').html('');
        $('#posts_urls_tbody').html('');

        $.ajax({
            url: 'index.php',
            type: 'POST',
            data: new FormData($('form')[0]),
            processData: false,
            contentType: false,
            success: function (response) {

                if (response.status === 'success') {

                    response.data.postList.forEach(function (post) {
                        $('#posts_tbody').append(`
                            <tr>
                                <td>${post.url}</td>
                                <td>${post.title}</td>
                                <td>${post.content}</td>
                                <td>
                                    <form method="post" action="sender.php">
                                        <input type="hidden" name="title" value="${post.title}">
                                        <input type="hidden" name="content" value="${post.content}">
                                        <input type="hidden" name="url" value="${post.url}">
                                        <button type="button" class="btn btn-primary post-data">Gönder</button>
                                    </form>
                                </td>
                            </tr>
                        `);
                    });

                    // Tek tek gönderme
                    $('.post-data').on('click', function () {
                        let button = $(this);
                        button.attr('disabled', true).html('Gönderiliyor...');
                        var form = $(this).closest('form')[0];

                        $.ajax({
                            url: 'sender.php',
                            type: 'POST',
                            data: new FormData(form),
                            processData: false,
                            contentType: false,
                            success: function (response) {
                                if (response.status === 'success') {

                                    button
                                        .html('Gönderildi')
                                        .removeClass('btn-primary')
                                        .addClass('btn-success');

                                    $('#posts_urls_tbody').append(`
                                        <tr>
                                            <td><a href="${response.post_url}" target="_blank">${response.post_url}</a></td>
                                        </tr>
                                    `);

                                } else {
                                    button
                                        .html('Gönderilemedi')
                                        .removeClass('btn-primary')
                                        .addClass('btn-danger');
                                }
                            }
                        });
                    });

                    // -------------------------------
                    //    TOPLU GÖNDERME – DÜZELTİLMİŞ
                    // -------------------------------
                    let delay = 0;

                    $('#submit_all').one('click', function () {

                        let allBtn = $(this);
                        allBtn.attr('disabled', true).text('Gönderiliyor...');

                        $('.post-data').each(function () {
                            let button = $(this);

                            setTimeout(function () {
                                button.click();
                            }, delay);

                            delay += 1200;
                        });
                    });
                }
            }
        });
    });
});
</script>

<div class="container text-center">
    <hr>
    <h4>Makale Oluşturucu | <a href="reports.php">Raporlar</a> | <a href="posts.php">Postlar</a></h4>
    <hr>

    <form action="" id="file_form" enctype="multipart/form-data">

        <div class="form-group col-6 mx-auto">
            <label><strong>Başlıklar</strong></label>
            <input type="text" name="titles" class="form-control" value="{a|b|c}">
        </div>

        <div class="form-group col-6 mx-auto">
            <label><strong>Html Öncesi</strong></label>
            <textarea name="before_html" class="form-control" rows="5"></textarea>
        </div>

        <div class="form-group col-6 mx-auto">
            <label><strong>Html Sonrası</strong></label>
            <textarea name="after_html" class="form-control" rows="5"></textarea>
        </div>

        <div class="form-group col-6 mx-auto">
            <label><strong>İçerikler</strong></label>
            <textarea name="contents" class="form-control" rows="5">{aa|bb|cc}</textarea>
        </div>

        <div class="form-group col-6 mx-auto">
            <label><strong>Site Adresleri</strong> <em>(Her satırda bir URL, sonda / olmasın)</em></label>
            <textarea name="urls" class="form-control" rows="5"></textarea>
        </div>

        <button type="button" class="btn btn-info" name="submit" value="1">Ekle</button>
    </form>

    <table class="table table-striped table-hover text-center mt-4" id="posts_table">
        <thead>
            <tr>
                <th>Adres</th>
                <th>Başlık</th>
                <th>İçerik</th>
                <th><button type="button" id="submit_all" class="btn btn-primary">Tümünü Ekle</button></th>
            </tr>
        </thead>
        <tbody id="posts_tbody"></tbody>
    </table>

    <hr>

    <table class="table table-striped table-hover text-center" id="post_urls_table">
        <thead>
            <tr><th>Gönderilen Linkler</th></tr>
        </thead>
        <tbody id="posts_urls_tbody"></tbody>
    </table>
</div>

</body>
</html>
