<?php
/**
 * Display general settings
 */
function mych_post_autob_display() { 

    // Get the progress from the session or initialize it to 0 if not set
    $success = '';
    // Check if the form is submitted


    $campaign_id = isset($_GET['id']) ? intval($_GET['id']) : 0;


    if ($campaign_id > 0) {
      global $wpdb;
      $table_name = $wpdb->prefix . 'mych_article_autocampaigns';

      $campaign = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $campaign_id), ARRAY_A);

      if ($campaign) {
          $title = $campaign['title'];
          $status = $campaign['pstatus'];
          $content_length = $campaign['content_length'];
          $content_language = $campaign['content_language'];
          $writing_style = $campaign['writing_style'];
          $writing_tone = $campaign['writing_tone'];
          $generate_tag = $campaign['generate_tag'];
          $generate_seo = $campaign['generate_seo'];
          $generate_faq = $campaign['generate_faq'];
          $generate_conc = $campaign['generate_conc'];
          $interval_time = $campaign['interval_time'];
           $category_id = $campaign['category_id'];

          // Retrieve other fields from the database
          // Rest of your form code
      }
  }





    if (isset($_POST['schdule-bulk-submit'])) {



      if ($campaign_id > 0) {
         // Editing an existing campaign
         // Retrieve and validate the submitted data
         $title = sanitize_text_field($_POST['cicg-api-post-title']);
      
         $status = sanitize_text_field($_POST['cicg-select-poststatus']);
         $content_length = intval($_POST['cicg_content_length']);
         $content_language = sanitize_text_field($_POST['cicg-select-lenguage']);
         $writing_style = sanitize_text_field($_POST['cicg_writing_style']);
         $writing_tone = sanitize_text_field($_POST['cicg_writing_tone']);
         $generate_tag = isset($_POST['cicg-generate-tag']) ? 'on' : 'off';
         $generate_faq = isset($_POST['cicg-generate-faq']) ? 'on' : 'off';
         $generate_conc = isset($_POST['cicg-generate-conc']) ? 'on' : 'off';
         $generate_seo = isset($_POST['cicg-generate-seo']) ? 'on' : 'off';

         $interval_time = sanitize_text_field($_POST['cicg-select-interval']);
 
         // Update the campaign data in the database
         global $wpdb;
         $table_name = $wpdb->prefix . 'mych_article_autocampaigns';
     



               $result = $wpdb->update(
                  $table_name,
                  array(
                      'title' => $title,
                      'pstatus' => $status,
                      'content_length' => $content_length,
                      'content_language' => $content_language,
                      'writing_style' => $writing_style,
                      'writing_tone' => $writing_tone,
                      'generate_tag' => $generate_tag,
                      'generate_faq' => $generate_faq,
                      'generate_conc' => $generate_conc,
                      'generate_seo' => $generate_seo,
                      'category_id' => sanitize_text_field($_POST['cicg-select-postcategory']),
                      'status' => 'run',
                      'interval_time' => $interval_time,
                  ),
                  array('id' => $campaign_id)
              );
            if ($result === false) {
                echo "Error: " . $wpdb->last_error;
            } else {
                $success = '2';
            }



     } else {

        // Sanitize and validate user inputs
        if (isset($_POST['cicg-api-post-title']) && !empty($_POST['cicg-api-post-title'])) {

        $title = sanitize_text_field($_POST['cicg-api-post-title']);
        $status = sanitize_text_field($_POST['cicg-select-poststatus']);
        $content_length = intval($_POST['cicg_content_length']);
        $content_language = sanitize_text_field($_POST['cicg-select-language']);
        $writing_style = sanitize_text_field($_POST['cicg_writing_style']);
        $writing_tone = sanitize_text_field($_POST['cicg_writing_tone']);
        $generate_tag = isset($_POST['cicg-generate-tag']) ? 'on' : 'off';
        $generate_faq = isset($_POST['cicg-generate-faq']) ? 'on' : 'off';
        $generate_conc = isset($_POST['cicg-generate-conc']) ? 'on' : 'off';
        $interval_time = sanitize_text_field($_POST['cicg-select-interval']);
        $generate_seo = isset($_POST['cicg-generate-seo']) ? 'on' : 'off';

        global $wpdb;
        $table_name = $wpdb->prefix . 'mych_article_autocampaigns';
    
        // Insert data into the custom table

                        $result = $wpdb->insert($table_name, array(
                        'title' => $title,
                        'pstatus' => $status,
                        'content_length' => $content_length,
                        'content_language' => $content_language,
                        'writing_style' => $writing_style,
                        'writing_tone' => $writing_tone,
                        'generate_tag' => $generate_tag,
                        'generate_faq' => $generate_faq,
                        'generate_seo' => $generate_seo,
                        'generate_conc' => $generate_conc,
                        'category_id' => sanitize_text_field($_POST['cicg-select-postcategory']),
                        'status' => 'run',
                        'interval_time' => $interval_time,
                    ));
                    if ($result === false) {
                        echo "Error: " . $wpdb->last_error;
                    } else {
                        $success = '1';
                    }
    
    } 
    else {
        echo '<p style="color:#ff0000;">Title cannot be empty</p>';
    }
   }

}
    ?>
   <div class="">
      <h3><?php echo esc_html( __('ChatGPT Autoblogging Setup','caacg') ); ?></h3>
   </div>
   <?php if($success==1){ ?>
   <div class="success" >
      <h3 style="color:#4BB543"><?php echo esc_html( __('We have received your request. Please be patience. Your articles will start appearing in your posts section shortly.','caacg') ); ?></h3>
   </div>
   <?php }   ?>
   <?php if($success==2){ ?>
   <div class="success" >
      <h3 style="color:#4BB543"><?php echo esc_html( __('Update has been succesfully done.. Your articles will start appearing in your posts section shortly.','caacg') ); ?></h3>
   </div>
   <?php }   ?>   
   <div class="cicg_chat-gpt-general-settings">
       <?php
             if ($campaign_id > 0) { ?>
        <form method="post" action="admin.php?page=autoblog-articles&id=<?php echo $campaign_id;?>">
            <?php } else { ?>
         <form method="post" action="admin.php?page=autoblog-articles">
            <?php } ?>
            <?php settings_fields( 'cicg-chatgpt-openai-content-generator-settings-group' ); ?>
            <?php do_settings_sections( 'cicg-chatgpt-openai-content-generator-settings-group' ); ?>
            <?php 
            $cicg_api_key = esc_attr( get_option('cicg_chatgpt_api_key') );
            $cicg_api_max_tokens = esc_attr( (get_option('cicg_chatgpt_api_max_tokens')) ? get_option('cicg_chatgpt_api_max_tokens') : 4000 );
            $cicg_api_temperature = esc_attr( (get_option('cicg_api_temperature')) ? get_option('cicg_api_temperature') : 1 );
            ?>

