<?php

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

require_once __DIR__ . '/../../vendor/autoload.php';

class EmailService {
    private $pdo;

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

    /**
     * Get system settings
     */
    private function getSettings() {
        try {
            $stmt = $this->pdo->query("SELECT setting_key, setting_value FROM settings");
            return $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        } catch (PDOException $e) {
            return [];
        }
    }

    /**
     * Send parcel notification email
     */
    public function sendParcelNotification($parcel, $recipient_email) {
        $settings = $this->getSettings();
        $mail = new PHPMailer(true);

        try {
            // Server settings
            $mail->isSMTP();
            $mail->Host       = $settings['smtp_host'] ?? 'smtp.gmail.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = $settings['smtp_user'] ?? '';
            $mail->Password   = $settings['smtp_pass'] ?? '';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = $settings['smtp_port'] ?? 587;

            // Sender info
            $fromEmail = $settings['company_email'] ?? 'no-reply@routexshipping.com';
            $fromName = $settings['company_name'] ?? 'RoutexShipping';
            $mail->setFrom($fromEmail, $fromName);
            
            // Recipient
            $mail->addAddress($recipient_email, $parcel['receiver_name']);

            // Content
            $date = date('Y-m-d');
            $subject = "Parcel Status Notification – {$date}";
            
            // Prepare variables
            $customerName = htmlspecialchars($parcel['receiver_name']);
            $trackingCode = htmlspecialchars($parcel['tracking_code']);
            $senderName = htmlspecialchars($parcel['sender_name']);
            $status = htmlspecialchars(ucwords(str_replace('_', ' ', $parcel['status'])));
            $companyName = htmlspecialchars($settings['company_name'] ?? 'RoutexShipping');
            $websiteUrl = 'www.routexshipping.com';

            // HTML Body
            $body = "
            <div style='font-family: Arial, sans-serif; color: #333; line-height: 1.6;'>
                <p>Dear {$customerName}：</p>
                <p>Good day!</p>
                <p>We trust this mail meets you well. This is to bring to your notice that your shipment with waybill number <strong>【{$trackingCode}】</strong> from <strong>【{$senderName}】</strong>, current status is <strong>【{$status}】</strong>.</p>
                <p>Please visit <a href='https://{$websiteUrl}' style='color: #2563eb; text-decoration: none;'>{$websiteUrl}</a> for more details.</p>
                <br>
                <p>Best regards,<br>{$companyName}</p>
            </div>";

            $altBody = "Dear {$customerName}：\n\nGood day!\n\nWe trust this mail meets you well. This is to bring to your notice that your shipment with waybill number 【{$trackingCode}】 from 【{$senderName}】, current status is 【{$status}】.\n\nPlease visit {$websiteUrl} for more details.\n\nBest regards,\n{$companyName}";

            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $body;
            $mail->AltBody = $altBody;

            $mail->send();

            // Log success
            $this->logEmail($recipient_email, $subject, $parcel['id'], 'sent');
            return true;

        } catch (Exception $e) {
            // Log error
            $this->logEmail($recipient_email, $subject ?? 'Notification', $parcel['id'], 'failed', $mail->ErrorInfo);
            return false;
        }
    }

    /**
     * Log email to database
     */
    private function logEmail($recipient, $subject, $parcel_id, $status, $error = null) {
        try {
            $stmt = $this->pdo->prepare("
                INSERT INTO email_logs (recipient_email, subject, parcel_id, status, error_message)
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([$recipient, $subject, $parcel_id, $status, $error]);
        } catch (PDOException $e) {
            // Silent fail for logging
        }
    }
}