<?php
/**
 * Email Service
 */

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

class EmailService {
    private $pdo;
    private $smtp_host;
    private $smtp_port;
    private $smtp_user;
    private $smtp_password;
    private $company_name;
    private $company_email;

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

    /**
     * Load SMTP settings from database
     */
    private function loadSettings() {
        try {
            $stmt = $this->pdo->query("SELECT setting_key, setting_value FROM settings");
            $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

            $this->smtp_host = $settings['smtp_host'] ?? 'smtp.gmail.com';
            $this->smtp_port = $settings['smtp_port'] ?? '587';
            $this->smtp_user = $settings['smtp_user'] ?? '';
            $this->smtp_password = $settings['smtp_password'] ?? '';
            $this->company_name = $settings['company_name'] ?? 'RoutexShipping';
            $this->company_email = $settings['company_email'] ?? '';
        } catch (PDOException $e) {
            $this->smtp_host = 'smtp.gmail.com';
            $this->smtp_port = '587';
            $this->company_name = 'RoutexShipping';
        }
    }

    /**
     * Send parcel notification email
     */
    public function sendParcelNotification($parcel, $recipient_email = null) {
        if (!$recipient_email) {
            $recipient_email = $parcel['receiver_email'] ?? $parcel['sender_email'];
        }

        if (!$recipient_email) {
            return false;
        }

        $subject = "Parcel Status Notification – " . date('Y-m-d');
        $body = $this->getParcelEmailTemplate($parcel);

        return $this->send($recipient_email, $subject, $body, $parcel['id']);
    }

    /**
     * Get parcel email template (Speedaf style)
     */
    private function getParcelEmailTemplate($parcel) {
        $status_label = Utils::getStatusLabel($parcel['status']);
        $tracking_code = $parcel['tracking_code'];
        $receiver_name = $parcel['receiver_name'];
        $current_location = $parcel['current_location'] ?? 'Processing';
        $company_name = htmlspecialchars($this->company_name);

        $html = '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
                .header h1 { margin: 0; font-size: 28px; }
                .content { background: #f9f9f9; padding: 30px; border: 1px solid #ddd; }
                .status-badge { display: inline-block; padding: 10px 20px; background: #667eea; color: white; border-radius: 20px; font-weight: bold; margin: 10px 0; }
                .info-row { margin: 15px 0; padding: 10px; background: white; border-left: 4px solid #667eea; }
                .info-label { font-weight: bold; color: #667eea; }
                .footer { background: #333; color: white; padding: 20px; text-align: center; border-radius: 0 0 8px 8px; font-size: 12px; }
                .button { display: inline-block; padding: 12px 30px; background: #667eea; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                  <img src="/routex/images/routex-logo.png" alt="RoutexShipping Logo" style="max-height: 60px; width: auto;" class="mx-auto">
                    <p>Your Parcel Tracking Update</p>
                </div>
                
                <div class="content">
                    <p>Hello <strong>' . $receiver_name . '</strong>,</p>
                    
                    <p>We have an update on your shipment:</p>
                    
                    <div class="status-badge">' . $status_label . '</div>
                    
                    <div class="info-row">
                        <div class="info-label">Tracking Code:</div>
                        <div>' . $tracking_code . '</div>
                    </div>
                    
                    <div class="info-row">
                        <div class="info-label">Current Location:</div>
                        <div>' . $current_location . '</div>
                    </div>
                    
                    <div class="info-row">
                        <div class="info-label">Receiver:</div>
                        <div>' . $receiver_name . '</div>
                    </div>
                    
                    <div class="info-row">
                        <div class="info-label">Destination:</div>
                        <div>' . ($parcel['receiver_city'] ?? '') . ', ' . ($parcel['receiver_country'] ?? '') . '</div>
                    </div>
                    
                    <p style="text-align: center;">
                        <a href="' . APP_URL . '/track?code=' . $tracking_code . '" class="button" style="color:#fff">Track Your Parcel</a>
                    </p>
                    
                    <p>If you have any questions, please don\'t hesitate to contact our support team.</p>
                    
                    <p>Best regards,<br><strong>' . $company_name . ' Team</strong></p>
                </div>
                
                <div class="footer">
                    <p>&copy; ' . date('Y') . ' ' . $company_name . '. All rights reserved.</p>
                    <p>This is an automated message. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
        ';

        return $html;
    }

    /**
     * Send email using PHP mail (fallback)
     */
    public function send($to, $subject, $body, $parcel_id = null) {
        // Check if Composer autoloader exists
        $autoloadPath = __DIR__ . '/../../vendor/autoload.php';
        if (!file_exists($autoloadPath)) {
            $this->logEmail($to, $subject, $parcel_id, 'failed', 'PHPMailer not installed. Run: composer require phpmailer/phpmailer');
            return false;
        }
        
        require_once $autoloadPath;

        // Log email attempt
        $this->logEmail($to, $subject, $parcel_id, 'pending');

        $mail = new PHPMailer(true);

        try {
            // Server settings
            $mail->isSMTP();
            $mail->Host       = $this->smtp_host;
            $mail->SMTPAuth   = !empty($this->smtp_user);
            $mail->Username   = $this->smtp_user;
            $mail->Password   = $this->smtp_password;
            $mail->SMTPSecure = $this->smtp_port == 465 ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = $this->smtp_port;

            // Recipients
            $fromEmail = !empty($this->company_email) ? $this->company_email : ('noreply@' . ($_SERVER['HTTP_HOST'] ?? 'localhost'));
            $mail->setFrom($fromEmail, $this->company_name);
            $mail->addAddress($to);

            // Content
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $body;
            $mail->AltBody = strip_tags(str_replace(['<br>', '</p>'], ["\n", "\n\n"], $body));

            $mail->send();
            $this->logEmail($to, $subject, $parcel_id, 'sent');
            return true;
        } catch (Exception $e) {
            $this->logEmail($to, $subject, $parcel_id, 'failed', $mail->ErrorInfo);
            return false;
        }
    }

    /**
     * Log email
     */
    private function logEmail($to, $subject, $parcel_id, $status, $error = null) {
        $stmt = $this->pdo->prepare("
            INSERT INTO email_logs (recipient_email, subject, parcel_id, status, error_message)
            VALUES (:to, :subject, :parcel_id, :status, :error)
        ");

        $stmt->execute([
            ':to' => $to,
            ':subject' => $subject,
            ':parcel_id' => $parcel_id,
            ':status' => $status,
            ':error' => $error
        ]);
    }
}
