<?php
namespace esigFluentIntegration;

use Mpdf\Tag\U;
use WP_E_Invite;

class esigFluentSetting {

        
    public static function get_sad_documents()
    {
        if (!function_exists('WP_E_Sig'))
                return;

        $api = WP_E_Sig();


        if (!class_exists('esig_sad_document'))
             return;

        $sad = new \esig_sad_document();

        $sad_pages = $sad->esig_get_sad_pages();
      

        $choices = [];


        foreach ($sad_pages as $page) {
            $document_status = $api->document->getStatus($page->document_id);

            if ($document_status != 'trash') {
                if ('publish' === get_post_status($page->page_id) || 'private' === get_post_status($page->page_id)) {
                    $choices[$page->page_id] = get_the_title($page->page_id);
                    
                }
            }

            
        }

        return $choices;
    }

    public static function get_signer_info_field($form_id,$type)
    {
        $signerInfo = [];
        $formFields = esigFluentSetting::getFormFields($form_id,$type);
        foreach ($formFields as $field) {
            $signerInfo[$field['name']] = $field['label'];
        }

        return $signerInfo;
    }
   
    
     public static function getEntryValue($formId,$enttyID){

       
       $entyValue = wpFluent()->table('fluentform_entry_details')
                    ->where('form_id', $formId)
                    ->where('submission_id', $enttyID);

       return $entyValue ;

    }

    public static function getEsigFeedSettings($formId){

       $getEsigFeed = (new \FluentForm\App\Modules\Form\Form(wpFluentForm()));
       $feedValue = $getEsigFeed->getMeta($formId, 'wpesignature_feeds', true);

       return $feedValue ;

    }

    public static function getAllFluentForm(){
        $forms = wpFluent()->table('fluentform_forms')
								->select(['id', 'title'])
								->orderBy('id', 'DESC')
								->get();

        $formArray = json_decode(json_encode($forms), true);

        return $formArray;
    }

    public static function getHtmlFieldsValue($formID,$names){

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

        $forms = wpFluent()->table('fluentform_forms')
								->select(['form_fields'])
								->orderBy('id', 'DESC')
                                ->where('id', $formID)
								->get();

        $formArray = json_decode(json_encode($forms), true);
        if(!is_array($formArray)) return false;       
        $fields = json_decode($formArray[0]['form_fields'], true);
	    $labelname = '';

        if(!is_array($fields)) return false;

		foreach ($fields as $value) {
                 
                    foreach ($value as $name) {
                        
                        if(array_key_exists("html_codes",$name['settings'])){
                          return $name['settings']['html_codes'];
                                                 
                        }
                                        
                    }                     
		}               
            

    }

    public static function getAllFluentFormFields($formId){

        $forms = fluentFormApi('forms')->form($formId);
        $inputFields = $forms->inputs($with = ['admin_label']);
        foreach ($inputFields as $key=> $field) {            
            $fieldsArray[] = array("label" => $field['admin_label'] , "name" => $key, "type" => $field['element']) ; 
        }
        return $fieldsArray;
                
                
    }

    /**
     * Get field label from database using formId and field_id
     * This ensures we get the full label even if it contains spaces
     * 
     * @param int $formId The form ID
     * @param string $fieldId The field ID/name
     * @return string The field label or empty string if not found
     */
    public static function getFieldLabel($formId, $fieldId) {
        if (empty($formId) || empty($fieldId)) {
            return '';
        }

        if (!function_exists('fluentFormApi')) {
            return '';
        }

        try {
            $forms = fluentFormApi('forms')->form($formId);
            $inputFields = $forms->inputs($with = ['admin_label']);
            
            if (isset($inputFields[$fieldId]) && isset($inputFields[$fieldId]['admin_label'])) {
                return $inputFields[$fieldId]['admin_label'];
            }
        } catch (\Exception $e) {
            // If there's an error, return empty string
            return '';
        }

        return '';
    }

    public static function getFormFields($formId,$getType){

        $forms = fluentFormApi('forms')->form($formId);
        $inputFields = $forms->inputs($with = ['admin_label']);
        foreach ($inputFields as $key=> $field) {
            

            if($getType == 'email'){
                if($field['element'] == 'input_email'){
                    $fieldsArray[] = array("label" => $field['admin_label'] , "name" => $key) ;
                }
            }

           if($getType == 'name'){
                if($field['element'] == 'input_name' || $field['element'] == 'input_text'){
                    $fieldsArray[] = array("label" => $field['admin_label'] , "name" => $key) ;
                }
            }
              
            
             
        }
        return $fieldsArray;
   
    }

    public static function save_submission_value($document_id, $form_id, $formData) 
    {
        WP_E_Sig()->meta->add($document_id, "esig_fluent_forms_submission_value", json_encode($formData));
    }

    public static function checkboxValue($value)
    {
        if(!is_array($value)) return false;

        $items = '';
        foreach ($value as $item) {
            if ($item) {
                $items .= esc_attr($item) . ', ';
            }
        }
        return substr($items, 0, -2);
    }

    public static function checkboxGridValue($value)
    {
        if(!is_array($value)) return false;

        $items = '';
        foreach ($value as $key => $item) {
            // Security: Escape key to prevent XSS
            $escaped_key = esc_html($key);
            if(is_array($item)){
                foreach ($item as $newItem) {
                    $items .= '<li>'. $escaped_key .' - <label><input type="checkbox" onclick="return false;" readonly checked="checked" style="margin-right: 5px;"></label>' . esc_attr($newItem) . '</li>';
                }
            }else{
                $items .= '<li>'. $escaped_key .' - <label><input type="radio" onclick="return false;" readonly checked="checked" style="margin-right: 5px;"></label>' . esc_attr($item) . '</li>';         
            }

        }
        return  "<ul class='esig-checkbox-tick'>$items</ul>";
    }
    

