<?php

namespace App\Services;

use App\Utils\Env;

class OneSignalService {
    private $appId;
    private $restApiKey;

    public function __construct() {
        $this->appId = Env::get('ONESIGNAL_APP_ID');
        $this->restApiKey = Env::get('ONESIGNAL_REST_API_KEY');
    }

    public function sendToUser($playerId, $title, $message, $data = []) {
        if (!$playerId) return;
        
        $fields = [
            'app_id' => $this->appId,
            'include_player_ids' => [$playerId],
            'headings' => ['en' => $title],
            'contents' => ['en' => $message],
            'data' => $data
        ];

        $this->sendRequest($fields);
    }

    public function broadcast($title, $message, $data = []) {
        $fields = [
            'app_id' => $this->appId,
            'included_segments' => ['All'],
            'headings' => ['en' => $title],
            'contents' => ['en' => $message],
            'data' => $data
        ];

        $this->sendRequest($fields);
    }

    private function sendRequest($fields) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json; charset=utf-8',
            'Authorization: Basic ' . $this->restApiKey
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }
}
