<?php
// app/Libraries/EmailService.php
namespace App\Libraries;

/**
 * Service untuk menangani pengiriman email, secara eksklusif via SendGrid HTTP API.
 */
class EmailService
{
    protected string $apiKey;
    protected string $apiUrl;
    protected string $fromEmail;
    protected string $fromName;
    protected \CodeIgniter\HTTP\CURLRequest $client;

    public function __construct()
    {
        $this->apiKey    = getenv('sendgrid.apiKey');
        $this->apiUrl    = getenv('sendgrid.apiUrl');
        $this->fromEmail = getenv('sendgrid.fromEmail');
        $this->fromName  = getenv('sendgrid.fromName');

        $this->client = \Config\Services::curlrequest(['timeout' => 15]);
    }

    /**
     * Mengirim email berisi link verifikasi.
     */
    public function sendVerificationLink(string $recipientEmail, string $verificationLink): bool
    {
        $data = [
            'subject'          => lang('Notifications.verificationSubject', [getenv('app.name')]),
            'greeting'         => lang('Notifications.verificationGreeting'),
            'message'          => lang('Notifications.verificationMessage', [getenv('app.name')]),
            'buttonText'       => lang('Notifications.verificationButton'),
            'backupText'       => lang('Notifications.verificationBackup'),
            'disclaimer'       => lang('Notifications.verificationDisclaimer'),
            'verificationLink' => $verificationLink,
        ];
        
        $content = view('emails/password_reset_link', $data); // Gunakan template yang sama
        return $this->send($recipientEmail, $data['subject'], $content);
    }

    /**
     * Mengirim email konfirmasi bahwa transaksi sedang menunggu pembayaran.
     */
    public function sendTransactionPending(string $recipientEmail, array $data): bool
    {
        $subject = 'Your '.$data['event']->name.' Order is Pending (#' . $data['transaction']->invoice_number . ')';
        $content = view('emails/transaction_pending', $data);
        
        return $this->send($recipientEmail, $subject, $content);
    }

    /**
     * Mengirim email konfirmasi bahwa pembayaran telah berhasil (dengan lampiran QR dan PDF).
     */
    public function sendTransactionPaid(string $recipientEmail, array $data, ?string $pdfPath = null): bool
    {
        $subject = 'Payment Successful for '.$data['event']->name.' (#' . $data['transaction']->invoice_number . ')';
        $content = view('emails/transaction_paid', $data);
        
        // Siapkan array untuk lampiran
        $attachments = [];

        // 1. Siapkan lampiran PDF jika ada
        if ($pdfPath && file_exists($pdfPath)) {
            $attachments[] = [
                'content'     => base64_encode(file_get_contents($pdfPath)),
                'filename'    => basename($pdfPath),
                'type'        => 'application/pdf',
                'disposition' => 'attachment'
            ];
        }

        // 2. Siapkan lampiran gambar QR (inline)
        $qrCodePath = WRITEPATH . 'qrcodes' . DIRECTORY_SEPARATOR;
        foreach ($data['participants'] as $participant) {
            if (!empty($participant->qr_image_path)) {
                $fullImagePath = $qrCodePath . $participant->qr_image_path;
                if (file_exists($fullImagePath)) {
                    $attachments[] = [
                        'content'     => base64_encode(file_get_contents($fullImagePath)),
                        'filename'    => $participant->qr_image_path,
                        'type'        => 'image/png',
                        'disposition' => 'inline',
                        'content_id'  => $participant->qr_number // Ini adalah CID
                    ];
                }
            }
        }
        
        // Panggil metode send dengan array lampiran
        return $this->send($recipientEmail, $subject, $content, $attachments);
    }

    public function sendTransactionRejected(string $recipientEmail, array $data): bool
    {
        $subject = lang('Notifications.trxRejectedSubject', [$data['transaction']->invoice_number]);
        $content = view('emails/transaction_rejected', $data);
        return $this->send($recipientEmail, $subject, $content);
    }

    public function sendTransactionCanceled(string $recipientEmail, array $data): bool
    {
        $subject = lang('Notifications.trxCanceledSubject', [$data['transaction']->invoice_number]);
        $content = view('emails/transaction_canceled', $data);
        return $this->send($recipientEmail, $subject, $content);
    }

    public function sendEmailChangeVerification(string $recipientEmail, string $verificationLink): bool
    {
        $data = [
            'subject'          => lang('Notifications.emailChangeSubject'),
            'greeting'         => lang('Notifications.emailChangeGreeting'),
            'message'          => lang('Notifications.emailChangeMessage', [getenv('app.name')]),
            'buttonText'       => lang('Notifications.emailChangeButton'),
            'backupText'       => lang('Notifications.verificationBackup'),
            'disclaimer'       => lang('Notifications.emailChangeDisclaimer'),
            'verificationLink' => $verificationLink,
        ];
        
        $content = view('emails/password_reset_link', $data); // Gunakan template yang sama
        return $this->send($recipientEmail, $data['subject'], $content);
    }

    public function sendPasswordResetLink(string $recipientEmail, string $resetLink): bool
    {
        $data = [
            'subject'          => lang('Notifications.passwordResetSubject'),
            'greeting'         => lang('Notifications.emailChangeGreeting'), // Bisa buat key baru
            'message'          => lang('Notifications.passwordResetMessage'),
            'buttonText'       => lang('Notifications.passwordResetButton'),
            'backupText'       => lang('Notifications.verificationBackup'),
            'disclaimer'       => lang('Notifications.passwordResetDisclaimer'),
            'verificationLink' => $resetLink, // Ganti nama variabel agar konsisten
        ];
        
        $content = view('emails/password_reset_link', $data);
        return $this->send($recipientEmail, $data['subject'], $content);
    }

    /**
     * Fungsi utama untuk mengirim semua jenis email via SendGrid API.
     */
    private function send(string $to, string $subject, string $htmlContent, array $attachments = []): bool
    {
        if (empty($this->apiKey) || empty($this->fromEmail) || empty($this->apiUrl)) {
            log_message('error', 'SendGrid is not fully configured.');
            return false;
        }

        $payload = [
            'personalizations' => [['to' => [['email' => $to]], 'subject' => $subject]],
            'from' => ['email' => $this->fromEmail, 'name' => $this->fromName],
            'content' => [['type' => 'text/html', 'value' => $htmlContent]]
        ];

        // Tambahkan lampiran ke payload jika ada
        if (!empty($attachments)) {
            $payload['attachments'] = $attachments;
        }

        try {
            $response = $this->client->post($this->apiUrl, [
                'headers' => ['Authorization' => 'Bearer ' . $this->apiKey, 'Content-Type'  => 'application/json'],
                'json' => $payload,
                'http_errors' => false 
            ]);
            
            if ($response->getStatusCode() === 202) {
                return true;
            }

            log_message('error', 'SendGrid API Error: ' . $response->getBody());
            return false;

        } catch (\Exception $e) {
            log_message('error', 'CURLRequest to SendGrid failed: ' . $e->getMessage());
            return false;
        }
    }
}