<?php

namespace GPLoker\Inc;

use function add_action;
use function count;
use function get_option;
use function get_post;
use function get_template_part;
use function get_transient;
use function in_array;
use function is_post_type_archive;
use function set_transient;
use function wp_slash;

class Hooks {
    
    private static bool $instance = false;

    public function __construct() {
        
        if ( self::$instance === false ) {
            self::$instance = true;
            
            add_filter( 'generate_search_title_output', [ $this, 'searchTitle' ] );
            add_filter( 'get_the_archive_title', [ $this, 'archiveTitle' ], 10, 3 );
            add_filter( 'generate_do_template_part', [ $this, 'isChangeTemplatePart' ], 10, 2 );
    
            add_action( 'generate_before_do_template_part', [ $this, 'templatePart' ] );
            add_action( 'generate_after_entry_content', [ $this, 'relatedJobs' ], 10 );
    
            # disable comment on job detail
            add_filter( 'comments_open', [ $this, 'closeComments' ] );
            add_filter( 'get_comment_author_link', [ $this, 'commentDisableLink' ] );
    
            # set post views
            add_action( 'wp_body_open', [ $this, 'setViewPost' ] );
    
            # set query posts by post views
            add_filter( 'generateblocks_query_loop_args', [ $this, 'GPQueryByPostViews' ], 10, 2 );
    
            add_filter( 'generate_svg_icon', [ $this, 'GPSVGIcon' ], 15, 2 );
    
            add_action( 'pre_get_posts', [ $this, 'jobsOnly' ] );
    
            add_action('generate_before_main_content', [$this, 'blogSearchResults']);
    
            # handle no thumbnail
            add_action('generate_before_content', [$this, 'noThumbnailOnCompanyHandle'], 10);
    
            add_action( 'pre_get_posts', [$this, 'stickyJobsShowHanlder'] );
            
            
            add_filter('found_posts', function ($found_posts, $query) {
                if (!is_admin() && $query->is_main_query()
                    && (
                        is_post_type_archive('lowongan') 
                        || (is_search() && isset($_GET['location'])) 
                        || is_tax('loker-category')
                        || is_tax('loker-tags')
                        || is_tax('location')
                    )
                ) {
                    $stickyJobsId = self::getAllStickyJobsId();
                    if ($query->get('paged') == 1) {
                        return $found_posts - count($stickyJobsId);
                    }
                }
                return $found_posts;
            }, 10, 2);
    
            add_action('generate_before_loop', function () {
                
                if (  
                    is_post_type_archive('lowongan') 
                    || (is_search() && isset($_GET['location']))
                    || is_tax('loker-tags')
                    || is_tax('loker-category') 
                    || is_tax( 'location' )
                ) {
                    
                    $paged = get_query_var('paged') ? get_query_var('paged') : 1;
                    if ( $paged == 1 && $stickyJobsId = self::getAllStickyJobsId() ) {
                        
                        $filterStickyPosts = [];
                        
                        if ( is_tax('loker-tags') ) {
                            $term = get_queried_object();
                            if (!empty($term) && is_a($term, 'WP_Term')) {
                                foreach($stickyJobsId as $postId) {
                                    if ( has_term($term->slug, 'loker-tags', $postId) ) {
                                        $filterStickyPosts[] = $postId;
                                    }
                                }
                            }
                            
                            $stickyJobsId = $filterStickyPosts;
                            $filterStickyPosts = [];
                        }
                        
                        
                        if ( is_tax('loker-category') ) {
                            $term = get_queried_object();
                            if (!empty($term) && is_a($term, 'WP_Term')) {
                                foreach($stickyJobsId as $postId) {
                                    if ( has_term($term->slug, 'loker-category', $postId) ) {
                                        $filterStickyPosts[] = $postId;
                                    }
                                }
                            }
                            
                            $stickyJobsId = $filterStickyPosts;
                            $filterStickyPosts = [];
                        }
                        
                        if ( is_tax('location') ) {
                            $term = get_queried_object();
                            if (!empty($term) && is_a($term, 'WP_Term')) {
                                foreach($stickyJobsId as $postId) {
                                    if ( has_term($term->slug, 'location', $postId) ) {
                                        $filterStickyPosts[] = $postId;
                                    }
                                }
                            }
                            
                            $stickyJobsId = $filterStickyPosts;
                            $filterStickyPosts = [];
                        }
                        
                        // search handler
                        if ( is_search() && isset($_GET['location']) ) {
                            
                            $location = isset($_GET['location']) ? sanitize_text_field($_GET['location']) : '';
                            if ( $location !== '' ) {
                                foreach($stickyJobsId as $postId) {
                                    if ( has_term($location, 'location', $postId) ) {
                                        $filterStickyPosts[] = $postId;
                                    }
                                }
                                
                                $stickyJobsId = $filterStickyPosts;
                                $filterStickyPosts = [];
                            }
                            
                            
                            $category = isset($_GET['category']) ? sanitize_text_field($_GET['category']) : '';
                            
                            
                            if ( $category !== '' ) {
                                foreach($stickyJobsId as $postId) {
                                    if ( has_term($category, 'loker-category', $postId) ) {
                                        $filterStickyPosts[] = $postId;
                                    }
                                }
                                
                                $stickyJobsId = $filterStickyPosts;
                                $filterStickyPosts = [];
                            }
                            
                            
                            $xf = ! empty($_GET['xf']) ? wp_slash($_GET['xf']) : [];
                            if ( $xf !== [] ) {
                                $xfCount = count($xf);
                                foreach($stickyJobsId as $postId) {
                                    $valid = 0;
                                    foreach( $xf as $slug ) {
                                        if ( has_term($slug, 'loker-tags', $postId) ) {
                                            $valid++;
                                        }
                                    }
                                    
                                    if ( $valid === $xfCount ) {
                                        $filterStickyPosts[] = $postId;    
                                    }
                                }
                                
                                $stickyJobsId = $filterStickyPosts;
                                $filterStickyPosts=[];
                            }
                            
                        }
                        
                        
                        global $post;
                        $originPosts = $post;
                        foreach ($stickyJobsId as $postId) {
                            $post = get_post($postId);
                            get_template_part( 'template-part/content', 'job-item' );
                        }
                        
                        $GLOBALS['post'] = $originPosts;
                    }
                }
            });
    
            add_filter('the_posts_pagination_args', function($args) {
           
                global $wp_query;
                if ( $stickyJobsId = self::getAllStickyJobsId() ) {
                    
                    $posts_per_page = get_option('posts_per_page');
                    $total = ceil($wp_query->found_posts / $posts_per_page );
                
                    if ( is_post_type_archive('lowongan') ) {
                        $items = $wp_query->found_posts + (count($stickyJobsId));
                        $total = ceil( $items / $posts_per_page );    
                    }
                    
                    $filterStickyPosts = [];
                    if ( is_tax( 'loker-tags' ) ) {
                        $term = get_queried_object();
                        if (!empty($term) && is_a($term, 'WP_Term')) {
                            foreach($stickyJobsId as $postId) {
                                if ( has_term($term->slug, 'loker-tags', $postId) ) {
                                    $filterStickyPosts[] = $postId;
                                }
                            }
                        }
                    }
                    
                    if ( is_tax( 'location' ) ) {
                        $term = get_queried_object();
                        if (!empty($term) && is_a($term, 'WP_Term')) {
                            foreach($stickyJobsId as $postId) {
                                if ( has_term($term->slug, 'location', $postId) ) {
                                    $filterStickyPosts[] = $postId;
                                }
                            }
                        }
                    }
                    
                    if ( is_tax( 'loker-category' ) ) {
                        $term = get_queried_object();
                        if (!empty($term) && is_a($term, 'WP_Term')) {
                            foreach($stickyJobsId as $postId) {
                                if ( has_term($term->slug, 'loker-category', $postId) ) {
                                    $filterStickyPosts[] = $postId;
                                }
                            }
                        }
                    }
                    
                    if ( $filterStickyPosts !== [] ) {
                        $total = ceil( ($wp_query->found_posts + (count($filterStickyPosts))) / $posts_per_page );
                    }
                    
                    // total pages
                    $args['total'] = $total;
                }
                
                // var_dump($args);
                return $args;
            }, 10);
            
            
            add_action('csf__gploker_save_after', function() {
                delete_transient('_lowongan_page_title');
            });
            
            add_filter('pre_get_document_title', function($title) {
                if (is_post_type_archive('lowongan')) {
                    return $this->getArchiveTitle($title);
                }
                
                return $title;
            });
        }
    }

