<?php
/*
Theme Name: FindStreak Job Board
Description: A complete job board theme with anti-scam protection and manual admin approval system for FindStreak.com
Version: 1.0
Author: FindStreak Team
*/

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Theme setup
function findstreak_theme_setup() {
    // Add theme support for various features
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('html5', array('comment-list', 'comment-form', 'search-form', 'gallery', 'caption'));
    add_theme_support('custom-logo');
    
    // Register navigation menus
    register_nav_menus(array(
        'primary' => 'Primary Navigation',
        'footer' => 'Footer Navigation'
    ));
}
add_action('after_setup_theme', 'findstreak_theme_setup');

// Enqueue styles and scripts
function findstreak_enqueue_scripts() {
    wp_enqueue_style('findstreak-style', get_stylesheet_uri(), array(), '1.0');
    wp_enqueue_script('findstreak-script', get_template_directory_uri() . '/js/main.js', array('jquery'), '1.0', true);
    
    // Localize script for AJAX
    wp_localize_script('findstreak-script', 'findstreak_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('findstreak_nonce')
    ));
}
add_action('wp_enqueue_scripts', 'findstreak_enqueue_scripts');

// Create Job post type
function create_job_post_type() {
    $labels = array(
        'name' => 'Jobs',
        'singular_name' => 'Job',
        'menu_name' => 'Job Listings',
        'add_new' => 'Add New Job',
        'add_new_item' => 'Add New Job',
        'edit_item' => 'Edit Job',
        'new_item' => 'New Job',
        'view_item' => 'View Job',
        'search_items' => 'Search Jobs',
        'not_found' => 'No jobs found',
        'not_found_in_trash' => 'No jobs found in trash'
    );
    
    $args = array(
        'labels' => $labels,
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'jobs'),
        'supports' => array('title', 'editor', 'thumbnail'),
        'menu_icon' => 'dashicons-businessman',
        'show_in_rest' => true,
        'menu_position' => 5
    );
    
    register_post_type('job', $args);
}
add_action('init', 'create_job_post_type');

// Create Job taxonomies
function create_job_taxonomies() {
    // Job Categories
    register_taxonomy('job_category', 'job', array(
        'labels' => array(
            'name' => 'Job Categories',
            'singular_name' => 'Job Category',
            'search_items' => 'Search Categories',
            'all_items' => 'All Categories',
            'edit_item' => 'Edit Category',
            'update_item' => 'Update Category',
            'add_new_item' => 'Add New Category',
            'new_item_name' => 'New Category Name'
        ),
        'hierarchical' => true,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'job-category'),
        'show_in_rest' => true
    ));
    
    // Job Locations
    register_taxonomy('job_location', 'job', array(
        'labels' => array(
            'name' => 'Job Locations',
            'singular_name' => 'Job Location',
            'search_items' => 'Search Locations',
            'all_items' => 'All Locations',
            'edit_item' => 'Edit Location',
            'update_item' => 'Update Location',
            'add_new_item' => 'Add New Location',
            'new_item_name' => 'New Location Name'
        ),
        'hierarchical' => true,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'job-location'),
        'show_in_rest' => true
    ));
}
add_action('init', 'create_job_taxonomies');

// Add job meta boxes
function add_job_meta_boxes() {
    add_meta_box('job_details', 'Job Details', 'job_details_callback', 'job', 'normal', 'high');
    add_meta_box('company_info', 'Company Information', 'company_info_callback', 'job', 'normal', 'high');
    add_meta_box('job_requirements', 'Job Requirements', 'job_requirements_callback', 'job', 'normal', 'high');
    add_meta_box('job_verification', 'Job Verification', 'job_verification_callback', 'job', 'side', 'high');
}
add_action('add_meta_boxes', 'add_job_meta_boxes');

