<?php
require_once('TCPDF/tcpdf.php');

/**
 * PDF Generator Class
 * Generates legally-bindable PDFs with signatures and timestamps
 */

class PDFGenerator {
    private $pdf;
    private $pdo;
    private $document_id;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    /**
     * Generate PDF from document
     */
    public function generateFromDocument($document_id, $include_signatures = true) {
        try {
            // Get document data
            $stmt = $this->pdo->prepare("SELECT * FROM documents WHERE id = ?");
            $stmt->execute([$document_id]);
            $document = $stmt->fetch();

            if (!$document) {
                throw new Exception("Document not found");
            }

            $this->document_id = $document_id;
            $this->pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

            // Set PDF properties
            $this->pdf->SetCreator(PDF_AUTHOR);
            $this->pdf->SetAuthor(PDF_AUTHOR);
            $this->pdf->SetTitle($document['document_type']);
            $this->pdf->SetSubject('Signed Document - ' . $document['created_at']);
            $this->pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
            $this->pdf->SetMargins(15, 15, 15);
            $this->pdf->SetAutoPageBreak(TRUE, 20);

            // Add page
            $this->pdf->AddPage();
            $this->addHeader($document);
            $this->addDocumentContent($document);

            if ($include_signatures) {
                $this->addSignatureSection($document_id);
            }

            $this->addFooter($document);
            $this->addAuditTrail($document);

            // Generate filename
            $filename = 'DOC_' . $document_id . '_' . date('YmdHis') . '.pdf';
            $filepath = PDF_DIR . $filename;

            // Output to file
            $this->pdf->Output($filepath, 'F');

            return ['success' => true, 'filename' => $filename, 'filepath' => $filepath];

        } catch (Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    /**
     * Add header with branding
     */
    private function addHeader($document) {
        // Get garage info
        $stmt = $this->pdo->prepare("SELECT garage_name, garage_logo_path FROM users WHERE id = ?");
        $stmt->execute([$document['user_id']]);
        $garage = $stmt->fetch();

        $this->pdf->SetFont('helvetica', 'B', 16);
        $this->pdf->Cell(0, 10, $garage['garage_name'] ?? 'Professional Services', 0, 1, 'C');

        $this->pdf->SetFont('helvetica', '', 10);
        $this->pdf->Cell(0, 5, strtoupper($document['document_type']), 0, 1, 'C');
        $this->pdf->Ln(5);

        // Add horizontal line
        $this->pdf->SetDrawColor(0, 0, 0);
        $this->pdf->Line(15, $this->pdf->GetY(), 195, $this->pdf->GetY());
        $this->pdf->Ln(5);
    }

    /**
     * Add main document content
     */
    private function addDocumentContent($document) {
        $data = json_decode($document['document_data'], true);

        $this->pdf->SetFont('helvetica', '', PDF_FONT_SIZE);

        // Add document information
        $html = '<h3>Document Details</h3>';
        $html .= '<table cellpadding="5">';
        $html .= '<tr><td width="30%"><strong>Customer:</strong></td><td>' . htmlspecialchars($document['customer_name']) . '</td></tr>';
        $html .= '<tr><td><strong>Email:</strong></td><td>' . htmlspecialchars($document['customer_email']) . '</td></tr>';

        if ($document['customer_phone']) {
            $html .= '<tr><td><strong>Phone:</strong></td><td>' . htmlspecialchars($document['customer_phone']) . '</td></tr>';
        }

        if ($document['vehicle_info']) {
            $html .= '<tr><td><strong>Vehicle:</strong></td><td>' . htmlspecialchars($document['vehicle_info']) . '</td></tr>';
        }

        $html .= '</table>';
        $this->pdf->writeHTML($html, true, false, true, false, '');

        // Add document fields
        $this->pdf->Ln(5);
        $this->pdf->SetFont('helvetica', 'B', 11);
        $this->pdf->Cell(0, 8, 'Agreement Terms & Conditions', 0, 1);
        $this->pdf->SetFont('helvetica', '', 10);

        $html = '<table cellpadding="4" border="1">';
        foreach ($data as $key => $value) {
            if ($key !== 'customer_name' && $key !== 'customer_email' && $key !== 'customer_phone') {
                $label = ucwords(str_replace('_', ' ', $key));
                $html .= '<tr>';
                $html .= '<td width="30%"><strong>' . htmlspecialchars($label) . ':</strong></td>';
                $html .= '<td width="70%">' . htmlspecialchars(is_array($value) ? json_encode($value) : $value) . '</td>';
                $html .= '</tr>';
            }
        }
        $html .= '</table>';

        $this->pdf->writeHTML($html, true, false, true, false, '');
    }

    /**
     * Add signature section
     */
    private function addSignatureSection($document_id) {
        // Get signatures
        $stmt = $this->pdo->prepare("
            SELECT id, signer_name, signer_email, signer_role, signature_timestamp, signature_data
            FROM signatures
            WHERE document_id = ?
            ORDER BY signature_timestamp ASC
        ");
        $stmt->execute([$document_id]);
        $signatures = $stmt->fetchAll();

        if (empty($signatures)) {
            return;
        }

        $this->pdf->Ln(10);
        $this->pdf->SetFont('helvetica', 'B', 11);
        $this->pdf->Cell(0, 8, 'Digital Signatures & Approvals', 0, 1);

        $this->pdf->SetFont('helvetica', '', 10);

        foreach ($signatures as $signature) {
            // Add signer info
            $html = '<div style="margin: 10px 0; padding: 10px; border: 1px solid #ccc;">';
            $html .= '<strong>' . htmlspecialchars($signature['signer_name']) . '</strong> (' . $signature['signer_role'] . ')<br>';
            $html .= '<small>Signed: ' . $signature['signature_timestamp'] . '</small><br>';
            if ($signature['signer_email']) {
                $html .= '<small>Email: ' . htmlspecialchars($signature['signer_email']) . '</small>';
            }
            $html .= '</div>';

            $this->pdf->writeHTML($html, true, false, true, false, '');

            // Add signature image if available (base64 encoded)
            if ($signature['signature_data'] && strpos($signature['signature_data'], 'data:image') === 0) {
                try {
                    // Extract base64 from data URI
                    $image_data = substr($signature['signature_data'], strpos($signature['signature_data'], ',') + 1);
                    $image_data = base64_decode($image_data);

                    // Save temporary image file
                    $temp_file = tempnam(sys_get_temp_dir(), 'sig');
                    file_put_contents($temp_file, $image_data);

                    // Add image to PDF
                    $this->pdf->Image($temp_file, 20, $this->pdf->GetY(), 50, 20, 'PNG');
                    $this->pdf->Ln(25);

                    // Clean up
                    unlink($temp_file);
                } catch (Exception $e) {
                    // Silently fail if signature image can't be added
                }
            }
        }
    }

    /**
     * Add footer with legal information
     */
    private function addFooter($document) {
        $this->pdf->Ln(10);
        $this->pdf->SetFont('helvetica', '', 8);
        $this->pdf->SetTextColor(100, 100, 100);

        $footer_text = "This document was electronically signed and generated on " . date('Y-m-d H:i:s') . ".\n";
        $footer_text .= "Document ID: " . $document['document_hash'] . "\n";
        $footer_text .= "For verification purposes, keep this document secure and confidential.";

        $this->pdf->MultiCell(0, 3, $footer_text, 0, 'C');
    }

    /**
     * Add audit trail information
     */
    private function addAuditTrail($document) {
        $this->pdf->AddPage();
        $this->pdf->SetFont('helvetica', 'B', 12);
        $this->pdf->Cell(0, 10, 'Audit Trail & Document Verification', 0, 1);

        $this->pdf->SetFont('helvetica', '', 9);
        $this->pdf->Ln(5);

        // Document Information
        $html = '<table cellpadding="3" border="1">';
        $html .= '<tr><td width="40%"><strong>Document ID:</strong></td><td>' . $document['document_hash'] . '</td></tr>';
        $html .= '<tr><td><strong>Document Type:</strong></td><td>' . ucfirst(str_replace('_', ' ', $document['document_type'])) . '</td></tr>';
        $html .= '<tr><td><strong>Created Date:</strong></td><td>' . $document['created_at'] . '</td></tr>';
        $html .= '<tr><td><strong>Created IP:</strong></td><td>' . $document['created_ip'] . '</td></tr>';
        $html .= '<tr><td><strong>Signed Date:</strong></td><td>' . ($document['signed_at'] ?? 'Not yet signed') . '</td></tr>';
        $html .= '<tr><td><strong>Signed IP:</strong></td><td>' . ($document['signed_ip'] ?? 'N/A') . '</td></tr>';
        $html .= '</table>';

        $this->pdf->writeHTML($html, true, false, true, false, '');

        // Signature Audit Trail
        $this->pdf->Ln(10);
        $this->pdf->SetFont('helvetica', 'B', 11);
        $this->pdf->Cell(0, 8, 'Signature Audit Trail', 0, 1);

        $stmt = $this->pdo->prepare("
            SELECT signer_name, signer_email, signer_role, signature_timestamp, signer_ip
            FROM signatures
            WHERE document_id = ?
            ORDER BY signature_timestamp ASC
        ");
        $stmt->execute([$this->document_id]);
        $signatures = $stmt->fetchAll();

        $html = '<table cellpadding="3" border="1">';
        $html .= '<tr><th>Signer</th><th>Role</th><th>Timestamp</th><th>IP Address</th></tr>';
        foreach ($signatures as $sig) {
            $html .= '<tr>';
            $html .= '<td>' . htmlspecialchars($sig['signer_name']) . '</td>';
            $html .= '<td>' . $sig['signer_role'] . '</td>';
            $html .= '<td>' . $sig['signature_timestamp'] . '</td>';
            $html .= '<td>' . $sig['signer_ip'] . '</td>';
            $html .= '</tr>';
        }
        $html .= '</table>';

        $this->pdf->SetFont('helvetica', '', 9);
        $this->pdf->writeHTML($html, true, false, true, false, '');

        // Legal disclaimer
        $this->pdf->Ln(10);
        $this->pdf->SetFont('helvetica', 'I', 8);
        $disclaimer = "This document has been digitally signed and is legally binding. All signatures, timestamps, and audit trail information are recorded and secured. Any modification to this document after signing will be detected and the document will be considered void.";
        $this->pdf->MultiCell(0, 3, $disclaimer, 0, 'J');
    }

    /**
     * Output PDF to browser for download
     */
    public function downloadPDF($filepath, $filename) {
        if (!file_exists($filepath)) {
            return false;
        }

        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
        header('Content-Length: ' . filesize($filepath));
        header('Cache-Control: must-revalidate');
        header('Pragma: public');

        readfile($filepath);
        return true;
    }
}
