<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class OSF_Custom_Post_Type_Case_Study
 */
class Pakrco_Project {
    public $post_type = 'pakrco_project';
    public $taxonomy  = 'pakrco_project_cat';
    public $taxonomy_2  = 'pakrco_project_regions';
    static $instance;

    public static function getInstance() {
        if (!isset(self::$instance) && !(self::$instance instanceof Pakrco_Project)) {
            self::$instance = new Pakrco_Project();
        }

        return self::$instance;
    }

    public function __construct() {
        add_action('init', [$this, 'create_post_type']);
        add_action('init', [$this, 'create_taxonomy']);
        if (pakrco_is_cmb2_activated()) {
            add_action('init', [$this, 'setup_metabox']);
            add_action( 'cmb2_admin_init', array($this,'register_theme_options_metabox' ));
        }
    }

    public function setup_metabox() {
        add_action('cmb2_admin_init', [$this, 'metabox_projects']);
    }

    public function metabox_projects() {
        $symbol = !empty(get_option('portfolio_archive')['currency_symbol']) ? get_option('portfolio_archive')['currency_symbol'] : '$';
        $cmb2 = new_cmb2_box(array(
            'id'           => 'pakrco_projects_setting',
            'title'        => esc_html__('Infomation', 'pakrco'),
            'object_types' => array('pakrco_project'),
        ));

        $cmb2->add_field(array(
            'name' => esc_html__('Status', 'pakrco'),
            'id'   => 'project_status',
            'type' => 'text',
        ));

        $cmb2->add_field(array(
            'name' => esc_html__('Location', 'pakrco'),
            'id'   => 'project_location',
            'type' => 'text',
        ));

        $cmb2->add_field(array(
            'name' => esc_html__('Type', 'pakrco'),
            'id'   => 'project_type',
            'type' => 'text',
        ));

        $cmb2->add_field(array(
            'name' => __('Price Min (' . $symbol . ')', 'pakrco'),
            'id'   => 'project_price_min',
            'type' => 'text',
        ));

        $cmb2->add_field(array(
            'name' => __('Price Max (' . $symbol . ')', 'pakrco'),
            'id'   => 'project_price_max',
            'type' => 'text',
        ));
    }


    /**
     * @return void
     */
    public function create_post_type() {

        $labels = array(
            'name'               => esc_html__('Projects', 'pakrco'),
            'singular_name'      => esc_html__('Project', 'pakrco'),
            'add_new'            => esc_html__('Add New Project', 'pakrco'),
            'add_new_item'       => esc_html__('Add New Project', 'pakrco'),
            'edit_item'          => esc_html__('Edit Project', 'pakrco'),
            'new_item'           => esc_html__('New Project', 'pakrco'),
            'view_item'          => esc_html__('View Project', 'pakrco'),
            'search_items'       => esc_html__('Search Projects', 'pakrco'),
            'not_found'          => esc_html__('No Projects found', 'pakrco'),
            'not_found_in_trash' => esc_html__('No Projects found in Trash', 'pakrco'),
            'parent_item_colon'  => esc_html__('Parent Project:', 'pakrco'),
            'menu_name'          => esc_html__('Projects', 'pakrco'),
        );

        $labels     = apply_filters('pakrco_project_labels', $labels);
        $slug_field = apply_filters('pakrco_project_slug', 'project');

        register_post_type($this->post_type,
            array(
                'labels'        => $labels,
                'supports'      => array('title', 'editor', 'thumbnail'),
                'public'        => true,
                'has_archive'   => true,
                'rewrite'       => array('slug' => $slug_field),
                'menu_position' => 5,
                'categories'    => array(),
            )
        );
    }

    /**
     * @return void
     */
    public function create_taxonomy() {
        $labels = array(
            'name'              => esc_html__('Categories', 'pakrco'),
            'singular_name'     => esc_html__('Category', 'pakrco'),
            'search_items'      => esc_html__('Search Category', 'pakrco'),
            'all_items'         => esc_html__('All Categories', 'pakrco'),
            'parent_item'       => esc_html__('Parent Category', 'pakrco'),
            'parent_item_colon' => esc_html__('Parent Category:', 'pakrco'),
            'edit_item'         => esc_html__('Edit Category', 'pakrco'),
            'update_item'       => esc_html__('Update Category', 'pakrco'),
            'add_new_item'      => esc_html__('Add New Category', 'pakrco'),
            'new_item_name'     => esc_html__('New Category Name', 'pakrco'),
            'menu_name'         => esc_html__('Categories', 'pakrco'),
        );
        $labels = apply_filters('pakrco_project_cat_labels', $labels);

        $slug_cat_field = apply_filters('pakrco_cat_project_slug', 'project-cat');

        $args = array(
            'hierarchical'      => true,
            'labels'            => $labels,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'show_in_nav_menus' => true,
            'rewrite'           => array('slug' => $slug_cat_field)
        );
        // Now register the taxonomy
        register_taxonomy($this->taxonomy, array($this->post_type), $args);

        $labels_2 = array(
            'name'              => esc_html__('Regions', 'pakrco'),
            'singular_name'     => esc_html__('Regions', 'pakrco'),
            'search_items'      => esc_html__('Search Regions', 'pakrco'),
            'all_items'         => esc_html__('All Regions', 'pakrco'),
            'parent_item'       => esc_html__('Parent Regions', 'pakrco'),
            'parent_item_colon' => esc_html__('Parent Regions:', 'pakrco'),
            'edit_item'         => esc_html__('Edit Regions', 'pakrco'),
            'update_item'       => esc_html__('Update Regions', 'pakrco'),
            'add_new_item'      => esc_html__('Add New Regions', 'pakrco'),
            'new_item_name'     => esc_html__('New Regions Name', 'pakrco'),
            'menu_name'         => esc_html__('Regions', 'pakrco'),
        );
        $labels_2 = apply_filters('pakrco_project_regions_labels', $labels_2);

        $slug_cat_field_2 = apply_filters('pakrco_regions_project_slug', 'project-regions');

        $args_2 = array(
            'hierarchical'      => true,
            'labels'            => $labels_2,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'show_in_nav_menus' => true,
            'rewrite'           => array('slug' => $slug_cat_field_2)
        );
        // Now register the taxonomy
        register_taxonomy($this->taxonomy_2, array($this->post_type), $args_2);
    }

