<?php
function register_job_post_type() {
    $labels = array(
        'name'               => 'Jobs',
        'singular_name'      => 'Job',
        'menu_name'          => 'Careers',
        'name_admin_bar'     => 'Job',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Job',
        'new_item'           => 'New Job',
        'edit_item'          => 'Edit Job',
        'view_item'          => 'View Job',
        'all_items'          => 'All Jobs',
        'search_items'       => 'Search Jobs',
        'not_found'          => 'No jobs found',
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'has_archive'        => true,
        'supports'           => array('title', 'editor'),
        'rewrite'            => array('slug' => 'careers'),
        'show_in_rest'       => true,
    );

    register_post_type('job', $args);
}
add_action('init', 'register_job_post_type');

function add_job_meta_boxes() {
    add_meta_box('job_details', 'Job Details', 'render_job_meta_box', 'job', 'normal', 'high');
}
add_action('add_meta_boxes', 'add_job_meta_boxes');

function render_job_meta_box($post) {
    // Add nonce for security
    wp_nonce_field('save_job_details', 'job_details_nonce');

    // Retrieve existing data
    $location = get_post_meta($post->ID, '_job_location', true);
    $salary = get_post_meta($post->ID, '_job_salary', true);

    // Location
    echo '<p><label>Location:</label>';
    echo '<input type="text" name="job_location" value="' . esc_attr($location) . '" /></p>';

    // Salary
    echo '<p><label>Salary:</label>';
    echo '<input type="text" name="job_salary" value="' . esc_attr($salary) . '" /></p>';
}

function save_job_meta($post_id) {
    // Check nonce
    if (!isset($_POST['job_details_nonce']) || !wp_verify_nonce($_POST['job_details_nonce'], 'save_job_details')) {
        return;
    }

    // Save meta fields
    if (isset($_POST['job_location'])) {
        update_post_meta($post_id, '_job_location', sanitize_text_field($_POST['job_location']));
    }
    if (isset($_POST['job_salary'])) {
        update_post_meta($post_id, '_job_salary', sanitize_text_field($_POST['job_salary']));
    }
}
add_action('save_post', 'save_job_meta');


function add_applicant_count_column($columns) {
    $columns['applicants'] = 'Applicants';
    return $columns;
}
add_filter('manage_job_posts_columns', 'add_applicant_count_column');

function display_applicant_count_column($column, $post_id) {
    if ($column === 'applicants') {
        $applicants = get_post_meta($post_id, '_job_applicants', true) ?: array();
        echo count($applicants);
    }
}
add_action('manage_job_posts_custom_column', 'display_applicant_count_column', 10, 2);