<?php
include_once('./common.php');
$g5['title'] = "여행지 추천 | TOP PLACES TO TRAVEL";
include_once(G5_PATH.'/_head.php');
if (!defined('_GNUBOARD_')) exit;

// Add debug function
function debugLog($message, $data = null) {
    error_log($message . ($data ? ': ' . print_r($data, true) : ''));
}

function getWikiCategories($parentCategory) {    
    $endpoint = "https://ko.wikipedia.org/w/api.php";
    $params = [
        'action' => 'query',
        'format' => 'json',
        'list' => 'categorymembers',
        'cmtitle' => "분류:" . $parentCategory,
        'cmlimit' => 10,
        'cmtype' => 'page',  // Changed to only get pages
        'cmnamespace' => 0,  // Only get main namespace
        'origin' => '*',
        'formatversion' => '2'
    ];
    
    $url = $endpoint . "?" . http_build_query($params);
    debugLog("Requesting categories URL", $url);
    
    $opts = [
        'http' => [
            'method' => 'GET',
            'header' => [
                'User-Agent: TravelApp/1.0 (Travel Information Service)',
                'Accept: application/json',
                'Accept-Charset: UTF-8'
            ]
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false
        ]
    ];
    
    $context = stream_context_create($opts);
    
    try {
        $response = file_get_contents($url, false, $context);
        if ($response === false) {
            debugLog("API Request Failed", error_get_last());
            return [];
        }
        
        $data = json_decode($response, true);
        $pages = [];
        
        if (isset($data['query']['categorymembers'])) {
            foreach ($data['query']['categorymembers'] as $member) {
                if (!isset($member['ns']) || $member['ns'] === 0) {
                    $pages[] = $member['title'];
                }
            }
        }
        
        debugLog("Found pages", $pages);
        return $pages;
    } catch (Exception $e) {
        debugLog("Exception occurred", $e->getMessage());
        return [];
    }
}


// Get destinations from Wikipedia category
function getDestinationsFromCategory($category) {
    $endpoint = "https://ko.wikipedia.org/w/api.php";
    $params = [
        'action' => 'query',
        'format' => 'json',
        'list' => 'categorymembers',  // Changed from 'titles' to 'list'
        'cmtitle' => "분류:" . $category,  // Changed to use cmtitle
        'cmtype' => 'page',
        'cmlimit' => 10,
        'prop' => 'extracts|pageimages|info|coordinates',
        'exintro' => true,
        'explaintext' => true,
        'pithumbsize' => 800,
        'inprop' => 'url',
        'origin' => '*',
        'formatversion' => '2'
    ];
    
    $url = $endpoint . "?" . http_build_query($params);
    debugLog("Requesting destinations URL", $url);
    
    $opts = [
        'http' => [
            'method' => 'GET',
            'header' => [
                'User-Agent: TravelApp/1.0',
                'Accept: application/json'
            ]
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false
        ]
    ];
    
    $context = stream_context_create($opts);
    
    try {
        $response = file_get_contents($url, false, $context);
        if ($response === false) {
            debugLog("Failed to get destinations", error_get_last());
            return [];
        }
        
        $data = json_decode($response, true);
        $destinations = [];
        
        if (isset($data['query']['categorymembers'])) {
            foreach ($data['query']['categorymembers'] as $member) {
                if (isset($member['pageid'])) {
                    $details = getDestinationDetails($member['pageid']);
                    if ($details && !empty($details['extract'])) {
                        $destinations[] = $details;
                    }
                }
            }
        }
        
        return $destinations;
    } catch (Exception $e) {
        debugLog("Exception in getDestinationsFromCategory", $e->getMessage());
        return [];
    }
}

