<?php

namespace GriffinForms\Admin\Html\Modals;

class CreateFolder extends \GriffinForms\Admin\Html\Modals\Format
{   
    protected $config;
    protected $icon_files = array();
    
    protected function setIconFiles()
    {
        $this->icon_files = array_diff(
            scandir($this->config->getRootPath() . 'admin/images/folder'), array('..', '.', '.DS_Store')
        );
    }
    
    protected function headerText()
    {
        $text = $this->lang->getText('create_folder');
        return $text;
    }
    
    protected function modalContent()
    {
        echo '<div class="container" id="griffinforms-modal-createfolder-wrap">';
        echo '<div id="griffinforms-createfolder-error" class="gf-notice gf-notice-danger" style="display: none;"></div>';
        $this->folderPreview();
        $this->folderSelectionIcons();
        $this->nameOption();
        $this->descriptionOption();
        echo '</div>';
        
    }
    
    protected function folderPreview()
    {
        $src = $this->config->getRootUrl() . 'admin/images/folder/1.png';
        echo '<div class="row">';
        echo '<div class="col-md-12 text-center">';
        echo '<img id="griffinforms-modal-createfolder-preview" src="' . esc_url($src) . '" width="96">';
        echo '</div>';
        echo '</div>';
        
    }
    
    protected function folderSelectionIcons()
    {
        echo '<div class="row mt-3">';
        echo '<div class="col-md-12 d-flex justify-content-center">';

        foreach ($this->icon_files as $icon) {
            if ($icon === 'default.png') {
                continue;
            }
            $src = $this->config->getRootUrl() . 'admin/images/folder/' . $icon;
            $icon_name = rtrim($icon, '.png');
            echo '<div class="mx-2">';
            echo '<img class="griffinforms-modal-createfolder-icon" src="' . esc_url($src) . ' " width="24" data-file="' . esc_attr($icon) . '" data-icon="' . esc_attr($icon_name) . '"></div>';
        }

        echo '</div>';
        echo '</div>';
    }
    
    protected function nameOption()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\InputText('folder_name', '');
        echo '<div class="row mt-4">';
        echo '<div class="col-md-3 text-end">';
        echo '<label class="form-label me-2">' . esc_html($this->lang->getText('folder_name_label')) . '</label>';
        echo '</div>';
        echo '<div class="col-md-9">';
        $field->html();
        echo '</div>';
        echo '</div>';
    }
    
    protected function descriptionOption()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\TextArea('folder_description', '');
        echo '<div class="row mt-4">';
        echo '<div class="col-md-3 text-end">';
        echo '<label class="form-label me-2">' . esc_html($this->lang->getText('folder_description_label')) . '</label>';
        echo '</div>';
        echo '<div class="col-md-9">';
        $field->html();
        echo '</div>';
        echo '</div>';
        
    }
    
    protected function actionBtn($text = 'save', $btn_class = 'primary')
    {
        $id = 'griffinforms-modalaction-' . strtolower($this->meta);
        $wp_class = $btn_class === 'primary' ? 'button button-primary' : 'button';
        echo '<button type="button" id="' . esc_attr($id) . '" class="' . esc_attr($wp_class) . '">';
        echo esc_html($this->lang->getText($text));
        echo '</button>';
    }
    
    public function modalJs()
    {
        $nonce = wp_create_nonce('create_item');
        
        ob_start();
        ?>
        jQuery(document).ready(function($) {
        
            $(".griffinforms-modal-createfolder-icon").click(function() {
                var src = $(this).attr("src");
                $("#griffinforms-modal-createfolder-preview").attr("src", src);
                $(".griffinforms-modal-createfolder-icon").removeClass("griffinforms-modal-createfolder-selectedfolder");
                $(this).addClass("griffinforms-modal-createfolder-selectedfolder");
            });
            
            $("#griffinforms-modalaction-createfolder").click(function() {
                var itemData, data;
                $("#griffinforms-createfolder-error").hide();
                $(this).prop("disabled", true);
                itemData = {};
                itemData["name"] = $("#griffinforms-foldername-inputtext").val().trim();
                itemData["description"] = $("#griffinforms-folderdescription-textarea").val().trim();
                itemData["icon"] = $(".griffinforms-modal-createfolder-selectedfolder").attr("data-icon");
                
                if (!itemData["name"]) {
                    showErrorMessage("<?php esc_html_e('Please enter folder name.', 'griffinforms-form-builder'); ?>");
                    $(this).prop("disabled", false);
                    return;
                }
                
                itemData = JSON.stringify(itemData);
                
                data = {
                    "action": "createItem",
                    "item_type": "folder",
                    "item_data": itemData,
                    "nonce": "<?php echo esc_js($nonce); ?>"
                };
                
                $.post(ajaxurl, data, function(response) {
                    if (typeof response !== 'object') {
                        try {
                            response = JSON.parse(response);
                        } catch (e) {
                            showErrorMessage("<?php echo esc_html($this->lang->getText('network_error_message')); ?>");
                            $("#griffinforms-modalaction-createfolder").prop("disabled", false);
                            return;
                        }
                    }

                    if (response.success) {
                        resetCreateFolderModal();                            
                        $("#griffinforms-createfolder-modal").modal('hide');
                        $("#griffinforms-selectfolder-modal").data('triggeredFrom', 'newItem').modal('show');
                    } else {
                        let msg = response.msg || "<?php esc_html_e('Error creating folder.', 'griffinforms-form-builder'); ?>";
                        showErrorMessage(msg);
                    }

                    $("#griffinforms-modalaction-createfolder").prop("disabled", false);
                }).fail(function() {
                    showErrorMessage("<?php esc_html_e('Error processing request.', 'griffinforms-form-builder'); ?>");
                    $("#griffinforms-modalaction-createfolder").prop("disabled", false);
                });
            });
    
            function resetCreateFolderModal() {
                $("#griffinforms-foldername-inputtext").val('');
                $("#griffinforms-folderdescription-textarea").val('');                    
                $(".griffinforms-modal-createfolder-selectedfolder").removeClass("griffinforms-modal-createfolder-selectedfolder");                    
                $("#griffinforms-modal-createfolder-preview").attr("src", "<?php echo esc_url($this->config->getRootUrl() . 'admin/images/folder/1.png'); ?>");
            }
    
            function showErrorMessage(message) {
                $("#griffinforms-createfolder-error").text(message).show();
            }
            
        });
        <?php
        $inline_js = ob_get_clean();
    
        wp_add_inline_script('griffinforms-global-js', $inline_js);
    }
}