    public function isChangeTemplatePart( $boolean, $template ) {
        if (
            $template == 'index'
            || is_tax( 'loker-category' )
            || is_tax( 'loker-tags' )
            || is_tax( 'location' )
        ) {
            $boolean = false;
        }

        if (
            $template == 'search'
            &&
            (
                isset( $_GET['location'] )
                || isset( $_GET['category'] )
            )
        ) {
            $boolean = false;
        }

        if ( $template == 'index' && is_home() && ! is_front_page() ) {
            $boolean = true;
        }

        if ( $template == 'single' && get_post_type() == 'lowongan' ) {
            $boolean = false;
        }

        if ( $template == 'single' && get_post_type() == 'companies' ) {
            $boolean = false;
        }

        if ( $template == 'archive' && is_post_type_archive('lowongan') ) {
            $boolean = false;
        }

        if ( $template == 'none' ) {
            $boolean = true;
        }

        return $boolean;
    }

    public function templatePart( $template ) {


        if (
            $template == 'index'
            || is_tax( 'loker-category' )
            || is_tax( 'loker-tags' )
            || is_tax( 'location' )
        ) {
            if ( !is_home() && $template != 'none' && $template != 'search') {
                get_template_part( 'template-part/content', 'job-item' );
            }

        }

        if (
            $template == 'search'
            &&
            (
                isset( $_GET['location'] )
                || isset( $_GET['category'] )
                || isset( $_GET['xf'])
            )
        ) {
            get_template_part( 'template-part/content', 'job-item' );
        }

        if ( $template == 'single' && get_post_type() == 'lowongan' ) {
            get_template_part( 'template-part/content', 'single-job' );
        }

        if ( $template == 'single' && get_post_type() == 'companies' ) {
            get_template_part( 'template-part/content', 'single-company' );
        }

        if ( $template == 'archive' && is_post_type_archive('lowongan') ) {
            get_template_part( 'template-part/content', 'job-item' );
        }

    }

