<?php
class ZaloService {
    private $accessToken;
    private $apiEndpoint = 'https://business.zalo.me/api/v2.0/oa/message/zns';

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

    public function sendZNS($phone, $templateId, $templateData) {
        $phone = preg_replace('/^0/', '84', $phone);

        $data = [
            'phone' => $phone,
            'template_id' => $templateId,
            'template_data' => $templateData,
        ];

        $headers = [
            'Content-Type: application/json',
            'access_token: ' . $this->accessToken,
        ];

        $ch = curl_init($this->apiEndpoint);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

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

        $result = json_decode($response, true);

        if ($httpCode !== 200 || $result['error'] !== 0) {
            return [
                'status' => 'error',
                'error_code' => $result['error'] ?? -1,
                'message' => $result['message'] ?? 'Unknown error occurred.',
                'data' => $result['data'] ?? null
            ];
        }

        return [
            'status' => 'success',
            'message' => 'Message sent successfully.',
            'data' => $result['data']
        ];
    }
}