    public static function repeaterValue($value)
    {
        if (!is_array($value)) return false;
        $items = '';
        foreach ($value as $val) {

            foreach ($val as $item) {
                if ($item) {
                    // Security: Escape item to prevent XSS
                    $escaped_item = esc_html($item);
                    $items .=  $escaped_item . '<br>';
                }
            }
        } 
        return $items; 
    }

    public static function arrayValue($value)
    {
        if (!is_array($value)) return false;
        $items = '';
        foreach ($value as $item) {
            if ($item) {
                // Security: Escape item to prevent XSS
                $escaped_item = esc_html($item);
                $items .=  $escaped_item . ' ';
            }
        }
        return $items; 
    }

    public static function addressValue($value)
    {
        if(!is_array($value)) return false;
        $result = '';
        foreach ($value as $key => $val) {

            if ($key == 'country') {
                $countries = getFluentFormCountryList();
                // Security: Escape country value to prevent XSS
                $escaped_country = isset($countries[$val]) ? esc_html($countries[$val]) : esc_html($val);
                $result .= $escaped_country . '.';
            } else {
                if ($val) {
                    // Security: Escape address value to prevent XSS
                    $escaped_val = esc_html($val);
                    $result .= $escaped_val . ',  ';
                }
            }
        }
        return $result;
    }


    public static function fileValue($value,$style)
    {
        
        $items = '';
            foreach ($value as $item) {               
                if ($item) {
                    // Security: Escape URL and filename to prevent XSS
                    $escaped_url = esc_url($item);
                    $escaped_filename = esc_html(basename($item));
                    $escaped_style = esc_attr($style);
                    $items .=  '<a href="'.$escaped_url.'" style="'.$escaped_style.'">'.$escaped_filename.'</a><br>';  
                }
            }
                           
        return $items;
    }

    public static function generateValue($data,$fieldId,$formId,$displayType,$field_type)
    {
        $style = '';
        if($displayType == 'underline'){
            $style = 'text-decoration:underline;';
        }

        if(!is_array($data)) return false;
        $value  = esig_esff_get($fieldId,$data);

     
        switch($field_type){
            case "input_checkbox":
                return self::checkboxValue($value);
                break;
            case "tabular_grid":
                return self::checkboxGridValue($value);
                break;
            case "repeater_field":
                return self::repeaterValue($value);
                break;
            case "address":
                return self::addressValue($value);
                break;
            case "html":
                return self::getHtmlFieldsValue($formId, 'html_codes');
                break;            
            case "input_email":
                $safe_email = sanitize_email( $value );
                return '<a style="' . esc_attr($style) . '" href="mailto:' . esc_attr($safe_email) . '" target="_blank">' . esc_html($safe_email) . '</a>';
                break;
            case "input_url":
                return '<a style="'. esc_attr($style) .'" href="' . esc_url($value) . '" target="_blank">' . esc_attr($value) . '</a>' ;
                break;
            case "input_image":
            case "input_file":            
                return self::fileValue($value,$style);
                break;
            default:
                if(is_array($value)) return self::arrayValue($value);
                return esc_html($value);
        }
    }

            /**
         * Generate fields option using form id
         * @param type $form_id
         * @return string
         */
        public static function get_value($data,$label,$formid,$field_id, $display, $option,$submit_type,$field_type) {
            
            // Get label from database instead of relying on shortcode attribute
            // This ensures we get the full label even if it contains spaces
            $dbLabel = self::getFieldLabel($formid, $field_id);
            
            // Use database label if available, otherwise fall back to shortcode label
            $label = !empty($dbLabel) ? $dbLabel : (is_string($label) ? trim($label) : '');
            
            if ($display == "label") {
                return $label;
            }

            $displayValue = self::generateValue($data,$field_id,$formid,$submit_type,$field_type);

            if($display == "value") return $displayValue;

            if($display == "label_value") {
                // Ensure we have a valid label before concatenating
                if (!empty($label) && $displayValue !== false) {
                    return $label . ": " . $displayValue;
                } elseif (!empty($label)) {
                    // If value is false/empty, still return the label
                    return $label;
                } elseif ($displayValue !== false) {
                    // If label is empty but value exists, return just the value
                    return $displayValue;
                }
            }

            return false;

        }
        
        
        /**
         * Wrap a field value with underline markup if the display type requires it.
         *
         * Values passed here are already escaped by generateValue() per field type,
         * so no additional escaping is applied — doing so would double-escape HTML
         * returned for email/URL/file fields.
         *
         * @since  2.0.1
         * @access public
         *
         * @param  string $ff_value    Already-escaped/sanitized field value or HTML markup.
         * @param  string $submit_type Display type: 'underline' or anything else.
         *
         * @return string
         */
        public static function display_value($ff_value, $submit_type) {
            if ($submit_type == "underline") {
                return '<u>' . $ff_value . '</u>';
            }
            return $ff_value;
        }
    
        public static function parseInput($string)
        {
            $results = preg_replace('/^{(.*)}$/', '$1', $string);
            $array = explode(".", $results);
            return esig_esff_get("1",$array);
        }

        public static function prepareNames($names)
        {
            if(!is_array($names)) return false;
            $result = false;
            foreach($names as $name)
            {
                $result .= $name . " ";
            }
            return rtrim($result);
        }

    
}
