<?php
defined('BASEPATH') or exit('No direct script access allowed');

class DocuSignMailer
{
    protected $endpoint = "https://us-central1-duepro-2cf60.cloudfunctions.net/emailwidgets/sendemail";

    /**
     * Send email with PDF attachment (base64 encode PDF and send to API)
     */
    public function sendEmailWithPdf(array $recipients, string $subject, string $message, string $pdfData, string $attachmentName = 'signed_document.pdf')
    {
        // Encode PDF as base64 for transport
        // $base64Pdf = base64_encode($pdfData);
        // return $base64Pdf;
        $filePath = FCPATH . 'uploads/' . $attachmentName;
        file_put_contents($filePath, $pdfData);

        $pdfUrl = base_url('uploads/' . $attachmentName);


        $payload = [
            "email"       => $recipients[0],   // single recipient
            "subject"     => $subject,
            "message"     => $message,
            "pdfUrl"   => $pdfUrl,
            "pdfFileName" => $attachmentName
        ];
        print_r($payload);


        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $this->endpoint,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS     => json_encode($payload),
            CURLOPT_TIMEOUT        => 30,
        ]);

        $response = curl_exec($ch);
        $error    = curl_error($ch);
        curl_close($ch);

        if ($error) {
            return ['success' => false, 'error' => $error];
        }

        return ['success' => true, 'response' => $response];
    }

    /**
     * Send email specifically to user
     */
    public function sendUserEmail(string $userEmail, string $pdfData)
    {
        $subject = 'Your Document is Signed!';
        $message = 'Hello, your document has been signed successfully. Please see the attached PDF.';
        return $this->sendEmailWithPdf([$userEmail], $subject, $message, $pdfData, 'user_signed_document.pdf');
    }

    /**
     * Send email specifically to attorney
     */
    public function sendAttorneyEmail(string $attorneyEmail, string $pdfData)
    {
        $subject = 'Client Document Signed';
        $message = 'Hello, the client’s document has been signed. PDF attached for your records.';
        return $this->sendEmailWithPdf([$attorneyEmail], $subject, $message, $pdfData, 'attorney_signed_document.pdf');
    }
}
