<?php
$accessToken = 'uT0Ews6XCihlQ9p6HVAI5hjT9ZGcoymq1lmotLX7USH7Ne8pIt/9CG+mJXfXFaw4+I/NZpmBsDmTRefCDdjfLGN18vxfBNRhBjA/00jmyRlVbhs5HJ+YcIsQQkaEfWs+cfYSdFSj4+KoO6P0meJaYwdB04t89/1O/w1cDnyilFU=';

$input = file_get_contents("php://input");
$data  = json_decode($input, true);

// log เพื่อยืนยันว่าโดนเรียก
file_put_contents(__DIR__.'/log.txt', $input.PHP_EOL, FILE_APPEND);

http_response_code(200);

if (empty($data['events'])) exit;

foreach ($data['events'] as $event) {

    if (
        $event['type'] === 'message' &&
        $event['message']['type'] === 'text' &&
        $event['source']['type'] === 'group'
    ) {
        $replyToken = $event['replyToken'];
        $textIn = $event['message']['text'];

        replyMessage($accessToken, $replyToken, "✅ Bot ตอบในกลุ่ม: {$textIn}");
    }
}

function replyMessage($token, $replyToken, $text)
{
    $url = 'https://api.line.me/v2/bot/message/reply';

    $payload = [
        'replyToken' => $replyToken,
        'messages' => [[
            'type' => 'text',
            'text' => $text
        ]]
    ];

    $headers = [
        'Content-Type: application/json',
        'Authorization: Bearer '.$token
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => json_encode($payload),
    ]);

    $response = curl_exec($ch);
    file_put_contents(__DIR__.'/line_api.log', $response.PHP_EOL, FILE_APPEND);
    curl_close($ch);
}