    public function get_term_project($post_id) {
        $terms = get_the_terms($post_id, $this->taxonomy);
        $output = '';
        if (!is_wp_error($terms) && is_array($terms)) {
            foreach ($terms as $key => $term) {
                $term_link = get_term_link($term);
                if (is_wp_error($term_link)) {
                    continue;
                }
                $output .= '<a href="' . esc_url($term_link) . '">' . $term->name . '</a>';
                if ($key < count($terms) - 1) {
                    $output .= ', ';
                }
            }

        }
        return $output;
    }

    public function get_region_project($post_id) {
        $terms = get_the_terms($post_id, $this->taxonomy_2);
        $output = '';
        if (!is_wp_error($terms) && is_array($terms)) {
            foreach ($terms as $key => $term) {
                $term_link = get_term_link($term);
                if (is_wp_error($term_link)) {
                    continue;
                }
                $output .= '<a href="' . esc_url($term_link) . '">' . $term->name . '</a>';
                if ($key < count($terms) - 1) {
                    $output .= ', ';
                }
            }

        }
        return $output;
    }

    public function get_all_meta_field_value() {
        $result = array(
            'project_status'    => array(),
            'project_location'  => array(),
            'project_type'      => array(),
            'project_price_min' => 0,
            'project_price_max' => 0
        );
        $args   = array(
            'post_type'      => 'pakrco_project',
            'posts_per_page' => -1,
        );

        $items = new WP_Query($args);

        if ($items->have_posts()) {
            while ($items->have_posts()) : $items->the_post();
                if (get_post_meta(get_the_ID(), 'project_status')) {
                    if (!in_array(get_post_meta(get_the_ID(), 'project_status', true), $result['project_status'])) {
                        array_push($result['project_status'], get_post_meta(get_the_ID(), 'project_status', true));
                    }
                }

                if (get_post_meta(get_the_ID(), 'project_location')) {
                    if (!in_array(get_post_meta(get_the_ID(), 'project_location', true), $result['project_location'])) {
                        array_push($result['project_location'], get_post_meta(get_the_ID(), 'project_location', true));
                    }
                }

                if (get_post_meta(get_the_ID(), 'project_type')) {
                    if (!in_array(get_post_meta(get_the_ID(), 'project_type', true), $result['project_type'])) {
                        array_push($result['project_type'], get_post_meta(get_the_ID(), 'project_type', true));
                    }
                }

                if (get_post_meta(get_the_ID(), 'project_price_max')) {
                    if ((int)$result['project_price_max'] < floatval(get_post_meta(get_the_ID(), 'project_price_max', true))) {
                        $result['project_price_max'] = floatval(get_post_meta(get_the_ID(), 'project_price_max', true));
                    }
                }

            endwhile;
            wp_reset_postdata();
        }
        return $result;
    }

