<?php echo message_box('success'); ?>

<div class="space-y-6">
    <div class="rounded-2xl border border-border bg-card shadow-sm">
        <div class="border-b border-border px-5 py-4">
            <h2 class="text-lg font-semibold text-foreground"><?= lang('update'); ?></h2>
            <p class="text-sm text-muted-foreground"><?= lang('system_update') ?></p>
        </div>
        <div class="p-5 space-y-6">
            <div class="grid gap-4 md:grid-cols-2">
                <div class="form-group">
                    <?= form_input_group('purchase_key', lang('purchase_key'), '', 'text', true, array('placeholder' => lang('enter_your') . ' ' . lang('purchase_key'))); ?>
                </div>
                <div class="form-group">
                    <?= form_input_group('buyer', lang('envato_username'), '', 'text', true, array('placeholder' => 'unique_coder')); ?>
                </div>
            </div>

            <div class="grid gap-4 md:grid-cols-2">
                <div class="rounded-xl border border-border bg-muted/30 p-4 text-center">
                    <h4 class="text-sm font-semibold text-muted-foreground"><?php echo lang('your_version'); ?></h4>
                    <p class="text-lg font-semibold text-foreground"><?php echo wordwrap($current_version, 1, '.', true); ?></p>
                </div>
                <div class="rounded-xl border border-border bg-muted/30 p-4 text-center">
                    <h4 class="text-sm font-semibold text-muted-foreground"><?php echo lang('latest_version'); ?></h4>
                    <p class="text-lg font-semibold text-foreground"><?php echo wordwrap($latest_version, 1, '.', true); ?></p>
                    <?php echo form_hidden('latest_version', $latest_version); ?>
                </div>
            </div>

            <div class="border-t border-border pt-5 text-center space-y-4">
                <?php if ($current_version != $latest_version && $latest_version > $current_version) { ?>
                    <div class="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-700 text-left">
                        Before performing an update, it is <b>strongly recommended to create a full backup</b>
                        of your current installation <b>(files and database)</b> and review the changelog.
                    </div>
                    <h3 class="text-base font-semibold text-foreground"><?php echo lang('update_available'); ?></h3>
                    <div class="update_app_wrapper" data-wait-text="<?php echo lang('wait_text'); ?>"
                         data-original-text="<?php echo lang('update_now'); ?>">
                        <a href="#" id="update_app"
                           class="inline-flex items-center gap-2 rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-500"><?php echo lang('update_now'); ?></a>
                    </div>
                    <div id="update_progress_wrap" class="hidden space-y-3 rounded-xl border border-border bg-muted/30 p-4">
                        <div class="flex items-center justify-between text-sm font-semibold text-foreground">
                            <span id="update_progress_label">Preparing update...</span>
                            <span id="update_progress_percent">0%</span>
                        </div>
                        <div class="h-2 overflow-hidden rounded-full bg-muted">
                            <div id="update_progress_bar" class="h-full w-0 rounded-full bg-emerald-500 transition-all duration-300"></div>
                        </div>
                        <p id="update_progress_note" class="text-sm text-muted-foreground">Waiting to start</p>
                    </div>
                    <div id="update_messages" class="text-left">
                    </div>
                <?php } else { ?>
                    <h3 class="text-base font-semibold text-emerald-600"><?php echo lang('using_latest_version'); ?></h3>
                <?php } ?>
                <?php if (count($update_errors) > 0) { ?>
                    <h2 class="text-sm font-semibold text-rose-600">Please fix the errors listed below.</h2>
                    <?php foreach ($update_errors as $error) { ?>
                        <div class="rounded-lg border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700 text-left">
                            <?php echo $error; ?>
                        </div>
                    <?php } ?>
                <?php } ?>
                <?php if (isset($update_info->additional_data)) {
                    echo $update_info->additional_data;
                } ?>
            </div>
        </div>
    </div>