function getDestinationDetails($pageId) {
    $endpoint = "https://ko.wikipedia.org/w/api.php";
    $params = [
        'action' => 'query',
        'format' => 'json',
        'pageids' => $pageId,
        'prop' => 'extracts|pageimages|videoinfo|audioinfo|info|coordinates',
        'exintro' => true,
        'explaintext' => true,
        'pithumbsize' => 800,
        'inprop' => 'url',
        'viprop' => 'url|mime',
        'aiprop' => 'url|mime'
    ];

    $url = $endpoint . "?" . http_build_query($params);
    $response = json_decode(file_get_contents($url), true);
    
    if (isset($response['query']['pages'][$pageId])) {
        $page = $response['query']['pages'][$pageId];
        return [
            'title' => $page['title'],
            'extract' => isset($page['extract']) ? $page['extract'] : '',
            'image' => isset($page['thumbnail']['source']) ? $page['thumbnail']['source'] : '',
            'coordinates' => isset($page['coordinates']) ? $page['coordinates'] : null,
            'url' => isset($page['fullurl']) ? $page['fullurl'] : '',
            'video' => isset($page['videoinfo']) ? $page['videoinfo'] : null,
            'audio' => isset($page['audioinfo']) ? $page['audioinfo'] : null
        ];
    }
    return null;
}

$regions = [
    'korea' => [
        'title' => '한국 팔도 여행지',
        'subregions' => [
            'seoul' => ['title' => '서울/경기', 'categories' => ['서울특별시의_관광지', 
                '경기도의_관광지',
                '인천광역시의_관광지',
                '수원시의_관광지',
                '서울의_고궁',
                '서울의_박물관']],
            'gangwon' => ['title' => '강원도', 'categories' => ['강원특별자치도의_관광지',
                '강원도의_국립공원',
                '강원도의_스키장',
                '속초시의_관광지',
                '강릉시의_관광지']],
            'chungcheong' => ['title' => '충청도', 'categories' => [
    '충청남도의_관광지',
    '충청북도의_관광지',
    '대전광역시의_관광지',
    '공주시의_관광지',
    '부여의_관광지',
    '단양의_관광지',
    '충청도의_국립공원'
]],
'gyeongsang' => ['title' => '경상도', 'categories' => [
    '경상북도의_관광지',
    '경상남도의_관광지',
    '부산광역시의_관광지',
    '대구광역시의_관광지',
    '경주시의_관광지',
    '울산광역시의_관광지',
    '통영시의_관광지',
    '안동시의_관광지'
]],
'jeolla' => ['title' => '전라도', 'categories' => [
    '전라북도의_관광지',
    '전라남도의_관광지',
    '광주광역시의_관광지',
    '전주시의_관광지',
    '여수시의_관광지',
    '순천시의_관광지',
    '목포시의_관광지'
]],
'jeju' => ['title' => '제주도', 'categories' => [
    '제주특별자치도의_관광지',
    '제주도의_해변',
    '제주도의_오름',
    '제주도의_박물관',
    '서귀포시의_관광지',
    '한라산_국립공원'
]]
        ]
    ],
    'usa' => [
        'title' => '미국 주별 여행지',
        'subregions' => [
            'northeast' => ['title' => '북동부', 'categories' => ['뉴욕의_관광지',
                '메사추세츠의_관광지',
                '보스턴의_관광지',
                '뉴욕의_박물관',
                '뉴욕의_공원',
                '맨해튼의_관광지',                
            '펜실베이니아의_관광지',
            '뉴저지의_관광지']],
            'midwest' => ['title' => '중서부', 'categories' => ['일리노이의_관광지',
            '미시간의_관광지',
            '시카고의_관광지',
            '오하이오의_관광지',
            '미네소타의_관광지']],
            'south' => ['title' => '남부', 'categories' => [ 
        '마이애미',                            // 도시명(개별 명소는 문서 내에서 확인)
        '올랜도',                              // 도시명(개별 명소는 문서 내에서 확인)
        '뉴올리언스',                          // 도시명(개별 명소는 문서 내에서 확인)
        '내슈빌',                              // 도시명(개별 명소는 문서 내에서 확인)
        '애틀랜타',                            // 도시명(개별 명소는 문서 내에서 확인)
        '월트 디즈니 월드 리조트',             // 실제 문서명        
        '월드 오브 코카콜라',                  // 실제 문서명
        'CNN 센터',                            // 실제 문서명
        '그레이트 스모키 산맥 국립공원',        // 실제 문서명
        '스톤 마운틴',                         // 실제 문서명
        '키웨스트'           
]],
            'west' => ['title' => '서부', 'categories' => ['캘리포니아의_관광지',
            '하와이의_관광지',
            '라스베가스의_관광지',
            '로스앤젤레스의_관광지',
            '샌프란시스코의_관광지']]
        ]
    ],
    'europe' => [
    'title' => '유럽 국가별 여행지',
    'subregions' => [
        'western' => ['title' => '서유럽', 'categories' => [
            '프랑스의_관광지',
            '독일의_관광지',
            '영국의_관광지',
            '파리의_박물관',
            '런던의_관광지',
            '베를린의_관광지',
            '암스테르담의_관광지',
            '스위스의_관광지'
        ]],
        'southern' => ['title' => '남유럽', 'categories' => [
            '이탈리아의_관광지',
            '스페인의_관광지',
            '로마의_관광지',
            '베네치아의_관광지',
            '바르셀로나의_관광지',
            '마드리드의_관광지',
            '그리스의_관광지',
            '산토리니의_관광지'
        ]],
        'northern' => ['title' => '북유럽', 'categories' => [
            '노르웨이의_관광지',
            '스웨덴의_관광지',
            '덴마크의_관광지',
            '핀란드의_관광지',
            '아이슬란드의_관광지',
            '오슬로의_관광지',
            '스톡홀름의_관광지',
            '코펜하겐의_관광지'
        ]],
        'eastern' => ['title' => '동유럽', 'categories' => [
            '체코의_관광지',
            '폴란드의_관광지',
            '프라하의_관광지',
            '부다페스트의_관광지',
            '크로아티아의_관광지',
            '오스트리아의_관광지',
            '비엔나의_관광지',
            '부쿠레슈티의_관광지'
        ]]
    ]
],
    'world' => [
    'title' => '세계 여행지',
    'subregions' => [
        'asia' => ['title' => '아시아', 'categories' => [
            '대한민국의_세계유산',
            '중국의_세계유산',
            '일본의_세계유산',
            '태국의_세계유산',
            '베트남의_세계유산'
        ]],
        'oceania' => ['title' => '오세아니아', 'categories' => [
            '호주의_세계유산',
    '뉴질랜드의_세계유산',
    '시드니의_관광지',
    '멜버른의_관광지',
    '오클랜드의_관광지',
    '골드코스트의_관광지',
    '퍼스의_관광지'
        ]],
        'middleeast' => ['title' => '중동', 'categories' => [
            '두바이의_관광지',
    '터키의_세계유산',
    '이스라엘의_세계유산',
    '이스탄불의_관광지',
    '아부다비의_관광지',
    '카타르의_관광지',
    '사우디아라비아의_관광지'
        ]],
        'africa' => ['title' => '아프리카', 'categories' => [
            '이집트의_세계유산',
    '모로코의_세계유산',
    '남아프리카공화국의_관광지',
    '케냐의_국립공원',
    '탄자니아의_관광지',
    '카이로의_관광지',
    '피라미드_관광지',
    '사하라_사막_관광',
    '빅토리아_폭포',
    '세렝게티_국립공원'
        ]],
        'southamerica' => ['title' => '남미', 'categories' => [
            '브라질의_세계유산',
    '페루의_세계유산',
    '아르헨티나의_세계유산',
    '마추픽추_관광지',
    '리우데자네이루의_관광지',
    '이과수_폭포',
    '칠레의_관광지',
    '콜롬비아의_관광지',
    '우유니_소금사막',
    '아마존_열대우림'
        ]]
    ]
]
];

