<?php
namespace GriffinForms\Includes\Schedulers;

use GriffinForms\Traits\Singleton;

class DraftCleanupScheduler
{
    use Singleton;

    /**
     * Register cron hook and schedule if not already scheduled.
     */
    public function register()
    {
        // Hook the runner
        add_action('griffinforms_draft_cleanup', [$this, 'run']);

        // Schedule daily if not already
        if (!wp_next_scheduled('griffinforms_draft_cleanup')) {
            wp_schedule_event(time() + HOUR_IN_SECONDS, 'daily', 'griffinforms_draft_cleanup');
        }
    }

    /**
     * Cron runner: prunes orphaned AI drafts.
     */
    public function run()
    {
        global $wpdb;
        $config = \GriffinForms\Config::getInstance();
        $table = $config->getTable('form');
        
        // Find drafts older than 7 days
        $older_than = 7;
        $date = gmdate('Y-m-d H:i:s', time() - ($older_than * DAY_IN_SECONDS));
        
        $draft_ids = $wpdb->get_col($wpdb->prepare(
            "SELECT id FROM $table WHERE status = 'draft' AND created < %s",
            $date
        ));
        
        if (empty($draft_ids)) {
            return;
        }
        
        // We need the SQL class but maybe outside admin scope during CRON
        $sql = \GriffinForms\Admin\Sql\App::getInstance();
        $count = 0;
        
        foreach ($draft_ids as $id) {
            $id = absint($id);
            if ($sql->deleteForm($id, true)) {
                $count++;
            }
        }
        
        if ($count > 0) {
            $log = \GriffinForms\Log::getInstance();
            $log->add('info', 'system', 0, 0, sprintf('Pruned %d orphaned AI drafts.', $count), 'draft_cleanup');
        }
    }
}