<div class="cicg_section-content-api" id="cicg_section-content-api">
    
   <table class="form-table ">
      <tr valign="top">
         <th scope="row"><?php echo esc_html(__('Title','caacg')); ?></th>
         <td>
     <input type="text" name="cicg-api-post-title" id="cicg-api-post-title" placeholder="<?php echo esc_html(__('Enter a topic for your blog title.'));?>" value="<?php echo esc_attr(!empty($title) ? $title : ''); ?>"
 />
       <a href="#" id="keyword-research-link" style="margin-left: 10px;"><?php echo esc_html(__('Keyword Research','caacg')); ?></a>

         </td>
      </tr>

      <?php
      $status = isset($status) ? $status : '';
      $generate_tag = isset($generate_tag) ? $generate_tag : 'off';
      $generate_faq = isset($generate_faq) ? $generate_faq : 'off';
      $generate_conc = isset($generate_conc) ? $generate_conc : 'off';
      $generate_seo = isset($generate_seo) ? $generate_seo : 'off';


      ?>
      <tr valign="top">
         <th scope="row"><?php echo esc_html(__('Post status','caacg')); ?></th>
         <td>
                <select id="cicg-select-poststatus" name="cicg-select-poststatus">
               <option value="publish" <?php selected('publish', $status); ?>><?php echo esc_html__('Publish','caacg'); ?></option>
               <option value="draft" <?php echo esc_attr('draft'); ?><?php selected('draft', $status); ?>><?php echo esc_html__('Draft','caacg'); ?></option>
               </select>
         </td>
      </tr>
      <tr valign="top">
            <th scope="row"><?php echo esc_html(__('Post Category','caacg')); ?></th>
            <td>
               <?php
               $args = array(
                     'show_option_all' => esc_html__('Select a category', 'caacg'),
                     'orderby' => 'name',
                     'hide_empty' => 0,
                     'name' => 'cicg-select-postcategory', // Name attribute for the select element
                     'id' => 'cicg-select-postcategory', // ID attribute for the select element
                     'taxonomy' => 'category', // Taxonomy to use (post categories)
                     'class' => 'postform', // CSS class for the select element
               );

               wp_dropdown_categories($args);
               $interval_time = isset($interval_time) ? $interval_time : 'em'; // Set a default value
        // Set the selected category based on $category_id
        echo '<script>';
        echo 'document.getElementById("cicg-select-postcategory").value = ' . intval($category_id) . ';';
        echo '</script>';

               ?>
            </td>
      </tr>

      <tr valign="top">
    <th scope="row"><?php echo esc_html(__('Interval', 'caacg')); ?></th>
    <td>
        <select id="cicg-select-interval" name="cicg-select-interval">
            <option value="em" <?php selected('em', $interval_time); ?>>
                <?php echo esc_html('Every Minute (only for testing)', 'caacg'); ?>
            </option>
            <option value="hourly" <?php selected('hourly', $interval_time); ?>>
                <?php echo esc_html('Hourly', 'caacg'); ?>
            </option>
            <option value="e3hours" <?php selected('e3hours', $interval_time); ?>>
                <?php echo esc_html('Every 3 hours', 'caacg'); ?>
            </option>
            <option value="e6hours" <?php selected('e6hours', $interval_time); ?>>
                <?php echo esc_html('Every 6 hours', 'caacg'); ?>
            </option>
            <option value="e12hours" <?php selected('e12hours', $interval_time); ?>>
                <?php echo esc_html('Every 12 hours', 'caacg'); ?>
            </option>
            <option value="e24hours" <?php selected('e24hours', $interval_time); ?>>
                <?php echo esc_html('Every 24 hours', 'caacg'); ?>
            </option>
            <option value="e3days" <?php selected('e3days', $interval_time); ?>>
                <?php echo esc_html('Every 3 days', 'caacg'); ?>
            </option>
            <option value="week" <?php selected('week', $interval_time); ?>>
                <?php echo esc_html('Once a week', 'caacg'); ?>
            </option>
        </select>
    </td>
