<?php

namespace App\Services;

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

class MailService
{
    private PHPMailer $mail;

    public function __construct()
    {
        $this->mail = new PHPMailer(true);
        $this->configure();
    }

    private function configure(): void
    {
        $this->mail->isSMTP();
        $this->mail->Host       = $_ENV['MAIL_HOST'] ?? '';
        $this->mail->SMTPAuth   = true;
        $this->mail->Username   = $_ENV['MAIL_USERNAME'] ?? '';
        $this->mail->Password   = $_ENV['MAIL_PASSWORD'] ?? '';
        $this->mail->SMTPSecure = $_ENV['MAIL_ENCRYPTION'] ?? 'tls';
        $this->mail->Port       = $_ENV['MAIL_PORT'] ?? 587;

        $this->mail->setFrom(
            $_ENV['MAIL_FROM'] ?? 'no-reply@localhost',
            $_ENV['MAIL_FROM_NAME'] ?? 'Exclusive Concierge'
        );

        $this->mail->isHTML(true);
    }

    public function sendBookingConfirmation(array $data): bool
    {
        try {

            $this->mail->clearAddresses();
            $this->mail->addAddress($data['customer_email'], $data['customer_name']);

            if (!empty($_ENV['ADMIN_EMAIL'])) {
                $this->mail->addCC($_ENV['ADMIN_EMAIL']);
            }

            $this->mail->Subject = "Booking Confirmation - {$data['booking_reference']}";

            $this->mail->Body = $this->buildTemplate($data);

            return $this->mail->send();

        } catch (Exception $e) {
            error_log("Mail Error: " . $this->mail->ErrorInfo);
            return false;
        }
    }

    private function buildTemplate(array $data): string
    {
        return "
        <div style='font-family:Arial;background:#0B0F19;color:#E5E7EB;padding:20px;'>
            <h2 style='color:#C9A24D;'>Booking Confirmed</h2>

            <p>Dear {$data['customer_name']},</p>

            <p>Your booking has been successfully created.</p>

            <table width='100%' cellpadding='8' style='background:#1F2937;border-radius:8px;'>
                <tr><td><strong>Reference:</strong></td><td>{$data['booking_reference']}</td></tr>
                <tr><td><strong>Service:</strong></td><td>{$data['service_name']}</td></tr>
                <tr><td><strong>Pickup:</strong></td><td>{$data['pickup_address']}</td></tr>
                <tr><td><strong>Dropoff:</strong></td><td>{$data['dropoff_address']}</td></tr>
                <tr><td><strong>Date & Time:</strong></td><td>{$data['pickup_datetime']}</td></tr>
                <tr><td><strong>Total:</strong></td><td>$ {$data['final_price']}</td></tr>
            </table>

            <p style='margin-top:20px;'>
                Our concierge team will contact you shortly.
            </p>

            <p style='color:#9CA3AF;'>Exclusive Concierge</p>
        </div>
        ";
    }
}