// Add error logging
if (empty($regions['korea']['categories'])) {
    error_log('Failed to fetch Korean categories');
}

if (isset($_POST['region']) && isset($_POST['subregion'])) {
    $destinations = [];
    $selected_region = $_POST['region'];
    $selected_subregion = $_POST['subregion'];
    
    if (isset($regions[$selected_region]['subregions'][$selected_subregion])) {
        $categories = $regions[$selected_region]['subregions'][$selected_subregion]['categories'];
        foreach ($categories as $category) {
            $category_destinations = getDestinationsFromCategory($category);
            // Filter destinations to include only those with images
            $category_destinations = array_filter($category_destinations, function($dest) {
                return !empty($dest['image']);
            });
            $destinations = array_merge($destinations, $category_destinations);
        }
        
        usort($destinations, function($a, $b) {
            return strlen($b['extract']) - strlen($a['extract']);
        });
        
        $destinations = array_slice($destinations, 0, 10);
    }
}
?>

<div class="travel-container">
    
    <div class="region-buttons">
        <div class="main-menu">
            <?php foreach ($regions as $key => $region): ?>
                <button class="region-title" onclick="toggleSubregions('<?php echo $key; ?>')">
                    <?php echo $region['title']; ?>
                </button>
            <?php endforeach; ?>
        </div>
        <?php foreach ($regions as $key => $region): ?>
            <div id="<?php echo $key; ?>-subregions" class="subregion-buttons hidden">
                <?php foreach ($region['subregions'] as $subkey => $subregion): ?>
                    <form method="POST" action="" style="display: inline;">
                        <input type="hidden" name="region" value="<?php echo $key; ?>">
                        <input type="hidden" name="subregion" value="<?php echo $subkey; ?>">
                        <button type="submit" class="btn-subregion">
                            <?php echo $subregion['title']; ?>
                        </button>
                    </form>
                <?php endforeach; ?>
            </div>
        <?php endforeach; ?>
    </div>

    <?php if (isset($destinations) && !empty($destinations)): ?>
        <div class="destination-results">
            <?php foreach ($destinations as $dest): ?>
                <div class="destination-card">
                    <?php if ($dest['image']): ?>
                        <img src="<?php echo $dest['image']; ?>" alt="<?php echo $dest['title']; ?>">
                    <?php endif; ?>
                    
                    <div class="destination-info">
                        <h3><?php echo $dest['title']; ?></h3>
                        <p><?php echo mb_substr($dest['extract'], 0, 200) . '...'; ?></p>
                        
                        <?php if ($dest['video'] || $dest['audio']): ?>
                            <div class="multimedia-content">
                                <?php if ($dest['video']): ?>
                                    <video controls>
                                        <source src="<?php echo $dest['video'][0]['url']; ?>" type="<?php echo $dest['video'][0]['mime']; ?>">
                                    </video>
                                <?php endif; ?>
                                
                                <?php if ($dest['audio']): ?>
                                    <audio controls>
                                        <source src="<?php echo $dest['audio'][0]['url']; ?>" type="<?php echo $dest['audio'][0]['mime']; ?>">
                                    </audio>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                        
                        <a href="<?php echo $dest['url']; ?>" target="_blank" class="read-more">자세히 보기</a>
                        <div class="wiki-attribution">
                            본 콘텐츠는 <a href="https://ko.wikipedia.org/" target="_blank">위키피디아</a>에서 제공됩니다. 
                            <a href="https://creativecommons.org/licenses/by-sa/3.0/" target="_blank">크리에이티브 커먼즈 저작자표시-동일조건변경허락 3.0</a> 라이선스에 따라 이용할 수 있습니다.
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<style>
.wiki-attribution {
    font-size: 12px;
    color: #666;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #eee;
    text-align: center;
}

