<?php
/*
  Class : CareerJet jobs Hooks
 */


// this is an include only WP file
if (!defined('ABSPATH')) {
    die;
}

// main plugin class
class JobSearch_CareerJet_Jobs_Hooks {

    // hook things up
    public function __construct() {

        // job meta fields
        //add_action('jobsearch_job_meta_ext_fields', array($this, 'careerjet_job_meta_fields'));

        //
        add_action('admin_menu', array($this, 'jobsearch_careerjet_jobs_import_page'));
        add_action('wp_ajax_jobsearch_import_careerjet_jobs', array($this, 'jobsearch_import_careerjet_jobs'));

        // job listings shortcode params hook
        add_filter('jobsearch_job_integrations_types_list', array($this, 'shortcode_params_add'), 10, 1);

        // job listings query args params hook
        add_filter('jobsearch_job_listing_query_args_array', array($this, 'careerjet_jobs_listing_parameters'), 10, 2);
    }

    public function jobsearch_careerjet_jobs_import_page() {
        
    }

    /**
     * CareerJet jobs settings page
     * */
    public function jobsearch_import_careerjet_jobs_settings() {
        global $jobsearch_form_fields;
        
        
        $publisher_number = get_option('jobsearch_careerjet_imp_publisher_number');
        ?>
        <div id="wrapper" class="jobsearch-post-settings jobsearch-careerjet-import-sec">
            <h2><?php esc_html_e('Import CareerJet Jobs', 'wp-jobsearch'); ?></h2>
            <div class="error" id="error_msg"><p><strong><?php _e('There is some error importing jobs.', 'wp-jobsearch'); ?></strong></p></div>
            <div id="success_msg" class="updated"><p><strong><?php _e('CareerJet jobs are imported successfully.', 'wp-jobsearch'); ?></strong></p></div>
            
            <form autocomplete="off" id="jobsearch-import-careerjet-jobs" class="jobsearch-careerjet-jobs" method="post" enctype="multipart/form-data">
                <?php
                wp_nonce_field('jobsearch-import-careerjet-jobs-page', '_wpnonce-jobsearch-import-careerjet-jobs-page');
                ?>
                <div class="jobsearch-element-field">
                    <div class="elem-label">
                        <label><?php esc_html_e('Keywords', 'wp-jobsearch') ?></label>
                    </div>
                    <div class="elem-field">
                        <?php
                        $field_params = array(
                            'force_std' => '',
                            'id' => 'keywords',
                            'cus_name' => 'keywords',
                            'field_desc' => esc_html__('Enter job title, keywords or company name.', 'wp-jobsearch'),
                        );
                        $jobsearch_form_fields->input_field($field_params);
                        ?>
                    </div>
                </div>
                <div class="jobsearch-element-field">
                    <div class="elem-label">
                        <label><?php esc_html_e('Location', 'wp-jobsearch') ?></label>
                    </div>
                    <div class="elem-field">
                        <?php
                        $field_params = array(
                            'force_std' => '',
                            'id' => 'location',
                            'cus_name' => 'location',
                            'field_desc' => esc_html__('Enter a location for search.', 'wp-jobsearch'),
                        );
                        $jobsearch_form_fields->input_field($field_params);
                        ?>
                    </div>
                </div>
                <div class="jobsearch-element-field">
                    <div class="elem-label">
                        <label><?php esc_html_e('Page', 'wp-jobsearch') ?></label>
                    </div>
                    <div class="elem-field">
                        <?php
                        $field_params = array(
                            'force_std' => '1',
                            'id' => 'page',
                            'cus_name' => 'page',
                            'field_desc' => esc_html__('Enter page number.', 'wp-jobsearch'),
                        );
                        $jobsearch_form_fields->input_field($field_params);
                        ?>
                    </div>
                </div>
                <div class="jobsearch-element-field">
                    <div class="elem-label">
                        <label><?php esc_html_e('Expired on', 'wp-jobsearch') ?></label>
                    </div>
                    <div class="elem-field">
                        <?php
                        $field_params = array(
                            'force_std' => '0',
                            'id' => 'expire_days',
                            'cus_name' => 'expire_days',
                            'field_desc' => esc_html__('Enter number of days (numeric format) for expiray date after job posted date.', 'wp-jobsearch'),
                        );
                        $jobsearch_form_fields->input_field($field_params);
                        ?>
                    </div>
                </div>
                <div class="jobsearch-element-field">
                    <div class="elem-label">
                        <label><?php esc_html_e('Posted By', 'wp-jobsearch') ?></label>
                    </div>
                    <div class="elem-field">
                        <?php
                        jobsearch_get_custom_post_field('', 'employer', esc_html__('Auto Generate', 'wp-jobsearch'), 'job_username', 'job_username');
                        ?>
                    </div>
                </div>
                <div class="jobsearch-element-field">
                    <div class="elem-label">&nbsp;</div>
                    <div class="elem-field">
                        <input type="button" id="import-careerjet-jobs" class="import-careerjet-jobs" name="import-careerjet-jobs" onclick="javascript:jobsearch_import_careerjet_jobs_submit('<?php echo esc_js(admin_url('admin-ajax.php')) ?>');" value="<?php esc_html_e('Import CareerJet Jobs', 'wp-jobsearch') ?>">
                        <div id="loading"><i class="fa fa-refresh fa-spin"></i></div>
                    </div>
                </div>
            </form>
        </div>
        <?php
    }

