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

$data = json_decode(file_get_contents('php://input'), true);
$wr_id = isset($data['wr_id']) ? $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;
}

$sql = "SELECT bo_table FROM {$g5['board_new_table']} WHERE wr_id = '{$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']; // 회원 닉네임 설정
$wr_content = htmlspecialchars($content);
$ip_address = $_SERVER['REMOTE_ADDR']; // IP 주소 가져오기

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

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

$result = sql_query($sql);

// 댓글 수 업데이트
if ($result) {
    $sql = "UPDATE {$g5['write_prefix']}{$bo_table} 
            SET wr_comment = wr_comment + 1 
            WHERE wr_id = '{$wr_id}'";
    sql_query($sql);

    echo json_encode(['success' => true, 'message' => '댓글이 작성되었습니다.', 'nickname' => $wr_name]);
} else {
    echo json_encode(['success' => false, 'message' => '댓글 작성에 실패했습니다.']);
}
exit;