.wiki-attribution a {
    color: #3498DB;
    text-decoration: none;
}

.wiki-attribution a:hover {
    text-decoration: underline;
}

.main-menu {
    display: flex;
    justify-content: center;
    gap: 15px;
    flex-wrap: wrap;
    margin-bottom: 20px;
}
.travel-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    font-family: 'Noto Sans KR', sans-serif;
}

.region-group {
    margin-bottom: 30px;
    text-align: center;
}

.region-group h3 {
    color: #2C3E50;
    font-size: 24px;
    margin-bottom: 15px;
    position: relative;
    display: inline-block;
}

.region-group h3:after {
    content: '';
    position: absolute;
    bottom: -5px;
    left: 50%;
    transform: translateX(-50%);
    width: 50px;
    height: 3px;
    background: #3498DB;
}

.region-title {
    padding: 12px 20px;
    font-size: 16px;
    background: linear-gradient(135deg, #3498DB, #2980B9);
    color: white;
    border: none;
    border-radius: 25px;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    white-space: nowrap;
}

.region-title:after {
    content: '▼';
    margin-left: 8px;
    font-size: 12px;
    transition: transform 0.3s ease;
}

.region-title.active {
    background: linear-gradient(135deg, #2980B9, #2C3E50);
}

.region-title.active:after {
    transform: rotate(180deg);
}

.hidden {
    display: none;
}

.subregion-buttons {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s ease-out;
}

.subregion-buttons.show {
    max-height: 500px;
    margin-top: 15px;
}

.btn-subregion {
    padding: 12px 24px;
    font-size: 15px;
    background: linear-gradient(135deg, #3498DB, #2980B9);
    color: white;
    border: none;
    border-radius: 25px;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.btn-subregion:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(0,0,0,0.2);
    background: linear-gradient(135deg, #2980B9, #2C3E50);
}

.destination-results {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    gap: 25px;
    margin-top: 40px;
}

.destination-card {
    border-radius: 15px;
    overflow: hidden;
    background: white;
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    transition: transform 0.3s ease;
}

.destination-card:hover {
    transform: translateY(-5px);
}

.destination-card img {
    width: 100%;
    height: 220px;
    object-fit: cover;
    transition: transform 0.3s ease;
}

.destination-card:hover img {
    transform: scale(1.05);
}

.destination-info {
    padding: 20px;
}

.destination-info h3 {
    margin: 0 0 12px 0;
    color: #2C3E50;
    font-size: 20px;
}

.destination-info p {
    color: #666;
    line-height: 1.7;
    font-size: 15px;
    margin-bottom: 15px;
}

.read-more {
    display: inline-block;
    padding: 10px 20px;
    background: linear-gradient(135deg, #3498DB, #2980B9);
    color: white;
    text-decoration: none;
    border-radius: 25px;
    font-size: 14px;
    transition: all 0.3s ease;
}

.read-more:hover {
    background: linear-gradient(135deg, #2980B9, #2C3E50);
    transform: translateY(-2px);
}

.multimedia-content {
    margin-top: 15px;
}

.multimedia-content audio,
.multimedia-content video {
    width: 100%;
    border-radius: 8px;
    margin-top: 12px;
}
/* 모바일 최적화 스타일 추가 */
@media (max-width: 768px) {
    .main-menu {
        flex-wrap: nowrap;
        overflow-x: auto;
        justify-content: flex-start;
        padding-bottom: 10px;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: none; /* Firefox */
    }

    .main-menu::-webkit-scrollbar {
        display: none; /* Chrome, Safari, Opera */
    }

    .region-title {
        font-size: 14px;
        padding: 10px 16px;
        flex-shrink: 0;
    }

    .travel-container {
        padding: 15px;
    }

    .region-group h3 {
        font-size: 20px;
    }

    .subregion-buttons {
        gap: 8px;
    }

    .btn-subregion {
        padding: 10px 18px;
        font-size: 14px;
        width: calc(50% - 8px);  /* 2열 그리드로 변경 */
    }

    .destination-results {
        grid-template-columns: 1fr;  /* 모바일에서는 1열로 */
        gap: 20px;
    }

    .destination-card {
        margin: 0 auto;
        max-width: 100%;
    }

    .destination-card img {
        height: 180px;  /* 모바일에서는 이미지 높이 축소 */
    }

    .destination-info h3 {
        font-size: 18px;
    }

    .destination-info p {
        font-size: 14px;
    }

    .read-more {
        width: 100%;  /* 모바일에서는 버튼 전체 너비로 */
        text-align: center;
        padding: 12px;
    }
}

/* 태블릿 최적화 */
@media (min-width: 769px) and (max-width: 1024px) {
    .destination-results {
        grid-template-columns: repeat(2, 1fr);  /* 태블릿에서는 2열로 */
    }

    .btn-subregion {
        width: calc(33.33% - 12px);  /* 3열 그리드로 변경 */
    }
}
</style>

<script>
function toggleSubregions(regionId) {
    const subregions = document.getElementById(regionId + '-subregions');
    const button = subregions.previousElementSibling;
    
    // 다른 모든 서브리전 닫기
    document.querySelectorAll('.subregion-buttons').forEach(el => {
        if (el.id !== regionId + '-subregions') {
            el.classList.remove('show');
            el.classList.add('hidden');
            el.previousElementSibling.classList.remove('active');
        }
    });
    
    // 선택된 서브리전 토글
    subregions.classList.toggle('hidden');
    subregions.classList.toggle('show');
    button.classList.toggle('active');
}
</script>
<?php
include_once(G5_PATH.'/tail.php');
?>