<?php
/**
 * Audit Certificate Generator
 * Adds an audit trail page to signed PDFs
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class SWPDF_Audit_Certificate {
    
    /**
     * Load TCPDF and FPDI libraries (lazy loading)
     * Uses Strauss-prefixed (namespaced) copies to prevent conflicts
     * with other plugins that may bundle the same libraries.
     */
    private static function load_pdf_libraries() {
        static $loaded = false;
        if ( ! $loaded ) {
            $classmap = SWPDF_PLUGIN_DIR . 'vendor-prefixed/autoload-classmap.php';
            if ( file_exists( $classmap ) ) {
                $map = require $classmap;
                spl_autoload_register( function ( $class ) use ( $map ) {
                    if ( isset( $map[ $class ] ) && file_exists( $map[ $class ] ) ) {
                        require $map[ $class ];
                    }
                } );
            }
            $loaded = true;
        }
    }
    
    /**
     * Add audit certificate page to a PDF
     *
     * @param string $pdf_path Path to the original PDF
     * @param array $audit_data Audit trail data
     * @return bool Success or failure
     */
    public static function add_audit_page( $pdf_path, $audit_data ) {
        // Lazy load PDF libraries
        self::load_pdf_libraries();
        
        try {
            // Create new PDF with FPDI (Strauss-prefixed)
            $pdf = new \Swpdf\Vendor\setasign\Fpdi\Tcpdf\Fpdi();
            $pdf->setPrintHeader( false );
            $pdf->setPrintFooter( false );
            
            // Get page count from original PDF
            $page_count = $pdf->setSourceFile( $pdf_path );
            
            // Import all pages from original PDF
            for ( $i = 1; $i <= $page_count; $i++ ) {
                $template_id = $pdf->importPage( $i );
                $size = $pdf->getTemplateSize( $template_id );
                
                $pdf->AddPage( $size['orientation'], array( $size['width'], $size['height'] ) );
                $pdf->useTemplate( $template_id, 0, 0, $size['width'], $size['height'] );
            }
            
            // Add audit certificate page
            $pdf->AddPage( 'P', 'LETTER' );
            self::render_audit_page( $pdf, $audit_data );
            
            // Save the modified PDF
            $pdf->Output( $pdf_path, 'F' );
            
            return true;
        } catch ( Exception $e ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging PDF generation errors
            error_log( 'PSF Audit Certificate Error: ' . $e->getMessage() );
            return false;
        }
    }
    
    /**
     * Render the audit certificate page content
     */
    private static function render_audit_page( $pdf, $data ) {
        $settings = get_option( 'swpdf_settings', array() );
        $company_name = $settings['company_name'] ?? get_bloginfo( 'name' );
        
        // Colors
        $primary_color = array( 0, 115, 170 ); // WordPress blue
        $success_color = array( 0, 163, 42 ); // Green
        $text_color = array( 35, 40, 45 );
        $light_gray = array( 240, 240, 241 );
        
        // Header background
        $pdf->SetFillColor( $primary_color[0], $primary_color[1], $primary_color[2] );
        $pdf->Rect( 0, 0, 220, 45, 'F' );
        
        // Header text
        $pdf->SetTextColor( 255, 255, 255 );
        $pdf->SetFont( 'helvetica', 'B', 22 );
        $pdf->SetXY( 20, 12 );
        $pdf->Cell( 0, 10, 'AUDIT CERTIFICATE', 0, 1, 'L' );
        
        $pdf->SetFont( 'helvetica', '', 11 );
        $pdf->SetXY( 20, 25 );
        $pdf->Cell( 0, 8, 'Electronic Signature Verification', 0, 1, 'L' );
        
        // Verified badge
        $pdf->SetFillColor( $success_color[0], $success_color[1], $success_color[2] );
        $pdf->RoundedRect( 150, 15, 45, 18, 3, '1111', 'F' );
        $pdf->SetFont( 'helvetica', 'B', 12 );
        $pdf->SetXY( 150, 20 );
        $pdf->Cell( 45, 8, '✓ VERIFIED', 0, 0, 'C' );
        
        // Reset text color
        $pdf->SetTextColor( $text_color[0], $text_color[1], $text_color[2] );
        
        // Document Info Section
        $y = 55;
        $pdf->SetFont( 'helvetica', 'B', 14 );
        $pdf->SetXY( 20, $y );
        $pdf->Cell( 0, 8, 'Document Information', 0, 1, 'L' );
        
        $y += 12;
        $pdf->SetFillColor( $light_gray[0], $light_gray[1], $light_gray[2] );
        $pdf->RoundedRect( 20, $y, 175, 45, 3, '1111', 'F' );
        
        $pdf->SetFont( 'helvetica', '', 10 );
        $y += 5;
        
        self::draw_field( $pdf, 25, $y, 'Document ID', '#' . ( $data['id'] ?? 'N/A' ) );
        $y += 10;
        self::draw_field( $pdf, 25, $y, 'Document Type', ucwords( str_replace( '-', ' ', $data['agreement_type'] ?? 'Agreement' ) ) );
        $y += 10;
        self::draw_field( $pdf, 25, $y, 'File Name', $data['file_name'] ?? 'N/A' );
        $y += 10;
        self::draw_field( $pdf, 25, $y, 'Company', $company_name );
        
        // Signer Information Section
        $y += 20;
        $pdf->SetFont( 'helvetica', 'B', 14 );
        $pdf->SetXY( 20, $y );
        $pdf->Cell( 0, 8, 'Signer Information', 0, 1, 'L' );
        
        $y += 12;
        $pdf->SetFillColor( $light_gray[0], $light_gray[1], $light_gray[2] );
        $pdf->RoundedRect( 20, $y, 175, 35, 3, '1111', 'F' );
        
        $y += 5;
        self::draw_field( $pdf, 25, $y, 'Name', $data['customer_name'] ?? 'N/A' );
        $y += 10;
        self::draw_field( $pdf, 25, $y, 'Email', $data['customer_email'] ?? 'N/A' );
        $y += 10;
        self::draw_field( $pdf, 25, $y, 'Phone', $data['customer_phone'] ?? 'N/A' );
        
        // Audit Trail Section
        $y += 20;
        $pdf->SetFont( 'helvetica', 'B', 14 );
        $pdf->SetTextColor( $primary_color[0], $primary_color[1], $primary_color[2] );
        $pdf->SetXY( 20, $y );
        $pdf->Cell( 0, 8, '🔒 Audit Trail', 0, 1, 'L' );
        $pdf->SetTextColor( $text_color[0], $text_color[1], $text_color[2] );
        
        $y += 12;
        $pdf->SetFillColor( 245, 250, 255 ); // Light blue tint
        $pdf->RoundedRect( 20, $y, 175, 55, 3, '1111', 'F' );
        
        // Border
        $pdf->SetDrawColor( $primary_color[0], $primary_color[1], $primary_color[2] );
        $pdf->RoundedRect( 20, $y, 175, 55, 3, '1111', 'D' );
        $pdf->SetDrawColor( 0, 0, 0 );
        
        $y += 5;
        self::draw_field( $pdf, 25, $y, 'Signed At', $data['signed_at'] ?? 'N/A' );
        $y += 10;
        self::draw_field( $pdf, 25, $y, 'IP Address', $data['ip_address'] ?? 'N/A' );
        $y += 10;
        
        // User agent (truncate if too long)
        $user_agent = $data['user_agent'] ?? 'N/A';
        if ( strlen( $user_agent ) > 80 ) {
            $user_agent = substr( $user_agent, 0, 77 ) . '...';
        }
        self::draw_field( $pdf, 25, $y, 'User Agent', $user_agent, 8 );
        
        $y += 15;
        
        // Document hash
        $hash = hash( 'sha256', wp_json_encode( $data ) . $data['signed_at'] );
        self::draw_field( $pdf, 25, $y, 'Document Hash', strtoupper( substr( $hash, 0, 32 ) ) . '...', 8 );
        
        // Footer
        $y = 250;
        $pdf->SetFont( 'helvetica', 'I', 9 );
        $pdf->SetTextColor( 128, 128, 128 );
        $pdf->SetXY( 20, $y );
        $pdf->MultiCell( 175, 5, 
            "This audit certificate confirms that the document was electronically signed using PDF Sign & Fill. " .
            "The signer's identity was verified through the email address provided. " .
            "This record is stored securely and can be used for verification purposes.",
            0, 'L'
        );
        
        $y += 20;
        $pdf->SetXY( 20, $y );
        $pdf->Cell( 175, 5, 'Generated: ' . current_time( 'F j, Y \a\t g:i:s A T' ), 0, 0, 'C' );
    }
    
    /**
     * Helper to draw a field label and value
     */
    private static function draw_field( $pdf, $x, $y, $label, $value, $value_size = 10 ) {
        $pdf->SetFont( 'helvetica', 'B', 9 );
        $pdf->SetTextColor( 100, 100, 100 );
        $pdf->SetXY( $x, $y );
        $pdf->Cell( 40, 5, $label . ':', 0, 0, 'L' );
        
        $pdf->SetFont( 'helvetica', '', $value_size );
        $pdf->SetTextColor( 35, 40, 45 );
        $pdf->SetXY( $x + 40, $y );
        $pdf->Cell( 130, 5, $value, 0, 0, 'L' );
    }
}