</tr>



      <tr valign="top">
         <th scope="row"><?php echo esc_html(__('Content length','caacg')); ?></th>
         <td>
               <input type="number" name="cicg_content_length" id="cicg-content-length" value="<?php echo esc_attr($content_length ? $content_length : 300); ?>" />
         </td>
      </tr>

<?php
      $languages = array(
    'en' => 'English',
    'fr' => 'French',
    'de' => 'German',
    'es' => 'Spanish',
    'it' => 'Italian',
    'pt' => 'Portuguese',
    'nl' => 'Dutch',
    'ru' => 'Russian',
    'ar' => 'Arabic',
    'zh' => 'Chinese (Simplified)',
    'zh-TW' => 'Chinese (Traditional)',
    'ja' => 'Japanese',
    'ko' => 'Korean',
    'hi' => 'Hindi',
    'bn' => 'Bengali',
    'ur' => 'Urdu',
    'fa' => 'Persian (Farsi)',
    'tr' => 'Turkish',
    'el' => 'Greek',
    'pl' => 'Polish',
    'cs' => 'Czech',
    'hu' => 'Hungarian',
    'fi' => 'Finnish',
    'sv' => 'Swedish',
    'no' => 'Norwegian',
    'da' => 'Danish',
    'is' => 'Icelandic',
    'ga' => 'Irish',
    'eu' => 'Basque',
    'et' => 'Estonian',
    'lv' => 'Latvian',
    'lt' => 'Lithuanian',
    'ro' => 'Romanian',
    'sr' => 'Serbian',
    'sk' => 'Slovak',
    'sl' => 'Slovenian',
    'uk' => 'Ukrainian',
    'hr' => 'Croatian',
    'bg' => 'Bulgarian'
);

