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

class AISB_Job_Notify {

    public static function maybe_send($job) {
        if (empty($job) || !is_array($job)) {
            return;
        }
        $s = aisb_get_settings();
        if (empty($s['notify_email_enabled'])) {
            return;
        }
        $failed = count($job['failed'] ?? []);
        if ($failed > 0 && empty($s['notify_email_failures'])) {
            return;
        }
        $to = sanitize_email($s['notify_email_to'] ?: get_option('admin_email'));
        if (!$to) {
            return;
        }

        $started = (int) ($job['started_ts'] ?? time());
        $duration = max(0, (int) ($job['completed_ts'] ?? time()) - $started);
        $processed = count($job['processed'] ?? []);
        $skipped = count($job['skipped'] ?? []);
        $total = (int) ($job['total'] ?? 0);
        $brand = aisb_brand_name();
        $host = wp_parse_url(home_url(), PHP_URL_HOST);

        $subject = sprintf('[%s] %s: %s (%d posts)', $host, $brand, __('job completed', 'pewit-ai-schema-builder'), $total);
        $body = $brand . ' ' . __('background job finished.', 'pewit-ai-schema-builder') . "\n\n";
        $body .= __('Website', 'pewit-ai-schema-builder') . ': ' . home_url() . "\n";
        $body .= __('Type', 'pewit-ai-schema-builder') . ': ' . ($job['type'] ?? 'bulk_schema') . "\n";
        $body .= __('Total', 'pewit-ai-schema-builder') . ": {$total}\n";
        $body .= __('Success', 'pewit-ai-schema-builder') . ": {$processed}\n";
        $body .= __('Failed', 'pewit-ai-schema-builder') . ": {$failed}\n";
        $body .= __('Skipped', 'pewit-ai-schema-builder') . ": {$skipped}\n";
        $body .= __('Duration', 'pewit-ai-schema-builder') . ': ' . self::format_seconds($duration) . "\n\n";
        $body .= __('Open dashboard', 'pewit-ai-schema-builder') . ': ' . aisb_admin_url('jobs') . "\n";

        wp_mail($to, $subject, $body);
    }

    private static function format_seconds($seconds) {
        $seconds = max(0, (int) $seconds);
        $m = (int) floor($seconds / 60);
        $s = $seconds % 60;
        return $m > 0 ? "{$m}m {$s}s" : "{$s}s";
    }
}