</div>
<script>
    $(function () {
        var updateInProgress = false;
        var csrfName = '<?= $this->security->get_csrf_token_name(); ?>';
        var csrfHash = '<?= $this->security->get_csrf_hash(); ?>';

        function csrfPayload(data) {
            data = data || {};
            data[csrfName] = csrfHash;
            return data;
        }

        function setUpdateProgress(percent, label, note) {
            $('#update_progress_wrap').removeClass('hidden');
            $('#update_progress_bar').css('width', percent + '%');
            $('#update_progress_percent').text(percent + '%');
            if (label) {
                $('#update_progress_label').text(label);
            }
            if (note) {
                $('#update_progress_note').text(note);
            }
        }

        function showUpdateError(message) {
            $('#update_messages').html('<div class="rounded-lg border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">' + message + '</div>');
        }

        function pollUpdateStatus(token) {
            $.ajax({
                url: '<?= base_url() ?>admin/auto_update/status/' + encodeURIComponent(token),
                method: 'GET',
                dataType: 'json',
                cache: false
            }).done(function (response) {
                if (!response || response.success !== true) {
                    updateInProgress = false;
                    $('#update_app').removeClass('pointer-events-none opacity-60').text($('.update_app_wrapper').data('original-text'));
                    showUpdateError((response && response.message) ? response.message : 'Unable to read update status.');
                    return;
                }

                setUpdateProgress(response.progress || 0, 'Updating database...', response.message || 'Working...');

                if (response.done || response.status === 'done') {
                    $('#update_messages').html('<div class="rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">Database upgrade completed successfully.</div>');
                    $('#update_progress_note').text('Finalizing...');
                    setTimeout(function () {
                        window.location.reload();
                    }, 2000);
                    return;
                }

                if (response.status === 'failed') {
                    updateInProgress = false;
                    $('#update_app').removeClass('pointer-events-none opacity-60').text($('.update_app_wrapper').data('original-text'));
                    showUpdateError(response.message || 'Update failed.');
                    return;
                }

                setTimeout(function () {
                    pollUpdateStatus(token);
                }, 2500);
            }).fail(function (response) {
                updateInProgress = false;
                $('#update_app').removeClass('pointer-events-none opacity-60').text($('.update_app_wrapper').data('original-text'));
                showUpdateError(response && response.responseText ? response.responseText : 'Unable to continue the update.');
            });
        }

        function startDatabaseUpdate() {
            $.ajax({
                url: '<?= base_url() ?>admin/auto_update/database',
                method: 'POST',
                dataType: 'json',
                data: csrfPayload({
                    auto_update: true
                })
            }).done(function (response) {
                if (!response || response.success !== true) {
                    updateInProgress = false;
                    $('#update_app').removeClass('pointer-events-none opacity-60').text($('.update_app_wrapper').data('original-text'));
                    showUpdateError((response && response.message) ? response.message : 'Update failed.');
                    return;
                }

                setUpdateProgress(response.progress || 0, 'Updating database...', response.message || 'Working...');

                if (response.done) {
                    $('#update_messages').html('<div class="rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">Database upgrade completed successfully.</div>');
                    $('#update_progress_note').text('Finalizing...');
                    setTimeout(function () {
                        window.location.reload();
                    }, 2000);
                    return;
                }

                pollUpdateStatus(response.token);
            }).fail(function (response) {
                updateInProgress = false;
                $('#update_app').removeClass('pointer-events-none opacity-60').text($('.update_app_wrapper').data('original-text'));
                showUpdateError(response && response.responseText ? response.responseText : 'Unable to continue the update.');
            });
        }

        $('#update_app').on('click', function (e) {
            e.preventDefault();
            if (updateInProgress) {
                return;
            }
            $('input[name="purchase_key"]').parents('.form-group').removeClass('has-error');
            $('input[name="buyer"]').parents('.form-group').removeClass('has-error');

            var purchase_key = $('input[name="purchase_key"]').val();
            var buyer = $('input[name="buyer"]').val();
            var latest_version = $('input[name="latest_version"]').val();
            if (purchase_key != '' && buyer != '') {
                var ubtn = $(this);
                updateInProgress = true;
                ubtn.html('Please wait...');
                ubtn.addClass('pointer-events-none opacity-60');
                setUpdateProgress(0, 'Preparing update...', 'Validating update package');
                $.post('<?= base_url() ?>admin/auto_update', csrfPayload({
                    purchase_key: purchase_key,
                    latest_version: latest_version,
                    buyer: buyer,
                    auto_update: true
                })).done(function (res) {
                    var trimmed = $.trim(res || '');
                    if (trimmed) {
                        try {
                            var result = JSON.parse(trimmed);
                            showUpdateError(result.message || 'Update validation failed.');
                        } catch (err) {
                            showUpdateError(trimmed);
                        }
                        updateInProgress = false;
                        ubtn.removeClass('pointer-events-none opacity-60');
                        ubtn.html($('.update_app_wrapper').data('original-text'));
                    } else {
                        setUpdateProgress(1, 'Starting database migration...', 'Applying updates step by step');
                        startDatabaseUpdate();
                    }
                }).fail(function (response) {
                    showUpdateError(response && response.responseText ? response.responseText : 'Unable to start update.');
                    updateInProgress = false;
                    ubtn.removeClass('pointer-events-none opacity-60');
                    ubtn.html($('.update_app_wrapper').data('original-text'));
                });
            } else if (purchase_key != '' && buyer == '') {
                $('input[name="purchase_key"]').parents('.form-group').removeClass('has-error');
                $('input[name="buyer"]').parents('.form-group').addClass('has-error');
            } else if (buyer != '' && purchase_key == '') {
                $('input[name="purchase_key"]').parents('.form-group').addClass('has-error');
                $('input[name="buyer"]').parents('.form-group').removeClass('has-error');
            } else {
                $('input[name="purchase_key"]').parents('.form-group').addClass('has-error');
                $('input[name="buyer"]').parents('.form-group').addClass('has-error');
            }
        });
    });
</script>