?>

<tr valign="top">
    <th scope="row"><?php echo esc_html(__('Language', 'caacg')); ?></th>
    <td>
        <select id="cicg-select-language" name="cicg-select-language">
            <?php
            foreach ($languages as $code => $name) {
                $selected = (isset($content_language) && $content_language === $code) ? 'selected' : '';
                echo '<option value="' . esc_attr($code) . '" ' . $selected . '>' . esc_html($name) . '</option>';
            }
            ?>
        </select>
    </td>
</tr>
<?php
$writing_styles = array(
    'formal' => 'Formal',
    'informal' => 'Informal',
    'technical' => 'Technical',
    'creative' => 'Creative',
    'professional' => 'Professional',
    'persuasive' => 'Persuasive',
    'narrative' => 'Narrative',
    'humorous' => 'Humorous',
    'educational' => 'Educational',
    'scientific' => 'Scientific',
    'expository' => 'Expository',
    'descriptive' => 'Descriptive',
    'analytical' => 'Analytical',
    'comparative' => 'Comparative',
    'argumentative' => 'Argumentative',
    'instructional' => 'Instructional',
    'editorial' => 'Editorial',
    'review' => 'Review',
    'personal' => 'Personal',
    'reflective' => 'Reflective',
);
?>
<tr valign="top">
    <th scope="row"><?php echo esc_html(__('Writing Style', 'caacg')) ?></th>
    <td>
    <select name="cicg_writing_style" id="cicg-writing-style">
    <?php
    foreach ($writing_styles as $style => $label) {
        $selected = (isset($writing_style) && $writing_style === $style) ? 'selected="selected"' : '';
        echo '<option value="' . esc_attr($style) . '" ' . $selected . '>' . esc_html($label) . '</option>';
    }
    ?>
</select>

    </td>
</tr>
<?php
$writing_tones = array(
    'formal' => 'Formal',
    'informal' => 'Informal',
    'humorous' => 'Humorous',
    'persuasive' => 'Persuasive',
    'descriptive' => 'Descriptive',
    'instructional' => 'Instructional',
    'empathetic' => 'Empathetic',
    'critical' => 'Critical',
    'optimistic' => 'Optimistic',
    'educational' => 'Educational',
);

?>

<tr valign="top">
    <th scope="row"><?php echo esc_html(__('Writing Tone', 'caacg')) ?></th>
    <td>
        <select name="cicg_writing_tone" id="cicg-writing-tone">
            <?php
            foreach ($writing_tones as $tone => $label) {
                $selected = (isset($writing_tone) && $writing_tone === $tone) ? 'selected' : '';
                echo '<option value="' . esc_attr($tone) . '" ' . $selected . '>' . esc_html($label) . '</option>';
            }
            ?>
        </select>
    </td>
</tr>

<tr valign="top">
    <th scope="row"><?php echo esc_html(__('SEO Optimize', 'caacg')) ?></th>
    <td>
        <label class="switch">
            <input type="checkbox" name="cicg-generate-seo" class="switch-input" <?php checked('on', $generate_seo); ?>>
            <span class="switch-label" data-on="On" data-off="Off"></span>
            <span class="switch-handle"></span>
        </label>
    </td>