// Job details meta box callback
function job_details_callback($post) {
    wp_nonce_field('save_job_meta', 'job_meta_nonce');
    
    $job_type = get_post_meta($post->ID, '_job_type', true);
    $experience_level = get_post_meta($post->ID, '_experience_level', true);
    $salary_min = get_post_meta($post->ID, '_salary_min', true);
    $salary_max = get_post_meta($post->ID, '_salary_max', true);
    $application_method = get_post_meta($post->ID, '_application_method', true);
    $application_email = get_post_meta($post->ID, '_application_email', true);
    $application_url = get_post_meta($post->ID, '_application_url', true);
    
    ?>
    <table class="form-table">
        <tr>
            <th><label for="job_type">Job Type</label></th>
            <td>
                <select name="job_type" id="job_type">
                    <option value="">Select Type</option>
                    <option value="full-time" <?php selected($job_type, 'full-time'); ?>>Full Time</option>
                    <option value="part-time" <?php selected($job_type, 'part-time'); ?>>Part Time</option>
                    <option value="contract" <?php selected($job_type, 'contract'); ?>>Contract</option>
                    <option value="freelance" <?php selected($job_type, 'freelance'); ?>>Freelance</option>
                    <option value="internship" <?php selected($job_type, 'internship'); ?>>Internship</option>
                </select>
            </td>
        </tr>
        <tr>
            <th><label for="experience_level">Experience Level</label></th>
            <td>
                <select name="experience_level" id="experience_level">
                    <option value="">Select Experience</option>
                    <option value="fresher" <?php selected($experience_level, 'fresher'); ?>>Fresher (0-1 year)</option>
                    <option value="junior" <?php selected($experience_level, 'junior'); ?>>Junior (1-3 years)</option>
                    <option value="mid" <?php selected($experience_level, 'mid'); ?>>Mid-level (3-5 years)</option>
                    <option value="senior" <?php selected($experience_level, 'senior'); ?>>Senior (5+ years)</option>
                </select>
            </td>
        </tr>
        <tr>
            <th><label for="salary_min">Salary Range (₹ per annum)</label></th>
            <td>
                <input type="number" name="salary_min" id="salary_min" value="<?php echo esc_attr($salary_min); ?>" placeholder="Minimum" style="width: 45%;">
                <span style="margin: 0 10px;">to</span>
                <input type="number" name="salary_max" id="salary_max" value="<?php echo esc_attr($salary_max); ?>" placeholder="Maximum" style="width: 45%;">
            </td>
        </tr>
        <tr>
            <th><label for="application_method">Application Method</label></th>
            <td>
                <select name="application_method" id="application_method">
                    <option value="">Select Method</option>
                    <option value="email" <?php selected($application_method, 'email'); ?>>Email</option>
                    <option value="url" <?php selected($application_method, 'url'); ?>>Website URL</option>
                </select>
            </td>
        </tr>
        <tr>
            <th><label for="application_email">Application Email</label></th>
            <td><input type="email" name="application_email" id="application_email" value="<?php echo esc_attr($application_email); ?>" class="regular-text"></td>
        </tr>
        <tr>
            <th><label for="application_url">Application URL</label></th>
            <td><input type="url" name="application_url" id="application_url" value="<?php echo esc_attr($application_url); ?>" class="regular-text"></td>
        </tr>
    </table>
    <?php
}

