<?php
$show_popup = false;
$popup_version = '';
$popup_features = [];
$forcePopup = false;

if (auth('is_login') == true && auth('user_role') == 1 && !auth('is_staff')) {
    $CI = &get_instance();
    $force_popup = ((string) $CI->input->get('force_whats_new', true) === '1' || $forcePopup == 1);
    $CI->config->load('whats_new', true);
    $updates = $CI->config->item('whats_new', 'whats_new');
    $updates = is_array($updates) ? $updates : [];

    if (!empty($updates)) {
        uksort($updates, function ($a, $b) {
            return version_compare($b, $a);
        });

        $current_version = settings()['version'] ?? '';
        $latest_installed = defined('NEW_VERSION') ? (string) NEW_VERSION : $current_version;
        $is_latest_version = !empty($current_version) && !empty($latest_installed) && version_compare($current_version, $latest_installed, '==');
        $target_version = $is_latest_version && isset($updates[$current_version]) ? $current_version : '';
        if ($force_popup && isset($updates[$current_version])) {
            $target_version = $current_version;
        } elseif ($force_popup && empty($target_version)) {
            $target_version = (string) array_key_first($updates);
        }
        if (empty($target_version)) {
            $updates = [];
        }
        $version_data = !empty($target_version) ? ($updates[$target_version] ?? []) : [];
        $features = isset($version_data['features']) && is_array($version_data['features']) ? $version_data['features'] : [];
        $numeric_keys = array_filter(array_keys($features), 'is_numeric');
        if (!empty($numeric_keys)) {
            uksort($features, function ($a, $b) {
                if (is_numeric($a) && is_numeric($b)) {
                    return (int) $a <=> (int) $b;
                }
                return strnatcmp((string) $a, (string) $b);
            });
        }

        $normalized = [];
        $index = 1;
        foreach ($features as $serial => $feature) {
            $title = trim((string) ($feature['title'] ?? ''));
            $description = trim((string) ($feature['description'] ?? ''));
            $image = trim((string) ($feature['image'] ?? ''));
            $url = trim((string) ($feature['url'] ?? ''));

            if ($title === '' && $description === '' && $image === '' && $url === '') {
                continue;
            }

            $normalized[] = [
                'serial' => is_numeric($serial) ? (int) $serial : $index,
                'title' => $title,
                'description' => $description,
                'image' => $image,
                'url' => $url,
            ];
            $index++;
        }

        if (!empty($normalized)) {
            $show_popup = true;
            $popup_version = $target_version;
            $popup_features = $normalized;
        }
    }
}
?>

<?php if ($show_popup) : ?>
    <style>
        #whatsNewReleaseModal .modal-content {
            border: 0;
            border-radius: 18px;
            overflow: hidden;
            box-shadow: 0 20px 50px rgba(0, 0, 0, .25);
        }

        #whatsNewReleaseModal .modal-header {
            border-bottom: 0;
            background: linear-gradient(135deg, #0f172a, #1d4ed8 55%, #14b8a6);
            color: #fff;
            padding: 18px 22px;
        }

        #whatsNewReleaseModal .modal-title {
            font-weight: 700;
            letter-spacing: .2px;
        }

        #whatsNewReleaseModal .close {
            color: #fff;
            opacity: .85;
            text-shadow: none;
        }

        #whatsNewReleaseModal .modal-body {
            background: linear-gradient(180deg, #f8fbff, #ffffff);
            max-height: 70vh;
            overflow-y: auto;
            padding: 18px;
        }

        #whatsNewReleaseModal .wn-feature-card {
            border-radius: 14px;
            border: 1px solid #e6edf8;
            background: #fff;
            padding: 14px;
            margin-bottom: 12px;
            transform: translateY(14px);
            opacity: 0;
            animation: wnRise .55s ease forwards;
        }

        #whatsNewReleaseModal .wn-feature-card:nth-child(1) {
            animation-delay: .04s;
        }

        #whatsNewReleaseModal .wn-feature-card:nth-child(2) {
            animation-delay: .1s;
        }

        #whatsNewReleaseModal .wn-feature-card:nth-child(3) {
            animation-delay: .16s;
        }

        #whatsNewReleaseModal .wn-feature-card:nth-child(4) {
            animation-delay: .22s;
        }

        #whatsNewReleaseModal .wn-feature-card img {
            width: 100%;
            height: auto;
            border-radius: 10px;
            margin-bottom: 10px;
        }

        #whatsNewReleaseModal .wn-feature-title {
            font-size: 17px;
            font-weight: 700;
            margin: 0 0 6px;
            color: #0f172a;
        }

        #whatsNewReleaseModal .wn-feature-desc {
            margin: 0;
            color: #334155;
            line-height: 1.6;
        }

        #whatsNewReleaseModal .modal-footer {
            border-top: 1px solid #edf2fb;
            background: #fff;
        }

        @keyframes wnRise {
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }
    </style>

    <div class="modal fade" id="whatsNewReleaseModal" tabindex="-1" role="dialog" aria-labelledby="whatsNewReleaseTitle" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close whatsNewCloseBtn" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title" id="whatsNewReleaseTitle">What's New in v<?= html_escape($popup_version); ?></h4>
                </div>
                <div class="modal-body">
                    <?php foreach ($popup_features as $feature) : ?>
                        <div class="wn-feature-card">
                            <?php if (!empty($feature['image'])) : ?>
                                <img src="<?= html_escape($feature['image']); ?>" alt="<?= html_escape($feature['title']); ?>">
                            <?php endif; ?>

                            <?php if (!empty($feature['title'])) : ?>
                                <h5 class="wn-feature-title"><?= html_escape('#' . ($feature['serial'] ?? '')); ?> <?= html_escape($feature['title']); ?></h5>
                            <?php endif; ?>

                            <?php if (!empty($feature['description'])) : ?>
                                <p class="wn-feature-desc"><?= html_escape($feature['description']); ?></p>
                            <?php endif; ?>

                            <?php if (!empty($feature['url'])) : ?>
                                <a href="<?= html_escape($feature['url']); ?>" target="_blank" class="btn btn-sm btn-secondary">Explore</a>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="modal-footer">
                    <a href="<?= base_url('admin/settings/whats_new'); ?>" class="btn btn-secondary">See Full Changelog</a>
                    <button type="button" class="btn btn-default whatsNewCloseBtn" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        (function() {
            var cookieName = 'whats_new_seen_v_<?= html_escape($popup_version); ?>';
            var forcePopup = <?= isset($force_popup) && $force_popup ? 'true' : 'false'; ?>;
            if (forcePopup || !getCookie(cookieName)) {
                $('#whatsNewReleaseModal').modal('show');
            }

            function setWhatsNewCookie() {
                setCookie(cookieName, '1', 525600); // 365 days
            }

            $(document).on('click', '.whatsNewCloseBtn', function() {
                setWhatsNewCookie();
            });

            $('#whatsNewReleaseModal').on('hidden.bs.modal', function() {
                setWhatsNewCookie();
            });
        })();
    </script>
<?php endif; ?>