<?php
if (!defined('_GNUBOARD_')) {
    exit;
}

if (!function_exists('oi_popup_write_log')) {
    function oi_popup_write_log($status, $title, $lines, $log_file = '', $log_tag = '')
    {
        $status = trim((string)$status);
        $title = trim((string)$title);
        $log_file = trim((string)$log_file);
        $log_tag = trim((string)$log_tag);

        if (!is_array($lines)) {
            $lines = array((string)$lines);
        }

        if ($log_file === '') {
            $log_file = G5_DATA_PATH . '/log/order_result_popup.log';
        }

        $dir = dirname($log_file);
        if (!is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }

        $ip = isset($_SERVER['REMOTE_ADDR']) ? trim((string)$_SERVER['REMOTE_ADDR']) : '';
        $uri = isset($_SERVER['REQUEST_URI']) ? trim((string)$_SERVER['REQUEST_URI']) : '';
        $mb_id = '';
        if (isset($GLOBALS['member']) && is_array($GLOBALS['member']) && isset($GLOBALS['member']['mb_id'])) {
            $mb_id = trim((string)$GLOBALS['member']['mb_id']);
        }

        $normalized_lines = array();
        foreach ($lines as $line) {
            $line = trim((string)$line);
            if ($line === '') {
                continue;
            }
            $normalized_lines[] = $line;
        }

        $entry = array(
            'at' => defined('G5_TIME_YMDHIS') ? G5_TIME_YMDHIS : date('Y-m-d H:i:s'),
            'status' => $status,
            'tag' => $log_tag,
            'title' => $title,
            'lines' => $normalized_lines,
            'mb_id' => $mb_id,
            'ip' => $ip,
            'uri' => $uri
        );

        @file_put_contents($log_file, json_encode($entry, JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND | LOCK_EX);
    }
}

if (!function_exists('oi_render_result_popup')) {
    function oi_render_result_popup($title, $lines, $redirect_url, $button_text = '확인', $options = array())
    {
        $title = (string)$title;
        $redirect_url = (string)$redirect_url;
        $button_text = (string)$button_text;
        if (!is_array($lines)) {
            $lines = array((string)$lines);
        }

        $status = 'success';
        $subtitle = '처리 내역을 확인해 주세요.';
        $enable_log = false;
        $log_file = '';
        $log_tag = '';
        if (is_string($options) && trim($options) !== '') {
            $status = trim($options);
        } else if (is_array($options)) {
            if (isset($options['status']) && trim((string)$options['status']) !== '') {
                $status = trim((string)$options['status']);
            }
            if (isset($options['subtitle'])) {
                $subtitle = trim((string)$options['subtitle']);
            }
            if (isset($options['log'])) {
                $enable_log = (bool)$options['log'];
            }
            if (isset($options['log_file'])) {
                $log_file = trim((string)$options['log_file']);
            }
            if (isset($options['log_tag'])) {
                $log_tag = trim((string)$options['log_tag']);
            }
        }

        $status = strtolower($status);
        if ($status !== 'error' && $status !== 'success') {
            $status = 'success';
        }

        $status_class = ($status === 'error') ? 'status-error' : 'status-success';
        $status_icon = ($status === 'error') ? '!' : '✓';
        $safe_subtitle = htmlspecialchars($subtitle, ENT_QUOTES, 'UTF-8');

        if ($enable_log) {
            oi_popup_write_log($status, $title, $lines, $log_file, $log_tag);
        }

        $safe_title = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
        $safe_redirect = htmlspecialchars($redirect_url, ENT_QUOTES, 'UTF-8');
        $safe_button = htmlspecialchars($button_text, ENT_QUOTES, 'UTF-8');

        echo '<!doctype html><html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">';
        echo '<title>' . $safe_title . '</title>';
        echo '<style>
            body{margin:0;background:#f3f4f6;font-family:"Noto Sans KR","Apple SD Gothic Neo","Malgun Gothic",sans-serif;color:#1f2937;}
            .wrap{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:18px;box-sizing:border-box;}
            .modal{width:min(860px,96vw);background:linear-gradient(180deg,#ffffff 0%,#fafafa 100%);border-radius:18px;border:1px solid #d5d9e0;box-shadow:0 30px 70px rgba(2,6,23,.22);overflow:hidden;}
            .head{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid #e9edf5;}
            .icon{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:999px;color:#fff;font-size:15px;font-weight:800;box-shadow:0 6px 14px rgba(15,23,42,.25)}
            .title{font-size:20px;font-weight:800;letter-spacing:-0.2px;color:#0f172a;}
            .body{padding:20px;}
            .warn{margin:0 0 6px;font-size:40px;font-weight:800;line-height:1.35;}
            .sub{margin:0 0 14px;font-size:31px;color:#4b5563;}
            .list{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:10px;}
            .line{padding:10px 12px;background:#f5f6f8;border:1px solid #e1e4ea;border-radius:10px;font-size:32px;line-height:1.65;word-break:break-word;}
            .actions{display:flex;justify-content:flex-end;padding:14px 20px 20px;border-top:1px solid #edf0f5;background:#fcfdff;}
            .btn{min-width:116px;height:44px;border-radius:999px;font-size:16px;font-weight:700;color:#fff;padding:0 18px;cursor:pointer;}
            .status-success .head{background:linear-gradient(135deg,#f8f9fb 0%,#f1f3f6 100%);}
            .status-success .icon{background:#1f2937;}
            .status-success .warn{color:#1e293b;}
            .status-success .btn{border:1px solid #1f2937;background:linear-gradient(135deg,#1f2937 0%,#111827 100%);box-shadow:0 8px 18px rgba(17,24,39,.24);}
            .status-success .btn:hover{background:linear-gradient(135deg,#111827 0%,#0b1220 100%);}
            .status-error .head{background:linear-gradient(135deg,#fff7f7 0%,#ffe9e9 100%);}
            .status-error .icon{background:#b91c1c;}
            .status-error .warn{color:#991b1b;}
            .status-error .btn{border:1px solid #b91c1c;background:linear-gradient(135deg,#dc2626 0%,#b91c1c 100%);box-shadow:0 8px 18px rgba(185,28,28,.24);}
            .status-error .btn:hover{background:linear-gradient(135deg,#b91c1c 0%,#991b1b 100%);}
            @media (max-width: 640px){
                .line{font-size:15px;line-height:1.55}
                .warn{font-size:18px}
                .sub{font-size:15px}
                .title{font-size:18px}
            }
        </style></head><body>';
        echo '<div class="wrap"><div class="modal ' . $status_class . '">';
        echo '<div class="head"><span class="icon">' . $status_icon . '</span><span class="title">' . $safe_title . '</span></div>';
        echo '<div class="body">';
        $first = '';
        $list = array();
        foreach ($lines as $line) {
            $line = trim((string)$line);
            if ($line === '') {
                continue;
            }
            if ($first === '') {
                $first = $line;
            } else {
                $list[] = $line;
            }
        }
        if ($first !== '') {
            echo '<p class="warn">' . htmlspecialchars($first, ENT_QUOTES, 'UTF-8') . '</p>';
        }
        echo '<p class="sub">' . $safe_subtitle . '</p>';
        echo '<ul class="list">';
        foreach ($list as $line) {
            echo '<li class="line">' . nl2br(htmlspecialchars($line, ENT_QUOTES, 'UTF-8')) . '</li>';
        }
        echo '</ul>';
        echo '</div><div class="actions"><button type="button" class="btn" onclick="location.href=\'' . $safe_redirect . '\'">' . $safe_button . '</button></div>';
        echo '</div></div></body></html>';
        exit;
    }
}

if (!function_exists('oi_fail_popup')) {
    function oi_fail_popup($message, $code = '', $redirect_url = '', $title = '요청 처리 실패', $button_text = '확인', $subtitle = '요청이 중단되었습니다.', $options = array())
    {
        $message = trim((string)$message);
        $code = trim((string)$code);
        $redirect_url = trim((string)$redirect_url);
        if ($redirect_url === '') {
            $redirect_url = G5_SHOP_URL;
        }

        $lines = array();
        if ($message !== '') {
            $lines[] = $message;
        }
        if ($code !== '') {
            $lines[] = $code;
        }

        $popup_options = array(
            'status' => 'error',
            'subtitle' => $subtitle
        );
        if (is_array($options)) {
            if (isset($options['log'])) {
                $popup_options['log'] = (bool)$options['log'];
            }
            if (isset($options['log_file'])) {
                $popup_options['log_file'] = trim((string)$options['log_file']);
            }
            if (isset($options['log_tag'])) {
                $popup_options['log_tag'] = trim((string)$options['log_tag']);
            }
        }

        oi_render_result_popup($title, $lines, $redirect_url, $button_text, $popup_options);
    }
}

if (!function_exists('oi_success_popup')) {
    function oi_success_popup($message, $details = array(), $redirect_url = '', $title = '처리 완료', $button_text = '확인', $subtitle = '처리 내역을 확인해 주세요.', $options = array())
    {
        $message = trim((string)$message);
        $redirect_url = trim((string)$redirect_url);
        if ($redirect_url === '') {
            $redirect_url = G5_SHOP_URL;
        }

        if (!is_array($details)) {
            $details = array((string)$details);
        }

        $lines = array();
        if ($message !== '') {
            $lines[] = $message;
        }

        foreach ($details as $detail) {
            $detail = trim((string)$detail);
            if ($detail === '') {
                continue;
            }
            $lines[] = $detail;
        }

        $popup_options = array(
            'status' => 'success',
            'subtitle' => $subtitle
        );
        if (is_array($options)) {
            if (isset($options['log'])) {
                $popup_options['log'] = (bool)$options['log'];
            }
            if (isset($options['log_file'])) {
                $popup_options['log_file'] = trim((string)$options['log_file']);
            }
            if (isset($options['log_tag'])) {
                $popup_options['log_tag'] = trim((string)$options['log_tag']);
            }
        }

        oi_render_result_popup($title, $lines, $redirect_url, $button_text, $popup_options);
    }
}