    public function searchTitle( $template ) {
        if ( !isset( $_GET['location'] ) && ! isset( $_GET['category'] ) ) {
            return $template;
        }

        global $wp_query;
        $keyword  = ! empty( $_GET['s'] ) ? sanitize_text_field( $_GET['s'] ) : '';
        $location = ! empty( $_GET['location'] ) ? sanitize_text_field( $_GET['location'] ) : '';
        $category = ! empty( $_GET['category'] ) ? sanitize_text_field( $_GET['category'] ) : '';
        $xf = ! empty($_GET['xf']) ? wp_slash($_GET['xf']) : [];

        if ( ! empty( $location ) ) {
            $location = str_replace( [ '-', '_' ], ' ', $location );
            $location = ucwords( $location );
        }

        if ( ! empty( $category ) ) {
            $category = str_replace( [ '-', '_' ], ' ', $category );
            $category = ucwords( $category );
        }

        $template = '<div ' . generate_get_attr( 'page-header' ) . '>';
        $template .= '<div class="search-result">';
        $template .= "<h2 class='widget-title'>Hasil Pencarian</h2>";

        $template .= '<div class="src">';
        if ( $keyword ) {
            $template .= "<b>{$keyword}</b>";
        }

        if ( $category ) {
            $template .= "<span>{$category}</span>";
        }

        if ( $location ) {
            $template .= "<span>{$location}</span>";
        }
        
        if ( $xf !== [] ) {
            foreach($xf as $item) {
                $term = get_term_by('slug', $item, 'loker-tags');
                
                if ($term) {
                    $template .= "<span>{$term->name}</span>";
                }
            }
            
        }

        $template .= '</div>';

        $template .= '<div class="search-result-count">';
        $template .= '<span class="result-count">' . $wp_query->found_posts . ' lowongan</span>';
        $template .= '</div>';

        $template .= '</div>';

        return $template;
    }