    public function careerjet_job_meta_fields() {
        global $jobsearch_form_fields;

        $careerjet_jobs_switch = get_option('jobsearch_integration_careerjet_jobs');

        if ($careerjet_jobs_switch == 'on') {
            ?>
            <div class="jobsearch-elem-heading">
                <h2><?php esc_html_e('CareerJet Job Fields', 'wp-jobsearch') ?></h2>
            </div>

            <div class="jobsearch-element-field">
                <div class="elem-label">
                    <label><?php esc_html_e('Job Detail Url', 'wp-jobsearch') ?></label>
                </div>
                <div class="elem-field">
                    <?php
                    $field_params = array(
                        'name' => 'job_detail_url',
                    );
                    $jobsearch_form_fields->input_field($field_params);
                    ?>
                </div>
            </div>
            <div class="jobsearch-element-field">
                <div class="elem-label">
                    <label><?php esc_html_e('Company Name', 'wp-jobsearch') ?></label>
                </div>
                <div class="elem-field">
                    <?php
                    $field_params = array(
                        'name' => 'company_name',
                    );
                    $jobsearch_form_fields->input_field($field_params);
                    ?>
                </div>
            </div>
            <?php
        }
    }

    public function jobsearch_import_careerjet_jobs() {
        $nonce_val = sanitize_key(wp_unslash($_POST['_nonce']));
        if (!current_user_can('administrator') || !wp_verify_nonce($nonce_val, 'jobsearch_ajax_nonce')) {
            $msg = esc_html__('You are not allowed to do this.', 'wp-jobsearch');
            echo json_encode(array('msg' => $msg, 'error' => '1'));
            die;
        }
        $search_keywords = sanitize_text_field(stripslashes($_POST['keywords']));
        $search_location = sanitize_text_field(stripslashes($_POST['location']));
        $page_num = sanitize_text_field($_POST['page']);
        $job_username = sanitize_text_field($_POST['job_username']);
        //
        
        $api_args = array(
            'keywords' => $search_keywords,
            'location' => $search_location,
            'page' => $page_num,
        );

        $careerjet_jobs = JobSearch_CareerJet_API::get_jobs($api_args);
        $json = array();
        if (isset($careerjet_jobs['error']) && $careerjet_jobs['error'] != '') {
            $json['type'] = 'error';
            $json['message'] = $careerjet_jobs['error'];
        } elseif (empty($careerjet_jobs) || $careerjet_jobs === NULL) {
            $json['type'] = 'error';
            $json['message'] = esc_html__('Sorry! There are no jobs found for your search query.', 'wp-jobsearch');
        } else {
            $no_unique_jobs_found = true;
            foreach ($careerjet_jobs as $careerjet_job) {
                $job_title = isset($careerjet_job->title) ? $careerjet_job->title : '';
                $job_desc = isset($careerjet_job->description) ? $careerjet_job->description : '';
                $job_location = isset($careerjet_job->locations) ? $careerjet_job->locations : '';
                $job_url = isset($careerjet_job->url) ? $careerjet_job->url : '';
                $job_company = isset($careerjet_job->company) ? $careerjet_job->company : '';
                $job_salary_min = isset($careerjet_job->salary_min) ? $careerjet_job->salary_min : '';
                $existing_id = jobsearch_get_postmeta_id_byval('jobsearch_field_job_detail_url', $job_url);

                if ($existing_id > 0) {
                    //
                } else {
                    $no_unique_jobs_found = false;
                    $post_data = array(
                        'post_type' => 'job',
                        'post_title' => $job_title,
                        'post_content' => $job_desc,
                        'post_status' => 'publish',
                    );
                    // Insert the job into the database
                    $post_id = wp_insert_post($post_data);

                    //
                    update_post_meta($post_id, 'jobsearch_job_employer_status', 'approved');
                    update_post_meta($post_id, 'jobsearch_field_job_featured', '');

                    // Insert job username meta key
                    if ($job_username > 0) {
                        update_post_meta($post_id, 'jobsearch_field_job_posted_by', $job_username, true);
                    } else {
                        if ($job_company != '') {
                            jobsearch_fake_generate_employer_byname($job_company, $post_id);
                        }
                    }

                    // Insert job posted on meta key
                    update_post_meta($post_id, 'jobsearch_field_job_publish_date', current_time('timestamp'), true);

                    // Insert job expired on meta key
                    $expire_days = $_POST['expire_days'];
                    $expired_date = date('d-m-Y H:i:s', strtotime("$expire_days days", current_time('timestamp')));
                    update_post_meta($post_id, 'jobsearch_field_job_expiry_date', strtotime($expired_date), true);

                    // Insert job status meta key
                    update_post_meta($post_id, 'jobsearch_field_job_status', 'approved', true);

                    // Insert job address meta key
                    if ($job_location != '') {
                        update_post_meta($post_id, 'jobsearch_field_location_address', $job_location, true);
                    }

                    update_post_meta($post_id, 'jobsearch_field_job_salary', $job_salary_min, true);

                    // Insert job referral meta key
                    update_post_meta($post_id, 'jobsearch_job_referral', 'careerjet', true);

                    // Insert job detail url meta key
                    update_post_meta($post_id, 'jobsearch_field_job_detail_url', ($job_url), true);

                    // Insert job comapny name meta key
                    update_post_meta($post_id, 'jobsearch_field_company_name', $job_company, true);
                    
                    update_post_meta($post_id, 'jobsearch_field_job_apply_type', 'external', true);
                    update_post_meta($post_id, 'jobsearch_field_job_apply_url', $job_url, true);
                }

            }
            if ($no_unique_jobs_found) {
                $json['type'] = 'error';
                $json['message'] = __('No new job found.', 'wp-jobsearch');
            } else {
                $json['type'] = 'success';
                $json['msg'] = sprintf(__('%s careerjet jobs are imported successfully.', 'wp-jobsearch'), count($careerjet_jobs));
            }
        }
        
        if (isset($_POST['action']) && $_POST['action'] == 'jobsearch_import_careerjet_jobs') {
            echo json_encode($json);
            die();
        }
    }

    public function array_insert($array, $values, $offset) {
        return array_slice($array, 0, $offset, true) + $values + array_slice($array, $offset, NULL, true);
    }

    public function shortcode_params_add($opts = array()) {
        $careerjet_jobs_switch = get_option('jobsearch_integration_careerjet_jobs');

        if ($careerjet_jobs_switch == 'on') {
            $opts[] = 'careerjet';
        }

        return $opts;
    }

    public function careerjet_jobs_listing_parameters($args, $attr) {

        $careerjet_jobs_switch = get_option('jobsearch_integration_careerjet_jobs');

        if ($careerjet_jobs_switch == 'on') {
            if (isset($attr['job_list_type']) && $attr['job_list_type'] == 'careerjet') {
                $filter_arr = array(
                    'key' => 'jobsearch_job_referral',
                    'value' => 'careerjet',
                    'compare' => '=',
                );
                $args['meta_query'][] = $filter_arr;
            }
        }

        return $args;
    }

}

// Class JobSearch_CareerJet_Jobs_Hooks
global $JobSearch_CareerJet_Jobs_Hooks_obj;
$JobSearch_CareerJet_Jobs_Hooks_obj = new JobSearch_CareerJet_Jobs_Hooks();
