<?php
function ftm_write_css($css_fields)
{

    //BASIC REQUIRED VARIABLES
    $counter = 1;
    $temp = $temp_latest = "";
    $css_fields_quantity = count($css_fields);
    $file_name = FTM_BASE_CSS_CUSTOMIZER_FILE_PATH;

    foreach ($css_fields as $field => $key) {

        if ($counter == 1) {
            $temp .= ":root{" . $field . ": " . $key . ";";
        } elseif ($counter == $css_fields_quantity) {
            $temp .= $field . ": " . $key . ";}";
        } else {
            $temp .= $field . ": " . $key . ";";
        }

        $counter++;
    }

    if (!is_dir(FTM_BASE_CSS_CUSTOMIZER_CSS_DIR)) {
        wp_mkdir_p(FTM_BASE_CSS_CUSTOMIZER_CSS_DIR);
    }

    //Get current CSS file
    if (file_exists($file_name)) {

        $latest_file = fopen($file_name, "r");
        $temp_latest = fgets($latest_file);
        fclose($latest_file);
    }

    //Check if there's any difference and write the new css file if it does
    if ($temp_latest != $temp) {

        $css_file = fopen($file_name, "w+");
        fwrite($css_file, $temp);
        fclose($css_file);
    }    
}

function webpack($file, $buildDirectory = 'dist'){
    static $manifest;
    static $manifestPath;

    if (is_null($manifest) || $manifestPath !== $buildDirectory) {
        $manifest = json_decode(
            file_get_contents(get_template_directory_uri() . "/" . $buildDirectory . '/manifest.json'),
            true
        );

        $manifestPath = $buildDirectory;
    }

    if (isset($manifest[$file])) {
        return get_template_directory_uri() . "/" . trim($buildDirectory . '/' . $manifest[$file], '/');
    }

    throw new InvalidArgumentException("File {$file} not defined in asset manifest.");
}

function get_states_list(){
    $usStates = array(
        'AL' => 'Alabama',
        'AK' => 'Alaska',
        'AZ' => 'Arizona',
        'AR' => 'Arkansas',
        'CA' => 'California',
        'CO' => 'Colorado',
        'CT' => 'Connecticut',
        'DE' => 'Delaware',
        'FL' => 'Florida',
        'GA' => 'Georgia',
        'HI' => 'Hawaii',
        'ID' => 'Idaho',
        'IL' => 'Illinois',
        'IN' => 'Indiana',
        'IA' => 'Iowa',
        'KS' => 'Kansas',
        'KY' => 'Kentucky',
        'LA' => 'Louisiana',
        'ME' => 'Maine',
        'MD' => 'Maryland',
        'MA' => 'Massachusetts',
        'MI' => 'Michigan',
        'MN' => 'Minnesota',
        'MS' => 'Mississippi',
        'MO' => 'Missouri',
        'MT' => 'Montana',
        'NE' => 'Nebraska',
        'NV' => 'Nevada',
        'NH' => 'New Hampshire',
        'NJ' => 'New Jersey',
        'NM' => 'New Mexico',
        'NY' => 'New York',
        'NC' => 'North Carolina',
        'ND' => 'North Dakota',
        'OH' => 'Ohio',
        'OK' => 'Oklahoma',
        'OR' => 'Oregon',
        'PA' => 'Pennsylvania',
        'RI' => 'Rhode Island',
        'SC' => 'South Carolina',
        'SD' => 'South Dakota',
        'TN' => 'Tennessee',
        'TX' => 'Texas',
        'UT' => 'Utah',
        'VT' => 'Vermont',
        'VA' => 'Virginia',
        'WA' => 'Washington',
        'WV' => 'West Virginia',
        'WI' => 'Wisconsin',
        'WY' => 'Wyoming'
    );

    return $usStates;
}

function get_current_state(){
    // Check if the "currState" cookie is set
    if (isset($_COOKIE['currState'])) {
        $currStateValue = $_COOKIE['currState'];
        return $currStateValue;
      } else {
        return null;
      }
}

function add_geo_meta_tag() {
    $currentState =  get_current_state();

    if(! is_null($currentState)){
        echo '<meta name="geo.region" content="'.$currentState.'" />';
    }    
}
add_action( 'wp_head', 'add_geo_meta_tag' );


function ftm_get_text_excerpt($content, $excerpt_length = 60, $add_elipsis = true) {
    // Strip HTML tags and shortcodes from the content
    $content = strip_tags($content);
    
    // Get the first 60 words from the stripped content
    $words = preg_split("/[\s]+/", $content, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
    if (count($words) > $excerpt_length) {
        array_pop($words); // Remove the last word (incomplete word)
    }
    
    // Create the text-only excerpt
    if($add_elipsis){
        $excerpt = implode(' ', $words) . '...';
    }
    else{
        $excerpt = implode(' ', $words);
    }    
    
    return $excerpt;
}

function ftm_get_estimated_time_to_read($content) {
    $content = wp_strip_all_tags( $content );
    $time = floor(str_word_count($content)/200);
    
    if($time < 1){
        return ' <i>-</i> <span class="post-time-to-read">Less than a minute.</span>';
    }

    return ' <i>-</i> <span class="post-time-to-read">'. $time . ' min read</span>';
}

// Function to load more posts via AJAX
function ftm_load_more_posts() {
    $offset = intval($_POST['offset']);
    
    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => 9, // Change to the number of posts to load
        'orderby'        => 'date',
        'order'          => 'DESC',
        'offset'         => $offset,
        'post_status'    => 'publish'
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) :
        $output = '';
        while ($query->have_posts()) : $query->the_post();
            // Display post content as needed            
            $output .= '<article>';
            if (has_post_thumbnail()) {
                $output .= '<div class="post-thumbnail">';
                $output .= '<a href="' . get_the_permalink() . '">';
                $output .=  get_the_post_thumbnail(null,'medium');
                $output .= '<div class="post_meta">';
                $output .= '<span class="author">By: ' . get_the_author_meta( 'nicename') . '&nbsp;|&nbsp;</span>';
                $output .= '<span class="post-date">' . get_the_modified_date() . '</span>';
                $output .= '</div>';
                $output .= '</a>';
                $output .= '</div>';
            }

            $output .= '<h4><a href="' . get_the_permalink() .'">' . get_the_title() . '</a></h4>';
            $output .= '<div class="post_excerpt">';
            $output .= ftm_get_text_excerpt(get_the_content(),25);
            $output .= '</div>';
            $output .= '</article>';         
        endwhile;
        echo $output;
        wp_reset_postdata();
    else :
        echo 'no-more-posts';
    endif;

    die(); // Always end with die() for AJAX
}

// Hook for the AJAX action
add_action('wp_ajax_ftm_load_more_posts', 'ftm_load_more_posts');
add_action('wp_ajax_nopriv_ftm_load_more_posts', 'ftm_load_more_posts');

function ftm_custom_pagination($query = null) {

    global $wp_query;    

    if(!is_null($query)){
        $paginating_query = $query;
    }
    else
    {
        $paginating_query = $wp_query;
    }    

    $big = 999999999; // A large number unlikely to be exceeded.
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

    $pagination_args = array(
        //'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
        //'format' => '/page/%#%',
        'current' => max(1, $paged),
        'total' => $paginating_query->max_num_pages,
        'prev_text' => __('Previous', 'FTM-Base'),
        'next_text' => __('Next', 'FTM-Base'),
    );

    echo '<div class="ftm-custom-pagination">';
    echo paginate_links($pagination_args);
    echo '</div>';
}