</tr>

<tr valign="top">
    <th scope="row"><?php echo esc_html(__('Generate Tags', 'caacg')) ?></th>
    <td>
        <label class="switch">
            <input type="checkbox" name="cicg-generate-tag" class="switch-input" <?php checked('on',  $generate_tag); ?>>
            <span class="switch-label" data-on="On" data-off="Off"></span>
            <span class="switch-handle"></span>
        </label>
    </td>
</tr>

<tr valign="top">
    <th scope="row"><?php echo esc_html(__('Generate FAQ', 'caacg')) ?></th>
    <td>
        <label class="switch faq">
            <input type="checkbox" name="cicg-generate-faq" class="switch-input" <?php checked('on', $generate_faq); ?>>
            <span class="switch-label" data-on="On" data-off="Off"></span>
            <span class="switch-handle"></span>
        </label>
    </td>
</tr>



      <tr valign="top">
            <th scope="row"><?php echo esc_html(__('Generate Conclusion','caacg')) ?></th>
            <td>
               <label class="switch conc">
                  <input type="checkbox" name="cicg-generate-conc"class="switch-input" <?php checked('on', $generate_conc); ?>>
                  <span class="switch-label" data-on="On" data-off="Off"></span>
                  <span class="switch-handle"></span>
               </label>
            </td>
      </tr>

      <tr valign="top" style="display: none;">
            <th scope="row"><?php echo esc_html(__('Add youtube video','caacg')) ?></th>
            <td>
               <label class="switch youtube" id="include-youtube-videos">
                  <input type="checkbox" class="switch-input" id="maddyoutubevideo" checked>
                  <span class="switch-label" data-on="On" data-off="Off"></span>
                  <span class="switch-handle"></span>
               </label>
            </td>
      </tr>
      <tr valign="top" id="youtube-videos-section" style="display: none;">
            <th scope="row"><p><?php echo esc_html(__('Choose where to embed YouTube videos:', 'caacg')); ?></p>
            </th>
            <td>
            <div id="" >
                     <label>
                        <input type="checkbox" name="youtube-video-top" value="1">
                        <?php echo esc_html(__('Top of Page', 'caacg')); ?>
                     </label>
                     <label>
                        <input type="checkbox" name="youtube-video-middle" value="1">
                        <?php echo esc_html(__('Middle of Page', 'caacg')); ?>
                     </label>
                     <label>
                        <input type="checkbox" name="youtube-video-end" value="1">
                        <?php echo esc_html(__('Right Before End of Page', 'caacg')); ?>
                     </label>
              </div>
            </td>
      </tr>      
      <input type="hidden" name="campaign_id" value="<?php echo esc_attr($campaign_id); ?>">

</table>


</div>
<p class="submit"><input type="submit" name="schdule-bulk-submit" id="schdule-bulk-submit" class="button button-primary" value="Schedule Article"></p>   
     </form>
<div id="keyword-research-popup" style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%, -50%); background-color:#fff; padding:20px; box-shadow:0px 0px 10px rgba(0,0,0,0.5); z-index:9999;">
    <span id="close-popup" style="cursor:pointer; float:right;font-size:20px;">&times;</span>
    <h2>Keyword Research</h2>
    <input type="text" id="keyword-input" placeholder="Enter keyword" style="width:100%; padding:10px; margin-bottom:10px;">
        <div id="empty-keyword-message" style="color: red; display: none;">Keyword cannot be empty</div>
    <div id="loading-icon" style="font-weight:bold;display: none;">Loading...</div>

    <button id="search-keywords" style="padding:10px 20px;">Search</button>
        <div id="suggestions" class="suggestions"></div>
