<?php



if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['apply_job_nonce']) && wp_verify_nonce($_POST['apply_job_nonce'], 'apply_for_job')) {
    $name = sanitize_text_field($_POST['applicant_name']);
    $email = sanitize_email($_POST['applicant_email']);
    $description = sanitize_textarea_field($_POST['applicant_description']);
    $cv = $_FILES['applicant_cv'];

    $upload = wp_handle_upload($cv, array('test_form' => false));
    if ($upload && !isset($upload['error'])) {
        $cv_url = $upload['url'];
        $job_id = get_the_ID();

        // Store applicant data
        $applicants = get_post_meta($job_id, '_job_applicants', true) ?: array();
        $applicants[] = array(
            'name' => $name,
            'email' => $email,
            'description' => $description,
            'cv' => $cv_url,
        );
        update_post_meta($job_id, '_job_applicants', $applicants);

        echo '<p>Application submitted successfully!</p>';
    } else {
        echo '<p>Error uploading CV.</p>';
    }
}

?>
<?php get_header(); // Include header

if (have_posts()) :
    while (have_posts()) : the_post(); ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <header class="entry-header">
                <h1 class="entry-title"><?php the_title(); ?></h1>
            </header>

            <div class="entry-content">
                <?php
                if (has_post_thumbnail()) {
                    the_post_thumbnail('full');
                }
                the_content(); // Main content of the post
                ?>
                <form method="POST" enctype="multipart/form-data">
                    <?php wp_nonce_field('apply_for_job', 'apply_job_nonce'); ?>
                    <label>Name: <input type="text" name="applicant_name" required></label><br>
                    <label>Email: <input type="email" name="applicant_email" required></label><br>
                    <label>Description: <textarea name="applicant_description" required></textarea></label><br>
                    <label>Upload CV: <input type="file" name="applicant_cv" required></label><br>
                    <input type="submit" value="Apply">
                </form>
            </div>

            <footer class="entry-footer">
                <?php
                // Display post categories, tags, etc. if needed
                the_terms($post->ID, 'case_study_category', 'Category: ', ', ');
                ?>
            </footer>
        </article>

<?php endwhile;
endif;

get_footer(); // Include footer