<?php

namespace BitApps\PiPro\src\Integrations\Line\helpers;

use BitApps\Pi\Helpers\Hash;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Client\HttpClient;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Request\Request;

// Prevent direct script access
if (!\defined('ABSPATH')) {
    exit;
}

class LineActionHandler
{
    public static function prepareMessageContent(
        $configs,
        $message,
        $emojiRepeaterFields,
        $audioRepeaterFields,
        $videoRepeaterFields,
        $stickerRepeaterFields,
        $imageRepeaterFields,
        $locationRepeaterFields
    ) {
        if ($configs['emoji-switch']['value'] === true) {
            $message = array_merge($message, ['emojis' => $emojiRepeaterFields]);
        }

        $messageContent = [$message];

        if ($configs['sticker-switch']['value'] === true) {
            $messageContent = array_merge($messageContent, $stickerRepeaterFields);
        }
        if ($configs['audio-switch']['value'] === true) {
            $messageContent = array_merge($messageContent, $audioRepeaterFields);
        }
        if ($configs['video-switch']['value'] === true) {
            $messageContent = array_merge($messageContent, $videoRepeaterFields);
        }
        if ($configs['image-switch']['value'] === true) {
            $messageContent = array_merge($messageContent, $imageRepeaterFields);
        }
        if ($configs['location-switch']['value'] === true) {
            $messageContent = array_merge($messageContent, $locationRepeaterFields);
        }

        return $messageContent;
    }

    public function setLineWebhook(Request $request)
    {
        $validated = $request->validate(
            [
                'token'    => ['required', 'string'],
                'endpoint' => ['required', 'url', 'sanitize:url'],
            ]
        );

        $token = Hash::decrypt($validated['token']);
        $endpoint = $validated['endpoint'];

        $httpClient = new HttpClient(
            [
                'headers' => [
                    'Authorization' => 'Bearer ' . $token,
                    'Content-Type'  => 'application/json'
                ]
            ]
        );

        return $httpClient->request(
            'https://api.line.me/v2/bot/channel/webhook/endpoint',
            'PUT',
            wp_json_encode(['endpoint' => $endpoint])
        );
    }
}
