<?php
/**
 * Email and PDF Report Generation for the Simply English Assessment
 *
 * This class handles:
 *   - Generating a PDF report from HTML using Dompdf
 *   - Sending the PDF report via email using wp_mail()
 *
 * Requires: Dompdf library in the vendor folder.
 */
class SEA_Email {

    private static $instance = null;

    public static function instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        // Try to load Dompdf if it's not already loaded.
        if ( ! class_exists( '\\Dompdf\\Dompdf' ) ) {
            $dompdf_path = SEA_PLUGIN_DIR . 'vendor/dompdf/autoload.inc.php';
            if ( file_exists( $dompdf_path ) ) {
                require_once $dompdf_path;
            }
        }
    }

    /**
     * Generate a PDF file from HTML string.
     *
     * @param string $html HTML content to convert to PDF.
     * @return string|false Path to the temporary PDF file on success, false on failure.
     */
    public function generate_pdf( $html ) {
        if ( ! class_exists( '\\Dompdf\\Dompdf' ) ) {
            error_log( 'Dompdf class not found. Please ensure the Dompdf library is installed in the vendor folder.' );
            return false;
        }

        try {
            $dompdf = new \\Dompdf\\Dompdf();
            $dompdf->loadHtml( $html );
            $dompdf->setPaper( 'A4', 'portrait' );
            $dompdf->render();

            $pdf_data = $dompdf->output();

            // Create a temporary file in the system temp directory.
            $temp_file = wp_tempnam( 'sea-report-' . time() . '.pdf' );
            if ( $temp_file && file_put_contents( $temp_file, $pdf_data ) ) {
                return $temp_file;
            } else {
                error_log( 'Failed to write PDF to temporary file.' );
                return false;
            }
        } catch ( Exception $e ) {
            error_log( 'Dompdf error: ' . $e->getMessage() );
            return false;
        }
    }

    /**
     * Send an email with an optional PDF attachment.
     *
     * @param string $to        Recipient email address.
     * @param string $subject   Email subject.
     * @param string $message   Plain-text email body (fallback).
     * @param string $html_body HTML email body (optional).
     * @param string $pdf_path  Path to the PDF file to attach (optional).
     * @return bool|WP_Error True on success, WP_Error on failure.
     */
    public function send_report( $to, $subject, $message, $html_body = '', $pdf_path = '' ) {
        // Prepare headers for HTML email.
        $headers = [ 'Content-Type: text/html; charset=UTF-8' ];

        // Prepare attachments array.
        $attachments = array();
        if ( $pdf_path && file_exists( $pdf_path ) ) {
            $attachments[] = $pdf_path;
        }

        // Use HTML body if provided, otherwise convert plain-text to HTML with line breaks.
        $body = $html_body ? $html_body : nl2br( $message );

        // Send the email.
        $sent = wp_mail( $to, $subject, $body, $headers, $attachments );

        // Clean up the temporary PDF file if we created one.
        if ( $pdf_path && file_exists( $pdf_path ) ) {
            @unlink( $pdf_path );
        }

        return $sent ? true : new WP_Error( 'email_failed', __( 'Failed to send email.', 'simply-english-assessment' ) );
    }
}