<?php
include_once('./_common.php');

// Function to process and validate URLs
function process_url($url) {
    // Remove whitespace
    $url = trim($url);
    
    // If URL is already shortened, return as is
    if (strlen($url) < 30) {
        return $url;
    }
    
    // Basic URL validation
    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        return $url;
    }
    
    // You can implement your preferred URL shortening method here
    // For example, using a URL shortening service or creating your own short URLs
    
    // Example of basic URL shortening using hash
    $hash = substr(md5($url), 0, 8);
    $short_url = G5_URL . '/u/' . $hash;
    
    // Store the URL mapping in database (recommended)
    $sql = "INSERT INTO {$g5['url_mapping_table']} 
            SET original_url = '" . sql_real_escape_string($url) . "',
                short_url = '" . sql_real_escape_string($short_url) . "',
                created_at = '" . G5_TIME_YMDHIS . "'
            ON DUPLICATE KEY UPDATE 
                hits = hits + 1";
    sql_query($sql);
    
    return $short_url;
}

// Process incoming data
$data = json_decode(file_get_contents('php://input'), true);
$wr_id = isset($data['wr_id']) ? (int)$data['wr_id'] : null;
$content = isset($data['content']) ? trim($data['content']) : null;

// 로그인 확인
if (!$member['mb_id']) {
    alert('로그인후 이용해주세요', G5_BBS_URL.'/login.php');
}

if (!$wr_id || !$content) {
    echo json_encode([
        'success' => false, 
        'message' => '잘못된 요청입니다.'
    ]);
    exit;
}

// Get board information
$sql = "SELECT bo_table FROM {$g5['board_new_table']} WHERE wr_id = '" . sql_real_escape_string($wr_id) . "' LIMIT 1";
$result = sql_fetch($sql);

if (!$result) {
    echo json_encode([
        'success' => false, 
        'message' => '게시판 정보를 찾을 수 없습니다.'
    ]);
    exit;
}

$bo_table = $result['bo_table'];
$wr_name = $member['mb_nick'];

// Process content for URLs
$pattern = '/(https?:\/\/[^\s<>"]+|www\.[^\s<>"]+)/';
$wr_content = preg_replace_callback($pattern, function($matches) {
    return process_url($matches[0]);
}, $content);

$wr_content = htmlspecialchars($wr_content);

// Get next comment number
$sql = "SELECT MAX(wr_comment) AS max_comment FROM {$g5['write_prefix']}{$bo_table} 
        WHERE wr_parent = '" . sql_real_escape_string($wr_id) . "' 
        AND wr_is_comment = '1'";
$comment_result = sql_fetch($sql);
$wr_comment = ($comment_result['max_comment'] + 1) * 10;

// Insert comment
$sql = "INSERT INTO {$g5['write_prefix']}{$bo_table} 
        SET wr_parent = '" . sql_real_escape_string($wr_id) . "', 
            wr_option = '0',
            wr_num = '" . sql_real_escape_string($wr['wr_num']) . "',
            wr_is_comment = '1', 
            wr_reply = '',
            wr_subject = '',
            wr_content = '" . sql_real_escape_string($wr_content) . "', 
            mb_id = '" . sql_real_escape_string($member['mb_id']) . "',
            wr_name = '" . sql_real_escape_string($wr_name) . "', 
            wr_email = '',
            wr_comment_reply = '',
            wr_comment = '" . sql_real_escape_string($wr_comment) . "',
            wr_datetime = '" . G5_TIME_YMDHIS . "',
            wr_last = '',
            wr_ip = '" . $_SERVER['REMOTE_ADDR'] . "'";

$result = sql_query($sql);

// Update comment count and return result
if ($result) {
    $sql = "UPDATE {$g5['write_prefix']}{$bo_table} 
            SET wr_comment = wr_comment + 1 
            WHERE wr_id = '" . sql_real_escape_string($wr_id) . "'";
    sql_query($sql);
    
    echo json_encode([
        'success' => true, 
        'message' => '댓글이 작성되었습니다.', 
        'nickname' => $wr_name
    ]);
} else {
    echo json_encode([
        'success' => false, 
        'message' => '댓글 작성에 실패했습니다.'
    ]);
}
exit;