/**
 * CMS Theme Management Script
 */
$(document).ready(function () {
    const apiBase = 'APIs/cms_api.php';
    let currentStep = 1;

    loadThemes();

    function loadThemes() {
        $.getJSON(`${apiBase}?action=get_themes`, function (res) {
            if (res.success) {
                let html = '';
                res.data.forEach(t => {
                    const activeClass = t.is_active == 1 ? 'border-primary shadow' : '';
                    const badge = t.is_active == 1 ? '<span class="badge bg-primary">Active</span>' : '';
                    html += `
                        <div class="col-md-4">
                            <div class="card h-100 rounded-4 border-2 ${activeClass}">
                                <div class="card-body p-4 text-center">
                                    <i class="bi bi-palette2 fs-1 text-primary mb-3"></i>
                                    <h5 class="fw-bold mb-1">${t.theme_name}</h5>
                                    <p class="text-muted small mb-3">/${t.directory_name}</p>
                                    ${badge}
                                    <div class="mt-4 d-flex gap-2 justify-content-center">
                                        ${t.is_active == 0 ? `<button class="btn btn-sm btn-primary px-3 btn-activate" data-id="${t.id}">فعال کریں</button>` : ''}
                                        <button class="btn btn-sm btn-outline-danger px-3 btn-delete-theme" data-id="${t.id}" ${t.is_active == 1 ? 'disabled' : ''}>مٹائیں</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                });
                $('#themesGrid').html(html);
            }
        });
    }

    $(document).on('click', '.btn-activate', function () {
        const id = $(this).data('id');
        $.ajax({
            url: apiBase,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ action: 'activate_theme', id: id }),
            success: function (res) {
                if (res.success) {
                    Swal.fire('کامیابی', 'تھیم تبدیل کرلیا گیا', 'success');
                    loadThemes();
                }
            }
        });
    });

    $('#btnUploadTheme').on('click', function () {
        const { value: file } = Swal.fire({
            title: 'Select Theme ZIP',
            input: 'file',
            inputAttributes: {
                'accept': '.zip',
                'aria-label': 'Upload your theme ZIP file'
            },
            showCancelButton: true
        }).then((result) => {
            if (result.value) {
                const formData = new FormData();
                formData.append('theme_zip', result.value);

                $.ajax({
                    url: 'APIs/cms_upload_theme.php',
                    method: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        if (res.success) {
                            Swal.fire('Success', 'Theme uploaded successfully', 'success');
                            loadThemes();
                        } else {
                            Swal.fire('Error', res.error, 'error');
                        }
                    }
                });
            }
        });
    });

    $(document).on('click', '.btn-delete-theme', function () {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Are you sure?',
            text: "This will permanently delete the theme files!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: apiBase,
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ action: 'delete_theme', id: id }),
                    success: function (res) {
                        if (res.success) {
                            Swal.fire('Deleted!', 'Theme has been deleted.', 'success');
                            loadThemes();
                        } else {
                            Swal.fire('Error', res.message || 'Deletion failed', 'error');
                        }
                    }
                });
            }
        });
    });

    // AI Creator Logic
    $('#btnAiCreator').on('click', function () {
        currentStep = 1;
        updateAiStep();
        $('#aiCreatorModal').modal('show');
    });

    $('#btnAiNext').on('click', function () {
        if (currentStep < 3) {
            currentStep++;
            updateAiStep();
        }
    });

    $('#btnAiPrev').on('click', function () {
        if (currentStep > 1) {
            currentStep--;
            updateAiStep();
        }
    });

    function updateAiStep() {
        $('.ai-step').addClass('d-none');
        $(`#step${currentStep}`).removeClass('d-none');

        $('#aiProgress').css('width', (currentStep / 3) * 100 + '%');

        if (currentStep === 1) $('#btnAiPrev').addClass('d-none');
        else $('#btnAiPrev').removeClass('d-none');

        if (currentStep === 3) {
            $('#btnAiNext').addClass('d-none');
            $('#btnAiGenerate').removeClass('d-none');
        } else {
            $('#btnAiNext').removeClass('d-none');
            $('#btnAiGenerate').addClass('d-none');
        }
    }

    $('.color-opt').on('click', function () {
        $('.color-opt').removeClass('border-primary border-2');
        $(this).addClass('border-primary border-2');
        $('input[name="color_scheme"]').val($(this).data('color'));
    });

    $('#aiThemeForm').on('submit', function (e) {
        e.preventDefault();
        const data = {
            action: 'ai_create_theme',
            name: $('input[name="theme_name"]').val(),
            color: $('input[name="color_scheme"]').val(),
            layout: $('input[name="layout"]:checked').val()
        };

        const $btn = $('#btnAiGenerate');
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> لوڈ ہو رہا ہے...');

        $.ajax({
            url: apiBase,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (res) {
                $btn.prop('disabled', false).html('تھیم تیار کریں');
                if (res.success) {
                    $('#aiCreatorModal').modal('hide');
                    Swal.fire('کامیابی', 'AI تھیم تیار کرلیا گیا ہے!', 'success');
                    loadThemes();
                } else {
                    Swal.fire('خرابی', res.message, 'error');
                }
            }
        });
    });
});
