<?php

/**
 *
 * @package esigForminatorAdmin
 * @author  Arafat Rahman <arafatrahmank@gmail.com>
 */



if (!class_exists('esigForminatorAdmin')) :

    class esigForminatorAdmin{

        /**$value->type == 'captcha'
         * Instance of this class.
         * @since    1.0.1
         * @var      object
         */
        protected static $instance = null;
        public $name;
        
        private $plugin_slug = null;

        private static $forminatorFormId = null;

        public static function setForminatorFormID($ID)
        {
            self::$forminatorFormId = $ID;
        }
        public static function getForminatorFormID()
        {
            return self::$forminatorFormId;
        }

        /**
         * Slug of the plugin screen.
         * @since    1.0.1
         * @var      string
         */
        protected $plugin_screen_hook_suffix = null;

        /**
         * Initialize the plugin by loading admin scripts & styles and adding a
         * settings page and menu.
         * @since     0.1
         */
        public function __construct() {
            /*
             * Call $plugin_slug from public plugin class.
             */
            $plugin = ESIG_FORMINATOR::get_instance();
            $this->plugin_slug = $plugin->get_plugin_slug();
            
       
            add_filter('esig_sif_buttons_filter', array($this, 'EsignForminatorSifButtons'), 15, 1);
            add_filter('esig_text_editor_sif_menu', array($this, 'EsignForminatorSifTextMenu'), 15, 1);
            add_filter('esig_admin_more_document_contents', array($this, 'documentAddData'), 10, 1);
            add_action('wp_ajax_esig_forminator_form_fields', array($this, 'EsignForminatorFields'));
            add_action('admin_enqueue_scripts', array($this, 'enqueueAdminScripts'));
            add_shortcode('esigforminator', array($this, 'render_shortcode_esigforminator'));
            add_action('admin_menu', array($this, 'adminMenu'),999);
            add_action('admin_init', array($this, 'esig_almost_done_forminator_settings'));
            //add_filter('forminator_esignature_form_submitted_data', array($this, 'esignForminatorFormSubmittedData'), 15, 3);
            add_action('forminator_addon_esignature_after_entry_saved', array($this, 'esignAfterEntrySaved'), 10, 3);
            add_filter('forminator_form_ajax_submit_response', array($this, 'esignFormSubmitResponse'),15,2);
            // non ajax form submit response
            add_filter('forminator_form_submit_response', array($this, 'esignFormSubmitResponse'),15,2);
        
        }



       public function esignFormSubmitResponse($response, $form_id){

        global $forminatorDocID; 

        $inviteURL = WP_E_Sig()->meta->get($forminatorDocID,"esig_forminator_forms_invite_url");
        
        // Validate redirect URL to prevent open redirect attacks
        if(!empty($inviteURL)){ 
            $inviteURL = wp_sanitize_redirect($inviteURL);
            $inviteURL = wp_validate_redirect($inviteURL, home_url());
            
            if ($inviteURL) {
                $response['behav'] = "behaviour-redirect";
                $response['redirect'] = 1;
                $response['url'] = $inviteURL;
                $response['newtab'] = "sametab";
            }
         }
        
        return $response;

       }



       public function esignAfterEntrySaved($formId,$entry_model,$form_settings_instance){

        if (!function_exists('WP_E_Sig')) {
            return false;
        }
        
        $sad = new esig_sad_document();    
        $esignSettingMetaKey = get_post_meta($formId,'esign-forminator-meta-key',true);
        
        if(empty($esignSettingMetaKey)){
            return false;
        }
        
        $esignSetting = esigForminatorSetting::getEsignFormSetting($formId,$esignSettingMetaKey);
        
        if(empty($esignSetting) || !is_array($esignSetting)){
            return false;
        }

        foreach($esignSetting as $value){

            $signerInfo = esig_forminator_get('signer_info',$value);
            
            // Get signer_name - handle both direct array access and function call
            if ( is_array( $signerInfo ) && isset( $signerInfo['signer_name'] ) ) {
                // Direct array access - preserves array structure
                $signerName = $signerInfo['signer_name'];
            } else {
                // Fallback to function call
                $signerName = esig_forminator_get('signer_name',$signerInfo);
                // If function returns false, try direct access
                if ( $signerName === false && is_array( $signerInfo ) ) {
                    $signerName = isset( $signerInfo['signer_name'] ) ? $signerInfo['signer_name'] : '';
                }
            }
            
            $signerEmail =  esig_forminator_get('email',$signerInfo);
            $signingLogic =  esig_forminator_get('signing_logic',$value);
            $displayType =  esig_forminator_get('display_type',$value);
            $selectSad =  esig_forminator_sanitize_init(esig_forminator_get('select_sad_doc',$value));

            $reminderSettings =  esig_forminator_get('reminder_email_settings',$value);

        } 


        $submitted_data = $entry_model->meta_data; 
        
        // Handle signer_name as array (multi-select) or single value (backward compatibility)
        $signerNameValue = '';
        
        if ( is_array( $signerName ) && ! empty( $signerName ) ) {
            // Multiple name fields selected - combine them with spaces
            $nameParts = array();
            
            foreach ( $signerName as $nameFieldId ) {
                // Handle both string keys and numeric array indices
                $fieldId = is_string( $nameFieldId ) ? $nameFieldId : (string) $nameFieldId;
                
                if ( empty( $fieldId ) ) {
                    continue;
                }
                
                // Check if this is a sub-field (e.g., name-2-first-name, name-2-last-name)
                // Extract base field ID and sub-field name
                if ( preg_match('/^(.+?)-(prefix|first-name|middle-name|last-name)$/', $fieldId, $matches) ) {
                    $baseFieldId = $matches[1]; // e.g., "name-2"
                    $subFieldName = $matches[2]; // e.g., "first-name" or "last-name"
                    $fieldValue = '';
                    
                    // Check if base field exists in submitted_data
                    if ( array_key_exists( $baseFieldId, $submitted_data ) ) {
                        $baseFieldData = $submitted_data[$baseFieldId];
                        
                        // Handle array structure
                        if ( is_array( $baseFieldData ) ) {
                            // Check for nested value structure
                            if ( isset( $baseFieldData['value'] ) && is_array( $baseFieldData['value'] ) ) {
                                // Nested structure: $submitted_data['name-2']['value']['first-name']
                                if ( isset( $baseFieldData['value'][$subFieldName] ) ) {
                                    $fieldValue = $baseFieldData['value'][$subFieldName];
                                }
                            } elseif ( isset( $baseFieldData[$subFieldName] ) ) {
                                // Direct structure: $submitted_data['name-2']['first-name']
                                $fieldValue = $baseFieldData[$subFieldName];
                            }
                        }
                        
                        if ( ! empty( $fieldValue ) ) {
                            $fieldValueStr = is_string( $fieldValue ) ? $fieldValue : (string) $fieldValue;
                            if ( ! empty( trim( $fieldValueStr ) ) ) {
                                $nameParts[] = trim( $fieldValueStr );
                            }
                        }
                    }
                } else {
                    // Not a sub-field, try direct access
                    if ( array_key_exists( $fieldId, $submitted_data ) ) {
                        // Handle different data structures
                        if ( is_array( $submitted_data[$fieldId] ) ) {
                            $fieldValue = isset( $submitted_data[$fieldId]['value'] ) ? $submitted_data[$fieldId]['value'] : '';
                        } else {
                            $fieldValue = $submitted_data[$fieldId];
                        }
                        
                        if ( ! empty( $fieldValue ) ) {
                            $fieldValueStr = is_string( $fieldValue ) ? $fieldValue : (string) $fieldValue;
                            if ( ! empty( trim( $fieldValueStr ) ) ) {
                                $nameParts[] = trim( $fieldValueStr );
                            }
                        }
                    }
                }
            }
            
            if ( ! empty( $nameParts ) ) {
                $signerNameValue = implode( ' ', $nameParts );
            }
        } elseif ( ! empty( $signerName ) && ! is_array( $signerName ) ) {
            // Single name field (backward compatibility)
            $fieldId = is_string( $signerName ) ? $signerName : (string) $signerName;
            if ( array_key_exists( $fieldId, $submitted_data ) ) {
                if ( is_array( $submitted_data[$fieldId] ) ) {
                    $fieldValue = isset( $submitted_data[$fieldId]['value'] ) ? $submitted_data[$fieldId]['value'] : '';
                } else {
                    $fieldValue = $submitted_data[$fieldId];
                }
                if ( ! empty( $fieldValue ) ) {
                    $signerNameValue = is_string( $fieldValue ) ? $fieldValue : (string) $fieldValue;
                }
            }
        }
        
        $signerName = ! empty( $signerNameValue ) ? trim( $signerNameValue ) : '';
        
        if(array_key_exists($signerEmail,$submitted_data)){
            if ( is_array( $submitted_data[$signerEmail] ) ) {
                $signerEmail = isset( $submitted_data[$signerEmail]['value'] ) ? $submitted_data[$signerEmail]['value'] : $signerEmail;
            } else {
                $signerEmail = $submitted_data[$signerEmail];
            }
        }

        // Check if signer name is empty or invalid
        if (empty($signerName)) {
            return false;
        }
        
        // check for valid signer name 
        if(!WP_E_Sig()->validation->esig_valid_string($signerName)) {
            return false;
        }
        
        if (empty($signerEmail) || !is_email($signerEmail)) {
            return false;
        }

        $document_id = $sad->get_sad_id($selectSad);
            
        $docStatus  = WP_E_Sig()->document->getStatus($document_id);
            
        if($docStatus !="stand_alone") return false;

        if (!is_email($signerEmail)) return false;

        self::setForminatorFormID($formId);
        //sending email invitation / redirecting .
        self::esig_invite_document($document_id, $signerEmail, $signerName, $formId,$signingLogic,$displayType,$reminderSettings,$submitted_data);
    

    }

        public static function esig_invite_document($old_doc_id, $signerEmail, $signerName, $formId,$signingLogic,$displayType,$reminderSettings,$formData) {

            if (!function_exists('WP_E_Sig')) return false;

            /* make it a basic document and then send to sign */
            $old_doc = WP_E_Sig()->document->getDocument($old_doc_id);

            esigForminatorSetting::setEntryValue($formData);
    
            global $forminatorDocID,$esigForminatorSubmissionData;

            $esigForminatorSubmissionData = $formData;
            // Copy the document
            $doc_id = WP_E_Sig()->document->copy($old_doc_id);

            $forminatorDocID = $doc_id;

    
            WP_E_Sig()->meta->add($doc_id, 'esig_forminator_form_id', $formId);           
           

            WP_E_Sig()->document->saveFormIntegration($doc_id, 'forminator');
            
            esigForminatorSetting::save_submission_value($doc_id,$formData);
           
            $esig_common = new WP_E_Common();
            $esig_common->set_document_timezone($doc_id);
            // Create the user=
            $recipient = array(
                "user_email" => $signerEmail,
                "first_name" => $signerName,
                "document_id" => $doc_id,
                "wp_user_id" => '',
                "user_title" => '',
                "last_name" => ''
            );
    
            $recipient['id'] = WP_E_Sig()->user->insert($recipient);
    
            $doc_title = $old_doc->document_title . ' - ' . $signerName;
            // Update the doc title
    
            WP_E_Sig()->document->updateTitle($doc_id, $doc_title);
            WP_E_Sig()->document->updateType($doc_id, 'normal');
            WP_E_Sig()->document->updateStatus($doc_id, 'awaiting');
            
            $doc = WP_E_Sig()->document->getDocument($doc_id);
    
            // trigger an action after document save .
            do_action('esig_sad_document_invite_send', array(
                'document' => $doc,
                'old_doc_id' => $old_doc_id,
            ));
            
            if( esig_forminator_get("enabled_signing_reminder", $reminderSettings) == '1'){
                esigForminatorSetting::enableReminder($reminderSettings,$doc_id);
            }
           
            // Get Owner
            $owner = WP_E_Sig()->user->getUserByID($doc->user_id);
            // Create the invitation?
            $invitation = array(
                "recipient_id" => $recipient['id'],
                "recipient_email" => $recipient['user_email'],
                "recipient_name" => $recipient['first_name'],
                "document_id" => $doc_id,
                "document_title" => $doc->document_title,
                "sender_name" => $owner->first_name . ' ' . $owner->last_name,
                "sender_email" => $owner->user_email,
                "sender_id" => 'stand alone',
                "document_checksum" => $doc->document_checksum,
                "sad_doc_id" => $old_doc_id,
            );
    
            $invite_controller = new WP_E_invitationsController();

            WP_E_Sig()->meta->add($doc_id, "esig_forminator_forms_invite_url", '');
           
            global $esigForminatorDocid;
            $esigForminatorDocid = $doc_id;

            if ($signingLogic == "email") { 
                            
                if ($invite_controller->saveThenSend($invitation, $doc)) 
                {
                    return true;
                }
       
            } 
            elseif ($signingLogic == "redirect") 
            {
                $invitation_id = $invite_controller->save($invitation);
                $invite_hash = WP_E_Sig()->invite->getInviteHash($invitation_id);
                $invite_url = WP_E_Invite::get_invite_url($invite_hash, $doc->document_checksum); 
                WP_E_Sig()->meta->add($doc_id, "esig_forminator_forms_invite_url", wp_sanitize_redirect(urldecode( $invite_url)));
            }

        }


        public function render_shortcode_esigforminator($atts) 
        {
            
            extract(shortcode_atts(array(
                'formid' => '',
                'label' => '', 
                'field_id' => '', 
                'field_type' => '',
                'display' => '',
                'option' => 'default'
                            ), $atts, 'esigforminator'));
            
            if (!function_exists('WP_E_Sig')) return '';
            
            // Validate formid and field_id are provided
            if (empty($formid) || empty($field_id)) {
                return '';
            }
            
            // Check if the field exists in the form
            // This prevents errors when fields are removed from the form but shortcodes remain in the document
            if (class_exists('Forminator_API')) {
                $field = Forminator_API::get_form_field($formid, $field_id, true);
                
                // If field doesn't exist, check if it's a multi-name sub-field (e.g., name-1-first-name)
                // In that case, check if the base field exists (e.g., name-1)
                if ((empty($field) || !is_array($field)) && preg_match('/^(.+?)-(prefix|first-name|middle-name|last-name)$/', $field_id, $matches)) {
                    $base_field_id = $matches[1];
                    $field = Forminator_API::get_form_field($formid, $base_field_id, true);
                }
                
                // If field still doesn't exist, return empty string to prevent errors
                if (empty($field) || (!is_array($field) && !is_object($field))) {
                    return '';
                }
                
                // Use the current field label from Forminator instead of the hardcoded shortcode label
                // This ensures the label is always up-to-date even if changed in Forminator
                if (is_array($field) && !empty($field['field_label'])) {
                    $label = $field['field_label'];
                } elseif (is_object($field) && isset($field->field_label)) {
                    $label = $field->field_label;
                }
            }
            
            $csum = sanitize_text_field(esig_forminator_get('csum'));
            if (empty($csum)) {
                $documentId = get_option('esig_global_document_id');
            } else {
                $documentId = WP_E_Sig()->document->document_id_by_csum($csum);
            }

            $esignSettingMetaKey = get_post_meta($formid,'esign-forminator-meta-key',true);

            $esignSetting = array();
            
            if(!empty($esignSettingMetaKey)){
                    $esignSetting = esigForminatorSetting::getEsignFormSetting($formid,$esignSettingMetaKey);
            }

            foreach($esignSetting as $value){
                $displayType =  esig_forminator_get('display_type',$value);            
            }

            global $forminatorDocID, $esigForminatorSubmissionData;
            $getEmtry = esigForminatorSetting::getEntryValue();
            if($getEmtry){   
                $forminatorData = $getEmtry;
            }
            elseif(!is_null($esigForminatorSubmissionData))
            {
                $forminatorData = $esigForminatorSubmissionData; 
            }
            else
            {
                $forminatorData = esigForminatorSetting::get_submission_value($documentId);
            }          
            
            $forminatorValue = esigForminatorSetting::generateValue($forminatorData,$field_id, $field_type, $display, $label,$formid,$displayType);
        
            $newFormId = self::getForminatorFormID();

            if (!$forminatorValue) return '';
            $allowOtherFormData = apply_filters("esig_forminator_allow_otherform_data",false);
            if(!wp_validate_boolean($allowOtherFormData))
            {
            if ($newFormId != $formid) return '';
            }

            return esigForminatorSetting::display_value($forminatorValue, $displayType);
        }

        public function documentAddData($more_contents) {
    
            
            $document_view = new esigForminatorDocumentView();
            $more_contents .= $document_view->add_document_view();    
                     
            return $more_contents;
        }

        public function EsignForminatorSifButtons($sif_menu) {
    
            $esig_type = esig_forminator_get('esig_type');
            $document_id = esig_forminator_sanitize_init(esig_forminator_get('document_id'));
    
            if (empty($esig_type) && !empty($document_id)) {
    
                $document_type = WP_E_Sig()->document->getDocumenttype($document_id);
                if ($document_type == "stand_alone") {
                    $esig_type = "sad";
                }
            }
    
            if ($esig_type != 'sad') return $sif_menu;
    
            $sif_menu .= ' {text: "Forminator Data",value: "forminator", onclick: function () { tb_show( "+ Forminator option", "#TB_inline?width=450&height=300&inlineId=esig-forminator-option");esign.tbSize(450);}},';
    
            return $sif_menu;
        }
    
        public function EsignForminatorSifTextMenu($sif_menu) {
    
            $esig_type = esig_forminator_get('esig_type');
            $document_id = esig_forminator_sanitize_init(esig_forminator_get('document_id'));
    
            if (empty($esig_type) && !empty($document_id)) {
                $document_type = WP_E_Sig()->document->getDocumenttype($document_id);
                if ($document_type == "stand_alone") {
                    $esig_type = "sad";
                }
            }
    
            if ($esig_type != 'sad') return $sif_menu;
            $sif_menu['forminator'] = array('label' => "Forminator Form Data");
            return $sif_menu;
        }

        public function EsignForminatorFields() {

            // Security: Verify nonce for CSRF protection
            if (!check_ajax_referer('esig_forminator_form_fields', 'esig_forminator_nonce', false)) {
                die('Security check failed');
            }

            // Security: Check user capabilities
            if (!current_user_can('edit_posts')) {
                die('Permission denied');
            }

            // Security: Check E-Signature plugin is available
            if (!function_exists('WP_E_Sig')) {
                die('E-Signature plugin not available');
            }

            // Security: Check current user is e-signature sender
            if (!WP_E_Sig()->user->checkEsigAdmin(get_current_user_id())) {
                die('Not authorized');
            }

            // Security: Validate and sanitize form_id
            $form_id = isset($_POST['form_id']) ? absint($_POST['form_id']) : 0;
            if (empty($form_id)) {
                die('Invalid form ID');
            }
    
            $html = '';
    
            $html .= '<select name="esig_forminator_field_id" class="chosen-select" style="width:250px;">';
            $html .= '<option value="all" >Insert all fields</option>';
            
            $formFields = Forminator_Api::get_form_fields($form_id);
            
            foreach ($formFields as $key=>$value) {

                if($value->type == 'captcha' || $value->type == 'postdata') {
                    continue;
                }
               
                $labelName = $value->field_label;
                $field_id = $value->element_id;
                $label = $value->field_label;
                $type = $value->type;  

                if($value->type == 'time'){                   
                    $label = "Timepicker";
                    $labelName = "Timepicker";
                }elseif($value->type == 'address'){                   
                    $label = "Address";
                    $labelName = "Address";
                }elseif($value->type == 'html'){                   
                    $label = "HTML";
                    $labelName = "HTML";
                }
                     
                
                $html .= '<option data-type="' . esc_attr($type) . '" data-id="' . esc_attr($label) . '" value="' . esc_attr($field_id) . '">' . esc_html($labelName) . '</option>';
            }

            echo $html;
    
            die();
        }
    
        public function enqueueAdminScripts() {
    
    
            
            $screen = get_current_screen();
            $admin_screens = array(
                'admin_page_esign-add-document',
                'admin_page_esign-edit-document',
                'e-signature_page_esign-view-document',
            );
    
            if (in_array(esig_forminator_get("id",$screen), $admin_screens)) {
                
                wp_enqueue_script('jquery');
                wp_enqueue_script('esig-forminator-add-admin-script', plugins_url('assets/js/esig-add-forminator.js', __FILE__), array('jquery', 'jquery-ui-dialog'), '0.1.0', true);
                
                // Localize script with nonce for AJAX security
                wp_localize_script('esig-forminator-add-admin-script', 'esigForminatorAjax', array(
                    'ajaxurl' => admin_url('admin-ajax.php'),
                    'esig_forminator_nonce' => wp_create_nonce('esig_forminator_form_fields')
                ));
            }
            
            if (esig_forminator_get("id",$screen) != "plugins") {
                wp_enqueue_script('esig-forminator-control-admin-script', plugins_url('assets/js/esig-forminator-control.js', __FILE__), array('jquery', 'jquery-ui-dialog'), '0.1.0', true);
            }

            if ( strpos(esig_forminator_get("id",$screen), 'esign-forminator-about') !== false){
               
                wp_enqueue_script('esign-forminator-iframe-script', plugins_url('assets/js/esign-iframe.js', __FILE__), array('jquery', 'jquery-ui-dialog'), '0.0.1', true);
               
                wp_register_style( 'esig-forminator-enqueue-style', plugins_url('about/assets/css/esig-about.css', __FILE__), false, '1.0.0' );
                wp_enqueue_style('esig-forminator-enqueue-style' );
                wp_enqueue_style( 'esig-google-fonts', 'https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@200;300;400;600;700;900&display=swap', false );
                wp_enqueue_style( 'esig-forminator-snip-styles', plugins_url('about/assets/css/esign-snip-styles.css', __FILE__), false, '1.0.0' );
            }
    
        }

        public function adminMenu() {
            $esigAbout = new esig_forminator_addon_about("Forminator");
            add_submenu_page('forminator', __('E-signature', 'esig'), __('E-signature', 'esig'), 'read', 'admin.php?page=esign-forminator-about', array($esigAbout, 'about_page'), 999);
       }

        final function esig_almost_done_forminator_settings() {

            
            if (!function_exists('WP_E_Sig'))
                return;

            // getting sad document id 
            $sadDocumentId = ESIG_GET('doc_preview_id');


            if (!$sadDocumentId) {
                return;
            }
            // creating esignature api here 
            $api = new WP_E_Api();

            $documents = $api->document->getDocument($sadDocumentId);


            $documentContent = $documents->document_content;

            $documentRaw = $api->signature->decrypt(ENCRYPTION_KEY, $documentContent);

            
           
          if (has_shortcode($documentRaw, 'esigforminator')) {

               
                
                preg_match_all('/' . get_shortcode_regex() . '/s', $documentRaw, $matches, PREG_SET_ORDER);

                //$forminator_shortcode = $matches[0][0];
                
                $forminatorShortcode = '';
                $forminatorFormid = '';
                foreach ($matches as $match) {

                    
                    if (in_array('esigforminator', $match)) {
                        
                        $atts = shortcode_parse_atts($match[0]);
                        extract(shortcode_atts(array(
                    'formid' => '',
                    'field_id' => '', //foo is a default value
                                ), $atts, 'esigforminator'));
                        if(is_numeric($formid)){
                            $forminatorFormid = $formid ; 
                            break;
                        }
                         //$forminator_shortcode = $match[0];
                       
                    }
                }
               
                WP_E_Sig()->document->saveFormIntegration($sadDocumentId, 'forminator');
            
                $data = array("form_id" => $forminatorFormid);
                $displayNotice = dirname(__FILE__) . '/views/alert-almost-done.php';
                $api->view->renderPartial('', $data, true, '', $displayNotice);
         }
        }
        

       


        /**
         * Return an instance of this class.
         * @since     0.1
         * @return    object    A single instance of this class.
         */
        public static function get_instance() {

            // If the single instance hasn't been set, set it now.
            if (null == self::$instance) {
                self::$instance = new self;
            }

            return self::$instance;
        }

    }
    
endif;