// Company info meta box callback
function company_info_callback($post) {
    $company_name = get_post_meta($post->ID, '_company_name', true);
    $company_website = get_post_meta($post->ID, '_company_website', true);
    $company_size = get_post_meta($post->ID, '_company_size', true);
    $company_location = get_post_meta($post->ID, '_company_location', true);
    $company_description = get_post_meta($post->ID, '_company_description', true);
    $contact_person = get_post_meta($post->ID, '_contact_person', true);
    $contact_email = get_post_meta($post->ID, '_contact_email', true);
    
    ?>
    <table class="form-table">
        <tr>
            <th><label for="company_name">Company Name</label></th>
            <td><input type="text" name="company_name" id="company_name" value="<?php echo esc_attr($company_name); ?>" class="regular-text"></td>
        </tr>
        <tr>
            <th><label for="company_website">Company Website</label></th>
            <td><input type="url" name="company_website" id="company_website" value="<?php echo esc_attr($company_website); ?>" class="regular-text"></td>
        </tr>
        <tr>
            <th><label for="company_size">Company Size</label></th>
            <td>
                <select name="company_size" id="company_size">
                    <option value="">Select Size</option>
                    <option value="startup" <?php selected($company_size, 'startup'); ?>>Startup (1-10 employees)</option>
                    <option value="small" <?php selected($company_size, 'small'); ?>>Small (11-50 employees)</option>
                    <option value="medium" <?php selected($company_size, 'medium'); ?>>Medium (51-200 employees)</option>
                    <option value="large" <?php selected($company_size, 'large'); ?>>Large (201-1000 employees)</option>
                    <option value="enterprise" <?php selected($company_size, 'enterprise'); ?>>Enterprise (1000+ employees)</option>
                </select>
            </td>
        </tr>
        <tr>
            <th><label for="company_location">Company Location</label></th>
            <td><input type="text" name="company_location" id="company_location" value="<?php echo esc_attr($company_location); ?>" class="regular-text"></td>
        </tr>
        <tr>
            <th><label for="company_description">Company Description</label></th>
            <td><textarea name="company_description" id="company_description" rows="4" cols="50"><?php echo esc_textarea($company_description); ?></textarea></td>
        </tr>
        <tr>
            <th><label for="contact_person">Contact Person</label></th>
            <td><input type="text" name="contact_person" id="contact_person" value="<?php echo esc_attr($contact_person); ?>" class="regular-text"></td>
        </tr>
        <tr>
            <th><label for="contact_email">Contact Email</label></th>
            <td><input type="email" name="contact_email" id="contact_email" value="<?php echo esc_attr($contact_email); ?>" class="regular-text"></td>
        </tr>
    </table>
    <?php
}

// Job requirements meta box callback
function job_requirements_callback($post) {
    $job_requirements = get_post_meta($post->ID, '_job_requirements', true);
    $job_responsibilities = get_post_meta($post->ID, '_job_responsibilities', true);
    $required_skills = get_post_meta($post->ID, '_required_skills', true);
    $job_benefits = get_post_meta($post->ID, '_job_benefits', true);
    
    ?>
    <table class="form-table">
        <tr>
            <th><label for="job_requirements">Job Requirements</label></th>
            <td><textarea name="job_requirements" id="job_requirements" rows="5" cols="50" placeholder="Enter requirements, one per line"><?php echo esc_textarea($job_requirements); ?></textarea></td>
        </tr>
        <tr>
            <th><label for="job_responsibilities">Key Responsibilities</label></th>
            <td><textarea name="job_responsibilities" id="job_responsibilities" rows="5" cols="50" placeholder="Enter responsibilities, one per line"><?php echo esc_textarea($job_responsibilities); ?></textarea></td>
        </tr>
        <tr>
            <th><label for="required_skills">Required Skills</label></th>
            <td><input type="text" name="required_skills" id="required_skills" value="<?php echo esc_attr($required_skills); ?>" class="regular-text" placeholder="Comma-separated skills"></td>
        </tr>
        <tr>
            <th><label for="job_benefits">Benefits & Perks</label></th>
            <td><textarea name="job_benefits" id="job_benefits" rows="4" cols="50" placeholder="Enter benefits, one per line"><?php echo esc_textarea($job_benefits); ?></textarea></td>
        </tr>
    </table>
    <?php
}

// Job verification meta box callback
function job_verification_callback($post) {
    $is_verified = get_post_meta($post->ID, '_is_verified', true);
    $verification_notes = get_post_meta($post->ID, '_verification_notes', true);
    $posted_date = get_post_meta($post->ID, '_posted_date', true);
    
    ?>
    <p><strong>Job Status:</strong></p>
    <label>
        <input type="checkbox" name="is_verified" value="1" <?php checked($is_verified, '1'); ?>>
        Mark as Verified & Approved
    </label>
    
    <p><strong>Verification Notes:</strong></p>
    <textarea name="verification_notes" rows="4" cols="30" placeholder="Internal notes for verification..."><?php echo esc_textarea($verification_notes); ?></textarea>
    
    <?php if ($posted_date): ?>
    <p><strong>Posted Date:</strong><br><?php echo date('Y-m-d H:i:s', strtotime($posted_date)); ?></p>
    <?php endif; ?>
    
    <p><strong>Actions:</strong></p>
    <button type="button" onclick="sendApprovalEmail(<?php echo $post->ID; ?>)" class="button">Send Approval Email</button>
    <button type="button" onclick="sendRejectionEmail(<?php echo $post->ID; ?>)" class="button">Send Rejection Email</button>
    <?php
}

