<?php
require_once('PHPMailer/Exception.php');
require_once('PHPMailer/PHPMailer.php');
require_once('PHPMailer/SMTP.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as MailerException;

/**
 * Email Handler Class
 * Sends signed documents via email with timestamps and audit trail
 */

class EmailHandler {
    private $pdo;
    private $mailer;

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

    /**
     * Setup PHPMailer configuration
     */
    private function setupMailer() {
        $this->mailer = new PHPMailer(true);

        try {
            // SMTP configuration
            $this->mailer->isSMTP();
            $this->mailer->Host = SMTP_HOST;
            $this->mailer->SMTPAuth = true;
            $this->mailer->Username = SMTP_USER;
            $this->mailer->Password = SMTP_PASS;
            $this->mailer->SMTPSecure = SMTP_ENCRYPTION;
            $this->mailer->Port = SMTP_PORT;

            // Set from address
            $this->mailer->setFrom(MAIL_FROM_EMAIL, MAIL_FROM_NAME);

            // Charset
            $this->mailer->CharSet = 'UTF-8';
        } catch (MailerException $e) {
            error_log("Mailer setup error: " . $e->getMessage());
        }
    }

    /**
     * Send signed document to customer and admin
     */
    public function sendSignedDocument($document_id, $pdf_path) {
        try {
            // Get document
            $stmt = $this->pdo->prepare("SELECT * FROM documents WHERE id = ?");
            $stmt->execute([$document_id]);
            $document = $stmt->fetch();

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

            // Get user (garage) info
            $stmt = $this->pdo->prepare("SELECT email, garage_name FROM users WHERE id = ?");
            $stmt->execute([$document['user_id']]);
            $user = $stmt->fetch();

            $results = [];

            // Send to customer
            $results['customer'] = $this->sendToCustomer($document, $user, $pdf_path);

            // Send to admin
            $results['admin'] = $this->sendToAdmin($document, $user, $pdf_path);

            return $results;

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

    /**
     * Send document to customer
     */
    private function sendToCustomer($document, $user, $pdf_path) {
        try {
            $this->mailer->clearAddresses();
            $this->mailer->addAddress($document['customer_email'], $document['customer_name']);

            $subject = 'Your Signed ' . ucfirst(str_replace('_', ' ', $document['document_type'])) . ' - ' . $document['document_type'] . '_' . $document['id'];

            $body = $this->getCustomerEmailTemplate($document, $user);

            $this->mailer->Subject = $subject;
            $this->mailer->Body = $body;
            $this->mailer->isHTML(true);

            // Attach PDF
            if (file_exists($pdf_path)) {
                $this->mailer->addAttachment($pdf_path, 'Signed_Document_' . $document['id'] . '.pdf');
            }

            $sent = $this->mailer->send();

            // Log email
            $this->logEmail($document['id'], $document['customer_email'], 'customer', $subject, $sent);

            return ['success' => $sent, 'email' => $document['customer_email']];

        } catch (MailerException $e) {
            $this->logEmail($document['id'], $document['customer_email'], 'customer', 'Failed', false, $e->getMessage());
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    /**
     * Send document to admin
     */
    private function sendToAdmin($document, $user, $pdf_path) {
        try {
            $this->mailer->clearAddresses();
            $this->mailer->addAddress($user['email'], $user['garage_name']);

            $subject = '[SIGNED] ' . ucfirst(str_replace('_', ' ', $document['document_type'])) . ' - ' . $document['customer_name'];

            $body = $this->getAdminEmailTemplate($document, $user);

            $this->mailer->Subject = $subject;
            $this->mailer->Body = $body;
            $this->mailer->isHTML(true);

            // Attach PDF
            if (file_exists($pdf_path)) {
                $this->mailer->addAttachment($pdf_path, 'Signed_Document_' . $document['id'] . '.pdf');
            }

            $sent = $this->mailer->send();

            // Log email
            $this->logEmail($document['id'], $user['email'], 'admin', $subject, $sent);

            return ['success' => $sent, 'email' => $user['email']];

        } catch (MailerException $e) {
            $this->logEmail($document['id'], $user['email'], 'admin', 'Failed', false, $e->getMessage());
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    /**
     * Get customer email template
     */
    private function getCustomerEmailTemplate($document, $user) {
        $signed_date = $document['signed_at'] ? date('F j, Y \a\t g:i A', strtotime($document['signed_at'])) : 'Not yet signed';

        $html = '<!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; color: #333; }
                .container { max-width: 600px; margin: 0 auto; }
                .header { background-color: #2c3e50; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; border: 1px solid #ddd; }
                .footer { background-color: #f5f5f5; padding: 15px; font-size: 12px; text-align: center; color: #666; }
                .info-box { background-color: #ecf0f1; padding: 15px; margin: 15px 0; border-left: 4px solid #3498db; }
                .signature-box { background-color: #d5f4e6; padding: 15px; margin: 15px 0; border-left: 4px solid #27ae60; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>' . htmlspecialchars($user['garage_name']) . '</h1>
                    <p>Document Signature Confirmation</p>
                </div>

                <div class="content">
                    <p>Dear ' . htmlspecialchars($document['customer_name']) . ',</p>

                    <p>Thank you for signing your ' . htmlspecialchars(ucfirst(str_replace('_', ' ', $document['document_type']))) . '. Your signed document has been generated and is attached to this email.</p>

                    <div class="info-box">
                        <strong>Document Details:</strong><br>
                        Document Type: ' . htmlspecialchars(ucfirst(str_replace('_', ' ', $document['document_type']))) . '<br>
                        Document ID: ' . htmlspecialchars($document['document_hash']) . '<br>
                        Signed Date: ' . $signed_date . '<br>
                        Customer: ' . htmlspecialchars($document['customer_name']) . '
                    </div>

                    <div class="signature-box">
                        <strong>✓ Signature Verified</strong><br>
                        Your signature has been digitally verified and recorded with a legal timestamp.
                    </div>

                    <p>Please keep this email and the attached PDF for your records. This document is legally binding and has been securely stored.</p>

                    <p><strong>Important:</strong> Do not modify, print, or alter the PDF document. Any modifications will invalidate the signatures.</p>

                    <p>If you have any questions, please contact ' . htmlspecialchars($user['garage_name']) . ' directly.</p>

                    <p>Best regards,<br>' . htmlspecialchars($user['garage_name']) . '</p>
                </div>

                <div class="footer">
                    <p>This is an automated email. Please do not reply to this address.</p>
                    <p>Document generated: ' . date('Y-m-d H:i:s') . '</p>
                </div>
            </div>
        </body>
        </html>';

        return $html;
    }

    /**
     * Get admin email template
     */
    private function getAdminEmailTemplate($document, $user) {
        $data = json_decode($document['document_data'], true);

        $html = '<!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; color: #333; }
                .container { max-width: 600px; margin: 0 auto; }
                .header { background-color: #34495e; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; border: 1px solid #ddd; }
                .footer { background-color: #f5f5f5; padding: 15px; font-size: 12px; text-align: center; color: #666; }
                .info-table { width: 100%; border-collapse: collapse; margin: 15px 0; }
                .info-table td { padding: 8px; border-bottom: 1px solid #ddd; }
                .info-table td:first-child { font-weight: bold; width: 30%; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h2>Document Signed</h2>
                    <p>Admin Notification</p>
                </div>

                <div class="content">
                    <h3>' . htmlspecialchars(ucfirst(str_replace('_', ' ', $document['document_type']))) . ' - ' . htmlspecialchars($document['customer_name']) . '</h3>

                    <table class="info-table">
                        <tr><td>Customer Name:</td><td>' . htmlspecialchars($document['customer_name']) . '</td></tr>
                        <tr><td>Customer Email:</td><td>' . htmlspecialchars($document['customer_email']) . '</td></tr>
                        <tr><td>Customer Phone:</td><td>' . htmlspecialchars($document['customer_phone'] ?? 'N/A') . '</td></tr>
                        <tr><td>Vehicle:</td><td>' . htmlspecialchars($document['vehicle_info'] ?? 'N/A') . '</td></tr>
                        <tr><td>Document Type:</td><td>' . htmlspecialchars(ucfirst(str_replace('_', ' ', $document['document_type']))) . '</td></tr>
                        <tr><td>Document ID:</td><td>' . htmlspecialchars($document['document_hash']) . '</td></tr>
                        <tr><td>Created:</td><td>' . $document['created_at'] . '</td></tr>
                        <tr><td>Signed:</td><td>' . ($document['signed_at'] ?? 'Pending') . '</td></tr>
                        <tr><td>Status:</td><td><strong style="color: green;">✓ SIGNED</strong></td></tr>
                    </table>

                    <h4>Document Fields:</h4>
                    <table class="info-table">';

        foreach ($data as $key => $value) {
            if (!in_array($key, ['customer_name', 'customer_email', 'customer_phone'])) {
                $label = ucwords(str_replace('_', ' ', $key));
                $html .= '<tr><td>' . htmlspecialchars($label) . ':</td><td>' . htmlspecialchars(is_array($value) ? json_encode($value) : $value) . '</td></tr>';
            }
        }

        $html .= '</table>

                    <p>The signed PDF document is attached to this email and has been archived in your system.</p>
                </div>

                <div class="footer">
                    <p>Document generated: ' . date('Y-m-d H:i:s') . '</p>
                </div>
            </div>
        </body>
        </html>';

        return $html;
    }

    /**
     * Log email sending
     */
    private function logEmail($document_id, $recipient_email, $recipient_type, $subject, $status, $error = null) {
        try {
            $stmt = $this->pdo->prepare("
                INSERT INTO email_log (document_id, recipient_email, recipient_type, subject, status, error_message)
                VALUES (?, ?, ?, ?, ?, ?)
            ");

            $stmt->execute([
                $document_id,
                $recipient_email,
                $recipient_type,
                $subject,
                $status ? 'sent' : 'failed',
                $error
            ]);
        } catch (Exception $e) {
            error_log("Email log error: " . $e->getMessage());
        }
    }

    /**
     * Get email history for document
     */
    public function getEmailHistory($document_id) {
        try {
            $stmt = $this->pdo->prepare("
                SELECT * FROM email_log
                WHERE document_id = ?
                ORDER BY sent_at DESC
            ");
            $stmt->execute([$document_id]);
            return $stmt->fetchAll();
        } catch (Exception $e) {
            return [];
        }
    }
}
