<?php
/**
 * bobcord_php.php — SDK BobCord (REST + builders)
 * User + Bot + EmbedBuilder + ActionRow / Button / WebAction
 * API: https://aml-s9xx-box.taildd440a.ts.net/api/v1.1
 * Pas de composer — file_get_contents / curl.
 */

const BOBCORD_DEFAULT_BASE = 'https://aml-s9xx-box.taildd440a.ts.net/api/v1.1';

function bobcord_web_action_confirm(string $title = 'Confirmer', string $body = '', ?array $then = null): array {
    $o = ['type' => 'confirm', 'title' => $title, 'body' => $body];
    if ($then !== null) $o['then'] = $then;
    return $o;
}

function bobcord_web_action_send_message(string $content, ?string $channel = null, $serverId = null, ?array $confirm = null): array {
    $o = ['type' => 'send_message', 'content' => $content];
    if ($channel !== null) $o['channel'] = $channel;
    if ($serverId !== null) $o['server_id'] = $serverId;
    if ($confirm !== null) $o['confirm'] = $confirm;
    return $o;
}

function bobcord_web_action_react(string $emoji = '👍', $messageId = 'self', ?array $confirm = null): array {
    $o = ['type' => 'react', 'emoji' => $emoji, 'message_id' => $messageId];
    if ($confirm !== null) $o['confirm'] = $confirm;
    return $o;
}

function bobcord_button(string $label, string $style = 'SECONDARY', ?string $customId = null, ?string $url = null, ?array $webAction = null, bool $disabled = false): array {
    $style = strtoupper($style);
    $o = ['type' => 'BUTTON', 'style' => $style, 'label' => $label, 'disabled' => $disabled];
    if ($style === 'LINK') {
        if (!$url) throw new InvalidArgumentException('LINK requires url');
        $o['url'] = $url;
    } else {
        if (!$customId) throw new InvalidArgumentException('BUTTON requires custom_id');
        $o['custom_id'] = $customId;
    }
    if ($style === 'WEB_ACTION') {
        if ($webAction === null) throw new InvalidArgumentException('WEB_ACTION requires web_action');
        $o['web_action'] = $webAction;
    }
    return $o;
}

function bobcord_action_row(array ...$components): array {
    return ['type' => 'ACTION_ROW', 'components' => array_slice($components, 0, 5)];
}

function bobcord_action_rows(array ...$rows): array {
    return array_slice($rows, 0, 4);
}

class EmbedBuilder {
    private array $data = ['fields' => []];
    public function title(string $t): self { $this->data['title'] = $t; return $this; }
    public function description(string $d): self { $this->data['description'] = $d; return $this; }
    public function color(int $c): self { $this->data['color'] = $c & 0xFFFFFF; return $this; }
    public function addField(string $name, string $value, bool $inline = false): self {
        $this->data['fields'][] = ['name' => $name, 'value' => $value, 'inline' => $inline];
        return $this;
    }
    public function footer(string $text): self { $this->data['footer'] = ['text' => $text]; return $this; }
    public function build(): array { return $this->data; }
}

class User {
    public string $token;
    public string $baseUrl = BOBCORD_DEFAULT_BASE;
    public ?array $me = null;

    public function __construct(string $token, string $baseUrl = BOBCORD_DEFAULT_BASE) {
        $this->token = trim($token);
        $this->baseUrl = rtrim($baseUrl, '/');
    }

    public function request(string $method, string $path, ?array $body = null) {
        $url = $this->baseUrl . '/' . ltrim($path, '/');
        $headers = [
            'Authorization: Bearer ' . $this->token,
            'Content-Type: application/json',
        ];
        $opts = [
            'http' => [
                'method' => $method,
                'header' => implode("\r\n", $headers),
                'ignore_errors' => true,
                'timeout' => 30,
            ],
        ];
        if ($body !== null) $opts['http']['content'] = json_encode($body, JSON_UNESCAPED_UNICODE);
        $raw = file_get_contents($url, false, stream_context_create($opts));
        $status = 0;
        if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m)) {
            $status = (int)$m[1];
        }
        if ($status === 204) return null;
        $data = $raw === false || $raw === '' ? [] : json_decode($raw, true);
        if ($status >= 400) {
            $err = is_array($data) ? ($data['error'] ?? $data) : $data;
            throw new RuntimeException("HTTP $status: " . json_encode($err));
        }
        return $data;
    }

    public function login(): array {
        $data = $this->request('GET', '/me');
        $this->me = $data['user'] ?? $data;
        return $this->me;
    }

    public function send(
        string $content = '',
        string $channel = 'général',
        int $serverId = 1,
        ?array $embeds = null,
        ?array $actionRows = null,
        $attachments = null
    ) {
        $body = ['content' => $content, 'channel' => $channel, 'server_id' => $serverId];
        if ($embeds !== null) $body['embeds'] = $embeds;
        if ($attachments !== null) $body['attachments'] = $attachments;
        if ($actionRows !== null) $body['action_rows'] = $actionRows;
        return $this->request('POST', '/message', $body);
    }

    public function edit($messageId, string $content) {
        return $this->request('PUT', '/message?id=' . urlencode((string)$messageId), ['content' => $content]);
    }

    public function delete($messageId) {
        return $this->request('DELETE', '/message', ['id' => $messageId]);
    }

    public function react($messageId, string $emoji) {
        return $this->request('PUT', '/message/react', ['id' => $messageId, 'emoji' => $emoji]);
    }
}

class Bot extends User {
    // même API REST ; WS optionnel côté app
}

/*
Exemple WEB_ACTION :
$user = new User('TON_TOKEN_24');
$rows = bobcord_action_rows(
    bobcord_action_row(
        bobcord_button('Réagir', 'WEB_ACTION', 'wa_r', null, bobcord_web_action_react('👍')),
        bobcord_button('Popup', 'WEB_ACTION', 'wa_c', null, bobcord_web_action_confirm('Sûr ?', 'popup custom'))
    )
);
$user->send('test', 'général', 1, null, $rows);
*/
