<?php
include_once('./common.php');
$g5['title'] = "위키백과 랜덤 게시물 생성";
include_once(G5_PATH.'/_head.php');
if (!defined('_GNUBOARD_')) exit;

// Get random Wiki articles
function getRandomWikiArticles($category = '') {
    $endpoint = "https://ko.wikipedia.org/w/api.php";
    
    if (!empty($category)) {
        // 카테고리 문서 가져오기
        $params = [
            'action' => 'query',
            'format' => 'json',
            'list' => 'categorymembers',
            'cmtitle' => "Category:" . $category,
            'cmlimit' => 20,
            'cmtype' => 'page'
        ];
        
        $url = $endpoint . "?" . http_build_query($params);
        $response = json_decode(file_get_contents($url), true);
        
        if (isset($response['query']['categorymembers'])) {
            return $response;
        }
    }
    
    // 카테고리가 없거나 검색 실패시 랜덤 문서 가져오기
    $params = [
        'action' => 'query',
        'format' => 'json',
        'list' => 'random',
        'rnlimit' => 20,
        'rnnamespace' => 0
    ];
    
    $url = $endpoint . "?" . http_build_query($params);
    $response = file_get_contents($url);
    return json_decode($response, true);
}

// Get article details
function getArticleDetails($pageId) {
    $endpoint = "https://ko.wikipedia.org/w/api.php";
    $params = http_build_query([
        'action' => 'query',
        'format' => 'json',
        'pageids' => $pageId,
        'prop' => 'extracts|pageimages',
        'exintro' => true,
        'explaintext' => true,
        'pithumbsize' => 300
    ]);

    $url = $endpoint . "?" . $params;
    $response = file_get_contents($url);
    return json_decode($response, true);
}


// Get available boards
function getAvailableBoards() {
    global $g5;
    $sql = " SELECT bo_table, bo_subject FROM {$g5['board_table']} ORDER BY bo_subject ";
    $result = sql_query($sql);
    $boards = array();
    while ($row = sql_fetch_array($result)) {
        $boards[$row['bo_table']] = $row['bo_subject'];
    }
    return $boards;
}

// Save to board
function saveToBoard($title, $content, $imageUrl = '') {
    global $member, $g5;
    
    // 위키피디아 출처 및 라이선스 정보 추가
    $wikiUrl = "https://ko.wikipedia.org/wiki/" . urlencode($title);
    $attribution = '<hr><p style="font-size: 0.9em; color: #666;">이 문서는 위키백과의 <a href="'.$wikiUrl.'" target="_blank">'.$title.'</a> 문서에서 발췌했습니다. ';
    $attribution .= '원문은 <a href="https://creativecommons.org/licenses/by-sa/3.0/" target="_blank">크리에이티브 커먼즈 저작자표시-동일조건변경허락 3.0</a> 라이선스에 따라 사용할 수 있으며, 추가적인 조건이 적용될 수 있습니다. 자세한 내용은 이용 약관을 참고하십시오.
Wikipedia®는 미국 및 다른 국가에 등록되어 있는 <a href="https://www.wikimediafoundation.org/" target="_blank">Wikimedia Foundation, Inc.</a> 소유의 등록 상표입니다.</p>';
    
    if ($imageUrl) {
        $imageUrl = htmlspecialchars($imageUrl, ENT_QUOTES);
        $content = '<div style="text-align:center;"><img src="'.$imageUrl.'" alt="'.htmlspecialchars($title, ENT_QUOTES).'" style="max-width:100%;"></div>' . $content;
    }
    
    $content .= $attribution;
    
    $bo_table = $_POST['target_board'];
    $sql = "insert into {$g5['write_prefix']}{$bo_table}
            set wr_num = '-1',
                wr_reply = '',
                wr_subject = '".addslashes($title)."',
                wr_content = '".addslashes($content)."',
                wr_option = 'html1',
                mb_id = '{$member['mb_id']}',
                wr_name = '{$member['mb_nick']}',
                wr_datetime = '".G5_TIME_YMDHIS."',
                wr_last = '".G5_TIME_YMDHIS."',
                wr_ip = '{$_SERVER['REMOTE_ADDR']}'";
    sql_query($sql);
}

