<?php

class SupportApi
{
    private string $server;

    public function __construct(string $server)
    {
        $this->server = rtrim($server, '/');
    }

    private function post(string $endpoint, array $payload): array
    {
        $url = $this->server . '/api/support/' . ltrim($endpoint, '/');

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload, JSON_UNESCAPED_UNICODE));
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);

        $res = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);

        if ($res === false) {
            return ['ok' => false, 'error' => 'curl_error', 'details' => $err];
        }

        $data = json_decode($res, true);
        if (!is_array($data)) {
            return ['ok' => false, 'error' => 'invalid_json_response', 'raw' => $res];
        }

        return $data;
    }

    public function createTicket(array $payload): array
    {
        return $this->post('create_ticket.php', $payload);
    }

    public function listTickets(array $payload): array
    {
        return $this->post('list_tickets.php', $payload);
    }

    public function getMessages(array $payload): array
    {
        return $this->post('get_messages.php', $payload);
    }

    public function reply(array $payload): array
    {
        return $this->post('reply.php', $payload);
    }

    public function unreadCount(array $payload): array
    {
        return $this->post('unread_count.php', $payload);
    }
}