    private function getArchiveTitle($original_title = 'Lowongan Kerja')
    {
        $transient_key = '_lowongan_page_title';

        $title = get_transient($transient_key);
        if ($title === false) {
            
            $default_title = $original_title . ' Terbaru {{YEAR}}';
            $title = Option::get('job_archive_page_title', $default_title);
    
            $translations = [
                'DATE'             => current_time('d'),
                'DAY_NAME'         => date_i18n('l'),
                'MONTH'            => current_time('m'),
                'MONTH_NAME'       => date_i18n('F'),
                'MONTH_NAME_SHORT' => date_i18n('M'),
                'YEAR'             => current_time('Y')
            ];
    
            // Gantikan placeholder dalam judul dengan data dari $translations
            foreach ($translations as $key => $value) {
                $title = str_replace("{{{$key}}}", $value, $title);
            }
    
            // Simpan hasil ke dalam transient selama 10 detik
            set_transient($transient_key, $title, 10);
        }
        
        
        return $title;
    }

    public function archiveTitle( $title, $original_title, $prefix ) {
        
        if (is_post_type_archive('lowongan')) {
            return $this->getArchiveTitle($original_title);
        }
            
        return str_replace( ':', ' ', $prefix ) . $original_title;
    }

    public function relatedJobs() {
        if ( is_singular( 'lowongan' ) ) {
            echo '<h3>Lowongan Kerja Sejenis</h3>';
            GPLokerRelatedJobs();
        }
    }

    public function closeComments( $comments ) {
        if ( is_singular( 'lowongan' ) ) {
            return false;
        }

        return $comments;
    }

    public function commentDisableLink( $author_link ) {
        return strip_tags( $author_link );
    }

    public function setViewPost() {
        global $post;
        if ( is_singular() ) {
            $view_count = (int) get_post_meta( $post->ID, 'post_views_count', true );
            if ( empty( $view_count ) ) {
                $view_count = 0;
            }
            update_post_meta( $post->ID, 'post_views_count', $view_count + 1 );
        }
    }

    public function GPQueryByPostViews( $query_args, $attributes ) {
        if (
            ! empty( $attributes['className'] )
            && strpos( $attributes['className'], 'order_by_views' ) !== false
        ) {

            $query_args['post_type'] = 'post';

            $custom_args = array(
                'meta_key' => 'post_views_count',
                'orderby'  => 'meta_value_num',
                'order'    => 'DESC',
            );
        } else {
            return $query_args;
        }

        return array_merge( $query_args, $custom_args );
    }

    public function GPSVGIcon( $output, $icon ) {
        if ( 'menu-bars' === $icon ) {
            $svg = '<svg width="18" height="15" viewBox="0 0 18 15" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M0.599609 1.2C0.599609 0.53726 1.13686 0 1.79961 0H16.1996C16.8623 0 17.3996 0.53726 17.3996 1.2C17.3996 1.86274 16.8623 2.4 16.1996 2.4H1.79961C1.13686 2.4 0.599609 1.86274 0.599609 1.2Z" fill="black"></path> <path fill-rule="evenodd" clip-rule="evenodd" d="M0.599609 7.2C0.599609 6.5373 1.13686 6 1.79961 6H16.1996C16.8623 6 17.3996 6.5373 17.3996 7.2C17.3996 7.8628 16.8623 8.4 16.1996 8.4H1.79961C1.13686 8.4 0.599609 7.8628 0.599609 7.2Z" fill="black"></path> <path fill-rule="evenodd" clip-rule="evenodd" d="M0.599609 13.2C0.599609 12.5373 1.13686 12 1.79961 12L9.5 12C10.1627 12 10.7 12.5373 10.7 13.2C10.7 13.8628 10.1627 14.4 9.5 14.4L1.79961 14.4C1.13686 14.4 0.599609 13.8628 0.599609 13.2Z" fill="black"></path> </svg>';

            return sprintf(
                '<span class="gp-icon %1$s">
                %2$s
            </span>',
                $icon,
                $svg
            );
        }

        return $output;
    }