</div>
<script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            var keywordLink = document.getElementById('keyword-research-link');
            var popup = document.getElementById('keyword-research-popup');
            var closePopup = document.getElementById('close-popup');
            var searchButton = document.getElementById('search-keywords');
            var keywordInput = document.getElementById('keyword-input');
            var suggestions = document.getElementById('suggestions');
            var titleInput = document.getElementById('cicg-api-post-title');
    var emptyKeywordMessage = document.getElementById('empty-keyword-message');
    var loadingIcon = document.getElementById('loading-icon');

            keywordLink.addEventListener('click', function(event) {
                event.preventDefault();
                popup.style.display = 'block';
            });

            closePopup.addEventListener('click', function() {
                popup.style.display = 'none';
            });

            searchButton.addEventListener('click', function() {
                var keyword = keywordInput.value;
                if (keyword) {
                    emptyKeywordMessage.style.display = 'none';
                    fetchKeywords(keyword);
                } else {
                 emptyKeywordMessage.style.display = 'block';
                }
            });
  
    
      function fetchKeywords(keyword) {
                  loadingIcon.style.display = 'block';
        fetch('<?php echo admin_url('admin-ajax.php'); ?>?action=get_keywords&keyword=' + encodeURIComponent(keyword))
            .then(response => response.json())
            .then(data => {
            loadingIcon.style.display = 'none';
            if (data.success && Array.isArray(data.data.keywords)) {
                    showSuggestions(data.data.keywords);
                } else {
                    
                    
                    console.error('Invalid response or no keywords found:', data);
                    suggestions.innerHTML = '';
                }
            })
            .catch(error => {
                loadingIcon.style.display = 'none';
                console.error('Error fetching keywords:', error);
                suggestions.innerHTML = '';
            });
    }

            
         


          function insertKeyword(keyword) {
                titleInput.value = keyword;
                popup.style.display = 'none';
            }
            
             function showSuggestions(keywords) {
                suggestions.innerHTML = '';
                keywords.forEach(function(keyword) {
                    var item = document.createElement('div');
                    item.classList.add('suggestion-item');
                    item.textContent = keyword;
                    item.addEventListener('click', function() {
                        insertKeyword(keyword);
                    });
                    suggestions.appendChild(item);
                });
                suggestions.style.display = 'block';
            }    

            keywordInput.addEventListener('input', function() {
                var value = keywordInput.value.toLowerCase();
                var items = suggestions.querySelectorAll('.suggestion-item');
                items.forEach(function(item) {
                    if (item.textContent.toLowerCase().includes(value)) {
                        item.style.display = 'block';
                    } else {
                        item.style.display = 'none';
                    }
                });
                suggestions.style.display = items.length ? 'block' : 'none';
            });
        });
        </script>
<style>
#keyword-research-popup {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 400px;
    padding: 20px;
    background: #000;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    
}

#keyword-research-popup #popup-content {
    text-align: center;
}

#keyword-research-popup h3 {
    margin-top: 0;
    color:#fff;
}

#keyword-research-popup input[type="text"] {
            width: calc(100% - 22px);
            padding: 10px;
            margin-bottom: 10px;
            background: #333;
            border: 1px solid #444;
            color: #fff;

}

        #keyword-research-popup button {
            padding: 10px 20px;
            margin-top: 10px;
            cursor: pointer;
            background: #444;
            border: 1px solid #555;
            color: #fff;
        }

        #keyword-results {
            margin-top: 20px;
            max-height: 200px;
            overflow-y: auto;
        }

        #keyword-results p {
            margin: 0;
            padding: 10px;
            background: #444;
            border: 1px solid #555;
            border-radius: 4px;
        }

        #keyword-results p:hover {
            background: #555;
        }
                .suggestions {
            border: 1px solid #ccc;
            max-height: 150px;
            overflow-y: auto;
            display: none;
        }
        .suggestion-item {
            padding: 10px;
            cursor: pointer;
        }
        .suggestion-item:hover {
            background-color: #f0f0f0;
        }
        .cicg_section-content-api input#cicg-api-post-title{
            width:40%;
        }
        @media (max-width: 767px) {
            .cicg_section-content-api input#cicg-api-post-title {
                width: 100%;
            }
        }


    
</style>     
   </div>


   <?php return;	
}