<?php
/*
Plugin Name: Delete Expired Job Listings
Description: A plugin to automatically delete expired job listings on a weekly basis.
Version: 1.0
Author: Zaheer Anjum
*/

// Add custom interval for weekly scheduling
function custom_cron_schedules($schedules) {
    // Add weekly to the existing schedules.
    $schedules['weekly'] = array(
        'interval' => 604800, // 1 week in seconds
        'display'  => __('Once Weekly'),
    );
    return $schedules;
}
add_filter('cron_schedules', 'custom_cron_schedules');

// Schedule an event if not already scheduled
if (!wp_next_scheduled('delete_expired_job_listings_hook')) {
    wp_schedule_event(time(), 'weekly', 'delete_expired_job_listings_hook');
}

// Hook into that action to run your function
add_action('delete_expired_job_listings_hook', 'delete_expired_job_listings');

function delete_expired_job_listings() {
    // Define your custom post type
    $post_type = 'job_listing';

    // Query for expired job listings
    $args = array(
        'post_type'      => $post_type,
        'post_status'    => 'expired', // Change this to match your job listings' expired status
        'posts_per_page' => -1 // Retrieve all expired listings
    );

    $expired_jobs = new WP_Query($args);

    if ($expired_jobs->have_posts()) {
        while ($expired_jobs->have_posts()) {
            $expired_jobs->the_post();
            wp_delete_post(get_the_ID(), true); // True for permanent deletion
        }
        wp_reset_postdata();
    }
}

// Clear the scheduled event on plugin deactivation
function myplugin_deactivation() {
    $timestamp = wp_next_scheduled('delete_expired_job_listings_hook');
    wp_unschedule_event($timestamp, 'delete_expired_job_listings_hook');
}
register_deactivation_hook(__FILE__, 'myplugin_deactivation');