// Process form submission //이미지가 있는 위키 문서만 게시물로 생성됩니다. 단, 생성되는 게시물 수는 10개보다 적을 수 있습니다.
if (isset($_POST['generate'])) {
    if (!$is_admin) {
        alert("관리자만 접근 가능합니다.");
    } else {
        $category = isset($_POST['wiki_category']) ? trim($_POST['wiki_category']) : '';
        $randomArticles = getRandomWikiArticles($category);
        $count = 0;
        
        if (!empty($category) && isset($randomArticles['query']['categorymembers'])) {
            foreach ($randomArticles['query']['categorymembers'] as $article) {
                $details = getArticleDetails($article['pageid']);
                if (isset($details['query']['pages'][$article['pageid']])) {
                    $page = $details['query']['pages'][$article['pageid']];
                    if (isset($page['thumbnail']['source'])) {
                        $imageUrl = $page['thumbnail']['source'];
                        saveToBoard($page['title'], $page['extract'], $imageUrl);
                        $count++;
                    }
                }
            }
        } else if (isset($randomArticles['query']['random'])) {
            foreach ($randomArticles['query']['random'] as $article) {
                $details = getArticleDetails($article['id']);
                if (isset($details['query']['pages'][$article['id']])) {
                    $page = $details['query']['pages'][$article['id']];
                    // 이미지가 있는 문서만 처리
                    if (isset($page['thumbnail']['source'])) {
                        $imageUrl = $page['thumbnail']['source'];
                        saveToBoard($page['title'], $page['extract'], $imageUrl);
                        $count++;
                    }
                }
            }
            echo "<div class='alert alert-success'>성공적으로 {$count}개의 이미지가 포함된 게시물이 생성되었습니다.</div>";
        }
    }
}
?>

<div class="wiki-generator">
    <?php if ($is_admin) { ?>
    <form method="POST" action="">
        <div class="form-group">
            <select name="target_board" class="select_board">
                <?php
                $boards = getAvailableBoards();
                foreach ($boards as $bo_table => $bo_subject) {
                    echo '<option value="'.$bo_table.'">'.$bo_subject.'</option>';
                }
                ?>
            </select>
            <input type="text" name="wiki_category" class="input_category" placeholder="카테고리 입력 (예: 경제, 정치, 스포츠)">
        </div>
        <button type="submit" name="generate" class="btn_submit">최대 20개의 랜덤 위키 게시물 생성</button>
        <p class="wiki-notice">주제를 선택하지 않으면 무작위 문서를 가져옵니다.</p>       
        <div class="wiki-help">
            <p class="wiki-notice"><strong>카테고리 입력 방법:</strong></p>
            <p class="wiki-notice">1. <a href="https://ko.wikipedia.org/wiki/특수:분류" target="_blank">위키백과 분류 페이지</a>에서 원하는 카테고리를 검색하세요.</p>
            <p class="wiki-notice">2. 카테고리명을 정확히 복사하여 입력하세요. (예시)</p>
            <ul class="category-examples">
                <li>대한민국의_정치</li>
                <li>대한민국의_경제</li>
                <li>대한민국의_문화</li>
                <li>한국의_스포츠</li>
                <li>과학_기술</li>
            </ul>
            <p class="wiki-notice">3. 언더바(_)를 포함하여 정확히 입력해야 합니다.</p>
        </div>
    </form>
    <?php } else { ?>
    <div class="alert alert-warning">관리자만 접근 가능한 기능입니다.</div>
    <?php } ?>
    
</div>

<style>
.wiki-help {
    margin-top: 20px;
    padding: 15px;
    background: #f9f9f9;
    border: 1px solid #ddd;
    border-radius: 5px;
    text-align: left;
}

.category-examples {
    list-style: none;
    padding: 0;
    margin: 10px 0;
    color: #666;
    font-style: italic;
}

.category-examples li {
    display: inline-block;
    margin: 5px 10px;
    padding: 3px 8px;
    background: #eee;
    border-radius: 3px;
}
    
.wiki-notice {
    color: #666;
    font-size: 0.9em;
    margin-top: 10px;
    font-style: italic;
}

.input_category {
    padding: 10px;
    margin-bottom: 20px;
    margin-left: 10px;
    font-size: 14px;
    border: 1px solid #ddd;
    border-radius: 4px;
    width: 200px;
}

.form-group {
    margin-bottom: 20px;
}
.wiki-generator {
    text-align: center;
    padding: 50px;
}

.btn_submit {
    padding: 15px 30px;
    font-size: 16px;
    background: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.alert {
    padding: 15px;
    margin: 20px 0;
    border-radius: 5px;
}

.alert-success {
    background: #dff0d8;
    color: #3c763d;
    border: 1px solid #d6e9c6;
}

.select_board {
    padding: 10px;
    margin-bottom: 20px;
    font-size: 14px;
    border: 1px solid #ddd;
    border-radius: 4px;
    width: 200px;
}

.alert-warning {
    background: #fcf8e3;
    color: #8a6d3b;
    border: 1px solid #faebcc;
}

.wiki-image {
    text-align: center;
    margin: 20px 0;
}

.wiki-image img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
</style>

<?php
include_once(G5_PATH.'/tail.php');
?>