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

class AIIO_Job_Notify {
    public static function maybe_send($job) {
        if (empty($job) || !is_array($job)) return;
        $s = aiio_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;
        $processed = count($job['processed'] ?? []);
        $total = (int) ($job['total'] ?? 0);
        $saved = 0;
        foreach ($job['processed'] ?? [] as $p) {
            $saved += (int) ($p['saved_bytes'] ?? 0);
        }
        $subject = sprintf('[%s] %s: %d images optimized', wp_parse_url(home_url(), PHP_URL_HOST), aiio_brand_name(), $processed);
        $body = aiio_brand_name() . " job finished.\n\nTotal: {$total}\nOptimized: {$processed}\nFailed: {$failed}\nSaved: " . AIIO_Optimizer::format_bytes($saved) . "\n\n" . aiio_admin_page_url('pewit-ai-image-optimizer-jobs') . "\n";

        $attachments = [];
        $tmp = '';
        $include_csv = !empty($s['notify_include_csv']);
        if ($include_csv) {
            $tmp = self::write_job_csv($job);
            if ($tmp) {
                $attachments[] = $tmp;
                $body .= "\n" . __('CSV summary attached.', 'pewit-ai-image-optimizer') . "\n";
            }
        }

        wp_mail($to, $subject, $body, '', $attachments);
        if ($tmp && is_file($tmp)) {
            wp_delete_file($tmp);
        }
    }

    private static function write_job_csv($job) {
        $rows = [['attachment_id', 'filename', 'saved_bytes', 'saved_label']];
        foreach ($job['processed'] ?? [] as $p) {
            $rows[] = [
                $p['id'] ?? '',
                $p['filename'] ?? '',
                $p['saved_bytes'] ?? 0,
                isset($p['saved_bytes']) ? AIIO_Optimizer::format_bytes((int) $p['saved_bytes']) : '',
            ];
        }
        $tmp = wp_tempnam('aiio-job-report');
        if (!$tmp) {
            return '';
        }
        $out = fopen($tmp, 'w'); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Local CSV export for email attachment.
        foreach ($rows as $row) {
            fputcsv($out, $row);
        }
        fclose($out); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Local CSV export for email attachment.
        return $tmp;
    }
}