    public function jobsOnly( $query ) {
        if ( ! is_admin() && $query->is_search ) {
            if ( isset( $_GET['location'] ) || isset( $_GET['category'] ) || isset($_GET['xf'])) {
                $query->set( 'post_type', 'lowongan' );

                $tax_query = [];

                if ( ! empty( $_GET['category'] ) ) {

                    $term_slug = sanitize_text_field( $_GET['category'] );

                    $tax_query[] = [
                        'taxonomy' => 'loker-category',
                        'field'    => 'slug',
                        'terms'    => $term_slug,
                    ];

                }

                if ( ! empty($_GET['xf']) ) {
                    $term_slugs = wp_slash($_GET['xf']);
                    $tax_query[] = [
                        'taxonomy' => 'loker-tags',
                        'field'    => 'slug',
                        'terms'    => $term_slugs,
                    ];
                }

                if (count($tax_query) > 1) {
                    $tax_query['relation'] = 'AND';
                }

                if ( ! empty($tax_query) ) {
                    $query->set('tax_query', $tax_query);
                }
            }
        }
    }

    public function blogSearchResults() {
        if ( is_home() && ! is_front_page() && ! empty($_GET['s']) ) {
            ?>
            <div class="gploker-search-result-keyword">
                <h2>Search for: <?php echo sanitize_text_field($_GET['s']);?></h2>
            </div>
            <?php
        }
    }

    public function noThumbnailOnCompanyHandle() {
        global $post;
        
        if ( 
            $post 
            && ! has_post_thumbnail($post->ID) 
            && $post->post_type == 'companies' 
        ) {
            ?>
            <div class="featured-image default-featured-image page-header-image-single">
                <img src="//placehold.co/300x300" class="attachment-full size-full" alt="" decoding="async" itemprop="image">
            </div>
            <?php
        }
    }


    public static function getAllStickyJobsId()
    {
        $stickyJobsId = get_transient('gplokerpro_sticky_jobs_id');
        if ( !is_array($stickyJobsId) ) {
            $stickyJobsId = [];
            global $wpdb;
            $sql = "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='gplokerpro_is_sticky' AND meta_value='on'";
            $query = $wpdb->get_results($sql);

            foreach ($query as $item) {
                $post = get_post($item->post_id);
                $stickyJobsId[strtotime($post->post_date)] = $item->post_id;
            }
            krsort($stickyJobsId);
            set_transient('gplokerpro_sticky_jobs_id', $stickyJobsId, 15);
        }

        return $stickyJobsId;
    }

    public function stickyJobsShowHanlder($query)
    {
        if (!is_admin() && $query->is_main_query() 
            && ( 
                is_post_type_archive('lowongan') 
                || (is_search() && isset($_GET['location'])) 
                || is_tax( 'loker-category' )
                || is_tax( 'loker-tags' )
                || is_tax( 'location' )
            ) 
        ) {
            if ( $stickyJobsId = self::getAllStickyJobsId() ) {
                $paged = get_query_var('paged') ? get_query_var('paged') : 1;
                $offset = count($stickyJobsId);
                
                $posts_per_page = get_option('posts_per_page');
                
                $first_posts_per_page = $posts_per_page - $offset;
                    
                $query->set('post__not_in', $stickyJobsId);
                
                if ( $paged == 1) {
            
                    $query->set('posts_per_page', $first_posts_per_page);    
            
                } else {
            
                    $query->set('offset', $first_posts_per_page + ($paged - 2) * $posts_per_page);
                }
                
            }
        }
    }

}

new Hooks();