<?php
if (!defined('ABSPATH')) exit;

class AISB_Validation_Cron {

    const CRON_HOOK = 'aisb_validation_scan';
    const REPORT_OPTION = 'aisb_validation_report';

    public static function init() {
        add_action(self::CRON_HOOK, [__CLASS__, 'run']);
        add_filter('cron_schedules', [__CLASS__, 'schedules']);
    }

    public static function schedules($schedules) {
        $schedules['aisb_weekly'] = [
            'interval' => WEEK_IN_SECONDS,
            'display'  => __('Once weekly (Pewit AI Schema Builder)', 'pewit-ai-schema-builder'),
        ];
        return $schedules;
    }

    public static function maybe_schedule() {
        $s = aisb_get_settings();
        if (empty($s['validation_scan_enabled'])) {
            self::unschedule();
            return;
        }
        if (!wp_next_scheduled(self::CRON_HOOK)) {
            wp_schedule_event(time() + HOUR_IN_SECONDS, 'aisb_weekly', self::CRON_HOOK);
        }
    }

    public static function unschedule() {
        $ts = wp_next_scheduled(self::CRON_HOOK);
        if ($ts) {
            wp_unschedule_event($ts, self::CRON_HOOK);
        }
    }

    public static function run() {
        $post_types = AISB_CPT_Registry::get_enabled_post_types();
        if (empty($post_types)) {
            return;
        }

        $issues = [];
        $checked = 0;
        $valid = 0;

        $q = new WP_Query([
            'post_type'      => $post_types,
            'post_status'    => 'publish',
            'posts_per_page' => 200,
            'fields'         => 'ids',
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Scheduled scan of posts that already have schema meta.
            'meta_query'     => [
                ['key' => AISB_Schema::META_JSON, 'compare' => 'EXISTS'],
            ],
        ]);

        foreach ($q->posts as $post_id) {
            $checked++;
            $schema = AISB_Schema::get_json($post_id);
            $type = AISB_Schema::get_type($post_id);
            if (!$schema) {
                continue;
            }
            $v = AISB_Rich_Results::validate($schema);
            if (!empty($v['errors'])) {
                $issues[] = [
                    'id'     => $post_id,
                    'title'  => get_the_title($post_id),
                    'type'   => $type,
                    'errors' => $v['errors'],
                ];
            } else {
                $valid++;
            }
        }

        $report = [
            'ran_at'   => current_time('mysql'),
            'checked'  => $checked,
            'valid'    => $valid,
            'issues'   => $issues,
            'issue_count' => count($issues),
        ];
        update_option(self::REPORT_OPTION, $report, false);

        $s = aisb_get_settings();
        if (!empty($s['notify_email_enabled']) && !empty($issues)) {
            $to = sanitize_email($s['notify_email_to'] ?: get_option('admin_email'));
            if ($to) {
                $subject = sprintf('[%s] %s: %d schema validation issues', wp_parse_url(home_url(), PHP_URL_HOST), aisb_brand_name(), count($issues));
                $body = sprintf(/* translators: 1: number of posts checked, 2: number of posts with errors */ __('%1$d posts checked, %2$d with errors.', 'pewit-ai-schema-builder'), $checked, count($issues)) . "\n\n";
                foreach (array_slice($issues, 0, 30) as $row) {
                    $body .= "#{$row['id']} {$row['title']} — " . implode('; ', $row['errors']) . "\n";
                }
                $body .= "\n" . aisb_admin_url('dashboard') . "\n";
                wp_mail($to, $subject, $body);
            }
        }
    }

    public static function get_report() {
        return get_option(self::REPORT_OPTION, null);
    }
}