   public function register_theme_options_metabox() {

        /**
         * Registers options page menu item and form.
         */
        $cmb2 = new_cmb2_box( array(
            'id'           => 'project_archive',
            'title'        => esc_html__( 'Projects Setting', 'pakrco' ),
            'object_types' => array( 'options-page' ),
            'option_key'      => 'project_archive',
            'position'        => 8,
        ) );

        $cmb2->add_field( array(
            'name' => esc_html__( 'Project Currency Symbol', 'pakrco' ),
            'id'   => 'currency_symbol',
            'type' => 'text',
            'default' => '$',
        ) );

        $cmb2->add_field( array(
            'name' => esc_html__( 'Hide Project Status', 'pakrco' ),
            'id'   => 'hide_status',
            'type' => 'checkbox',
        ) );

        $cmb2->add_field( array(
            'name' => esc_html__( 'Hide Project Type', 'pakrco' ),
            'id'   => 'hide_type',
            'type' => 'checkbox',
        ) );

        $cmb2->add_field( array(
            'name' => esc_html__( 'Hide Location', 'pakrco' ),
            'id'   => 'hide_location',
            'type' => 'checkbox',
        ) );

        $cmb2->add_field( array(
            'name' => esc_html__( 'Hide Budget', 'pakrco' ),
            'id'   => 'hide_budget',
            'type' => 'checkbox',
        ) );

        $group_field_id = $cmb2->add_field(array(
            'id'      => 'range',
            'type'    => 'group',
            'options' => array(
                'group_title'   => esc_html__('Budget range {#}', 'pakrco'),
                'add_button'    => esc_html__('Add Another Entry', 'pakrco'),
                'remove_button' => esc_html__('Remove Entry', 'pakrco'),
                'sortable'      => true,

            ),
        ));

        $cmb2->add_group_field($group_field_id, array(
            'name' => esc_html__('Min', 'pakrco'),
            'id'   => 'min',
            'type' => 'text',
        ));

        $cmb2->add_group_field($group_field_id, array(
            'name' => esc_html__('Max', 'pakrco'),
            'id'   => 'max',
            'type' => 'text',
        ));

    }

}

Pakrco_Project::getInstance();


function pakrco_order_post_type_archive_project($query) {
    if (is_admin()) {
        return;
    }
    if ($query->is_main_query() && is_post_type_archive('pakrco_project')) {
        $args = array(
            'relation' => 'AND',
        );

        if (isset($_GET['project_status']) && $_GET['project_status'] != '') {
            $args[] = array(
                'key'     => 'project_status',
                'value'   => $_GET['project_status'],
                'compare' => '='
            );
        }

        if (isset($_GET['project_location']) && $_GET['project_location'] != '') {
            $args[] = array(
                'key'     => 'project_location',
                'value'   => $_GET['project_location'],
                'compare' => '='
            );
        }

        if (isset($_GET['project_type']) && $_GET['project_type'] != '') {
            $args[] = array(
                'key'     => 'project_type',
                'value'   => $_GET['project_type'],
                'compare' => '='
            );
        }

        if (isset($_GET['project_budget']) && $_GET['project_budget'] != '') {
            if(explode('|', $_GET['project_budget'])[0]) {
                $args[] = array(
                    'key'     => 'project_price_min',
                    'value'   => explode('|', $_GET['project_budget'])[0],
                    'compare' => '>=',
                    'type'    => 'NUMERIC',
                );
            }
        }
        if (isset($_GET['project_budget']) && $_GET['project_budget'] != '') {
            if(explode('|', $_GET['project_budget'])[1]) {
                $args[] = array(
                    'key'     => 'project_price_max',
                    'value'   => explode('|', $_GET['project_budget'])[1],
                    'compare' => '<=',
                    'type'    => 'NUMERIC',
                );
            }
        }

        $query->set('meta_query', $args);

    }
}

add_action('pre_get_posts', 'pakrco_order_post_type_archive_project');

add_filter('project_query_args', function ($query){

    $args = array(
        'relation' => 'AND',
    );

    if (isset($_GET['project_status']) && $_GET['project_status'] != '') {
        $args[] = array(
            'key'     => 'project_status',
            'value'   => $_GET['project_status'],
            'compare' => '='
        );
    }

    if (isset($_GET['project_location']) && $_GET['project_location'] != '') {
        $args[] = array(
            'key'     => 'project_location',
            'value'   => $_GET['project_location'],
            'compare' => '='
        );
    }

    if (isset($_GET['project_type']) && $_GET['project_type'] != '') {
        $args[] = array(
            'key'     => 'project_type',
            'value'   => $_GET['project_type'],
            'compare' => '='
        );
    }

    if (isset($_GET['project_budget']) && $_GET['project_budget'] != '') {
        if(explode('|', $_GET['project_budget'])[0]) {
            $args[] = array(
                'key'     => 'project_price_min',
                'value'   => explode('|', $_GET['project_budget'])[0],
                'compare' => '>=',
                'type'    => 'NUMERIC',
            );
        }
    }
    if (isset($_GET['project_budget']) && $_GET['project_budget'] != '') {
        if(explode('|', $_GET['project_budget'])[1]) {
            $args[] = array(
                'key'     => 'project_price_max',
                'value'   => explode('|', $_GET['project_budget'])[1],
                'compare' => '<=',
                'type'    => 'NUMERIC',
            );
        }
    }
    $query['meta_query'] = $args;

    return $query;
});

function project_get_option( $key = '', $default = false ) {
    if ( function_exists( 'cmb2_get_option' ) ) {
        // Use cmb2_get_option as it passes through some key filters.
        return cmb2_get_option( 'project_archive', $key, $default );
    }

    // Fallback to get_option if CMB2 is not loaded yet.
    $opts = get_option( 'project_archive', $default );

    $val = $default;

    if ( 'all' == $key ) {
        $val = $opts;
    } elseif ( is_array( $opts ) && array_key_exists( $key, $opts ) && false !== $opts[ $key ] ) {
        $val = $opts[ $key ];
    }

    return $val;
}