// Save job meta data
function save_job_meta($post_id) {
    if (!isset($_POST['job_meta_nonce']) || !wp_verify_nonce($_POST['job_meta_nonce'], 'save_job_meta')) {
        return;
    }
    
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    // Save job details
    $fields = array(
        '_job_type', '_experience_level', '_salary_min', '_salary_max',
        '_application_method', '_application_email', '_application_url',
        '_company_name', '_company_website', '_company_size', '_company_location',
        '_company_description', '_contact_person', '_contact_email',
        '_job_requirements', '_job_responsibilities', '_required_skills', '_job_benefits',
        '_is_verified', '_verification_notes'
    );
    
    foreach ($fields as $field) {
        $key = ltrim($field, '_');
        if (isset($_POST[$key])) {
            update_post_meta($post_id, $field, sanitize_text_field($_POST[$key]));
        }
    }
    
    // Set posted date if not exists
    if (!get_post_meta($post_id, '_posted_date', true)) {
        update_post_meta($post_id, '_posted_date', current_time('mysql'));
    }
}
add_action('save_post', 'save_job_meta');

// AJAX handler for job search
function handle_job_search() {
    check_ajax_referer('findstreak_nonce', 'nonce');
    
    $search_term = sanitize_text_field($_POST['search_term']);
    $location = sanitize_text_field($_POST['location']);
    $category = sanitize_text_field($_POST['category']);
    $experience = sanitize_text_field($_POST['experience']);
    $job_type = sanitize_text_field($_POST['job_type']);
    
    $args = array(
        'post_type' => 'job',
        'post_status' => 'publish',
        'posts_per_page' => 10,
        'meta_query' => array(
            array(
                'key' => '_is_verified',
                'value' => '1',
                'compare' => '='
            )
        )
    );
    
    if ($search_term) {
        $args['s'] = $search_term;
    }
    
    if ($location) {
        $args['tax_query'][] = array(
            'taxonomy' => 'job_location',
            'field' => 'slug',
            'terms' => $location
        );
    }
    
    if ($category) {
        $args['tax_query'][] = array(
            'taxonomy' => 'job_category',
            'field' => 'slug',
            'terms' => $category
        );
    }
    
    if ($experience) {
        $args['meta_query'][] = array(
            'key' => '_experience_level',
            'value' => $experience,
            'compare' => '='
        );
    }
    
    if ($job_type) {
        $args['meta_query'][] = array(
            'key' => '_job_type',
            'value' => $job_type,
            'compare' => '='
        );
    }
    
    $jobs = new WP_Query($args);
    
    ob_start();
    if ($jobs->have_posts()) {
        while ($jobs->have_posts()) {
            $jobs->the_post();
            // Include job card template here
            get_template_part('template-parts/job-card');
        }
        wp_reset_postdata();
    } else {
        echo '<p>No jobs found matching your criteria.</p>';
    }
    
    $html = ob_get_clean();
    wp_send_json_success($html);
}
add_action('wp_ajax_job_search', 'handle_job_search');
add_action('wp_ajax_nopriv_job_search', 'handle_job_search');

