<?php
class CommunicationSenderController {
    private $brevoApiKey;
    private $twilioAccountSid;
    private $twilioAuthToken;
    private $twilioPhoneNumber; // Your default Twilio number (e.g., '+1234567890')

    public function __construct($brevoApiKey = null, $twilioAccountSid = null, $twilioAuthToken = null, $twilioPhoneNumber = null) {
        // Load from config/env - adjust as needed
        $this->brevoApiKey = $brevoApiKey ?: $_ENV['BREVO_API_KEY'] ?? 'YOUR_BREVO_API_KEY';
        $this->twilioAccountSid = $twilioAccountSid ?: $_ENV['TWILIO_ACCOUNT_SID'] ?? 'YOUR_TWILIO_ACCOUNT_SID';
        $this->twilioAuthToken = $twilioAuthToken ?: $_ENV['TWILIO_AUTH_TOKEN'] ?? 'YOUR_TWILIO_AUTH_TOKEN';
        $this->twilioPhoneNumber = $twilioPhoneNumber ?: $_ENV['TWILIO_PHONE_NUMBER'] ?? '+1234567890';
    }

    /**
     * Send transactional email via Brevo API
     * @param string $toEmail Recipient email
     * @param string $toName Recipient name (optional)
     * @param string $subject Email subject
     * @param string $htmlContent HTML body (or use templateId for dynamic)
     * @param string $fromEmail Sender email (must be verified in Brevo)
     * @param string $fromName Sender name
     * @param int $templateId Optional: Use Brevo template ID instead of htmlContent
     * @param array $params Optional: Dynamic params for template (e.g., ['name' => 'John'])
     * @return array JSON response with status, data, or error
     */
    public function sendEmail($toEmail, $subject, $toName = '', $htmlContent = '', $fromEmail = 'noreply@ips.gov', $fromName = 'IPS System', $templateId = null, $params = []) {
        if (empty($toEmail) || empty($subject)) {
            return $this->errorResponse('Missing required fields: toEmail or subject');
        }

        $url = 'https://api.brevo.com/v3/smtp/email';
        $payload = [
            'sender' => [
                'name' => $fromName,
                'email' => $fromEmail
            ],
            'to' => [
                [
                    'email' => $toEmail,
                    'name' => $toName
                ]
            ],
            'subject' => $subject
        ];

        // Use template if provided
        if ($templateId) {
            $payload['templateId'] = (int)$templateId;
            if (!empty($params)) $payload['params'] = $params;
        } else {
            if (empty($htmlContent)) {
                return $this->errorResponse('htmlContent or templateId required');
            }
            $payload['htmlContent'] = $htmlContent;
        }

        return $this->sendCurlRequest('POST', $url, json_encode($payload), [
            'accept: application/json',
            'api-key: ' . $this->brevoApiKey,
            'content-type: application/json'
        ]);
    }

    /**
     * Send SMS via Twilio API
     * @param string $toPhone Recipient phone (E.164, e.g., '+1234567890')
     * @param string $messageBody SMS content (max 1600 chars)
     * @param string $fromPhone Optional: Override default Twilio number
     * @return array JSON response with status, data, or error
     */
    public function sendSMS($toPhone, $messageBody, $fromPhone = null) {
        if (empty($toPhone) || empty($messageBody)) {
            return $this->errorResponse('Missing required fields: toPhone or messageBody');
        }

        $url = "https://api.twilio.com/2010-04-01/Accounts/{$this->twilioAccountSid}/Messages.json";
        $from = $fromPhone ?: $this->twilioPhoneNumber;
        $data = [
            'To' => $toPhone,
            'From' => $from,
            'Body' => $messageBody
        ];

        return $this->sendTwilioRequest('POST', $url, $data);
    }

    // Private helpers
    private function sendCurlRequest($method, $url, $payload, $headers) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            return $this->errorResponse('cURL Error: ' . $error);
        }

        if ($httpCode === 201) {
            $result = json_decode($response, true);
            return [
                'status' => 'success',
                'data' => [
                    'message' => $result['messageId'] ?? 'Email sent successfully',
                    'messageId' => $result['messageId'] ?? null
                ]
            ];
        }

        $errorMsg = json_decode($response, true)['message'] ?? 'API Error';
        return $this->errorResponse($errorMsg, $httpCode);
    }

    private function sendTwilioRequest($method, $url, $formData) {
        $auth = base64_encode($this->twilioAccountSid . ':' . $this->twilioAuthToken);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($formData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Basic ' . $auth,
            'Content-Type: application/x-www-form-urlencoded'
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            return $this->errorResponse('cURL Error: ' . $error);
        }

        if ($httpCode === 201) {
            $result = json_decode($response, true);
            return [
                'status' => 'success',
                'data' => [
                    'message' => $result['sid'] ?? 'SMS sent successfully',
                    'messageSid' => $result['sid'] ?? null
                ]
            ];
        }

        $errorMsg = json_decode($response, true)['message'] ?? 'API Error';
        return $this->errorResponse($errorMsg, $httpCode);
    }

    private function errorResponse($message, $code = 400) {
        http_response_code($code);
        return json_encode([
            'status' => 'error',
            'message' => $message
        ]);
    }
}