// AJAX handler for reporting jobs
function handle_report_job() {
    check_ajax_referer('report_job_nonce', 'nonce');
    
    $job_id = intval($_POST['job_id']);
    $reason = sanitize_text_field($_POST['reason']);
    $details = sanitize_textarea_field($_POST['details']);
    
    // Log the report (you can store this in database or send email)
    $report_data = array(
        'job_id' => $job_id,
        'reason' => $reason,
        'details' => $details,
        'reporter_ip' => $_SERVER['REMOTE_ADDR'],
        'reported_at' => current_time('mysql')
    );
    
    // Send email to admin
    $admin_email = get_option('admin_email');
    $job_title = get_the_title($job_id);
    $subject = 'Job Reported: ' . $job_title;
    $message = "A job has been reported by a user.\n\n";
    $message .= "Job: " . $job_title . "\n";
    $message .= "Job ID: " . $job_id . "\n";
    $message .= "Reason: " . $reason . "\n";
    $message .= "Details: " . $details . "\n";
    $message .= "Reporter IP: " . $_SERVER['REMOTE_ADDR'] . "\n";
    $message .= "View Job: " . get_permalink($job_id) . "\n";
    
    wp_mail($admin_email, $subject, $message);
    
    wp_send_json_success('Report submitted successfully.');
}
add_action('wp_ajax_report_job', 'handle_report_job');
add_action('wp_ajax_nopriv_report_job', 'handle_report_job');

// Add admin notices for pending jobs
function show_pending_jobs_notice() {
    $pending_jobs = wp_count_posts('job');
    if ($pending_jobs->pending > 0) {
        echo '<div class="notice notice-warning is-dismissible">';
        echo '<p><strong>Job Board:</strong> You have ' . $pending_jobs->pending . ' job posting(s) waiting for approval. <a href="' . admin_url('edit.php?post_type=job&post_status=pending') . '">Review now</a></p>';
        echo '</div>';
    }
}
add_action('admin_notices', 'show_pending_jobs_notice');

// Customize admin columns for jobs
function set_custom_job_columns($columns) {
    unset($columns['date']);
    $columns['company'] = 'Company';
    $columns['job_type'] = 'Job Type';
    $columns['location'] = 'Location';
    $columns['verified'] = 'Verified';
    $columns['date'] = 'Date';
    return $columns;
}
add_filter('manage_job_posts_columns', 'set_custom_job_columns');

// Add content to custom admin columns
function custom_job_column($column, $post_id) {
    switch ($column) {
        case 'company':
            echo get_post_meta($post_id, '_company_name', true);
            break;
        case 'job_type':
            echo ucfirst(get_post_meta($post_id, '_job_type', true));
            break;
        case 'location':
            $locations = get_the_terms($post_id, 'job_location');
            if ($locations) {
                echo $locations[0]->name;
            }
            break;
        case 'verified':
            $verified = get_post_meta($post_id, '_is_verified', true);
            echo $verified == '1' ? '<span style="color: green;">✓ Verified</span>' : '<span style="color: red;">✗ Pending</span>';
            break;
    }
}
add_action('manage_job_posts_custom_column', 'custom_job_column', 10, 2);

// Initialize default taxonomies
function create_default_job_taxonomies() {
    // Only run once
    if (get_option('findstreak_taxonomies_created')) {
        return;
    }
    
    // Default categories
    $default_categories = array(
        'Technology', 'Marketing', 'Sales', 'Design', 'Finance', 
        'Human Resources', 'Operations', 'Customer Support', 'Other'
    );
    
    foreach ($default_categories as $category) {
        if (!term_exists($category, 'job_category')) {
            wp_insert_term($category, 'job_category');
        }
    }
    
    // Default locations
    $default_locations = array(
        'Bangalore', 'Mumbai', 'Delhi', 'Pune', 'Hyderabad', 
        'Chennai', 'Kolkata', 'Ahmedabad', 'Remote', 'Other'
    );
    
    foreach ($default_locations as $location) {
        if (!term_exists($location, 'job_location')) {
            wp_insert_term($location, 'job_location');
        }
    }
    
    update_option('findstreak_taxonomies_created', true);
}
add_action('init', 'create_default_job_taxonomies');

// Redirect jobs archive to custom page
function redirect_jobs_archive() {
    if (is_post_type_archive('job')) {
        wp_redirect(home_url('/jobs'));
        exit;
    }
}
add_action('template_redirect', 'redirect_jobs_archive');

// Custom body classes
function findstreak_body_classes($classes) {
    if (is_singular('job')) {
        $classes[] = 'single-job-page';
    } elseif (is_post_type_archive('job')) {
        $classes[] = 'job-archive-page';
    }
    return $classes;
}
add_filter('body_class', 'findstreak_body_classes');

?>