<?php
// กำหนดข้อมูลสำหรับการเชื่อมต่อ MySQL
$servername = "localhost";
$username = "dufoon";
$password = "Tech0015";
$dbname = "dufoon";

// สร้างการเชื่อมต่อกับฐานข้อมูล
$conn = new mysqli($servername, $username, $password, $dbname);

// ตรวจสอบการเชื่อมต่อ
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// ฟังก์ชันสำหรับส่งข้อความผ่าน LINE Push Message API
function sendPush($userId, $message) {
    $access_token = 'xocNxD4lJiyghr0oWS+j7uyYGnS6mXVziZr6f+p94lf6j5EfBfEViAFXDpE6EUPQkWfQ3r83dwbNBI3Owtbi6LNIJiPLreNz0Iyelda3ycfmbSK6et1PDUdV9pusLy3/RkX2YZK8l3BGpCbkLkZfhQdB04t89/1O/w1cDnyilFU=';

    $data = [
        'to' => $userId,
        'messages' => [$message]
    ];

    $post_data = json_encode($data);
    $ch = curl_init('https://api.line.me/v2/bot/message/push');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $access_token
    ));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    $result = curl_exec($ch);
    if ($result === false) {
        error_log("cURL Error: " . curl_error($ch));
    } else {
        error_log("cURL Result: " . $result);
    }
    curl_close($ch);
}

// ฟังก์ชันสำหรับส่งการตอบกลับผ่าน LINE Reply Message API
function sendReply($replyToken, $message) {
    $access_token = 'xocNxD4lJiyghr0oWS+j7uyYGnS6mXVziZr6f+p94lf6j5EfBfEViAFXDpE6EUPQkWfQ3r83dwbNBI3Owtbi6LNIJiPLreNz0Iyelda3ycfmbSK6et1PDUdV9pusLy3/RkX2YZK8l3BGpCbkLkZfhQdB04t89/1O/w1cDnyilFU=';

    $data = [
        'replyToken' => $replyToken,
        'messages' => [$message]
    ];

    $post_data = json_encode($data);
    $ch = curl_init('https://api.line.me/v2/bot/message/reply');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $access_token
    ));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    $result = curl_exec($ch);
    if ($result === false) {
        error_log("cURL Error: " . curl_error($ch));
    } else {
        error_log("cURL Result: " . $result);
    }
    curl_close($ch);
}

// ตรวจสอบว่าเป็น Webhook หรือ Cronjob
if (php_sapi_name() === 'cli' || isset($_GET['cronjob'])) {
    // การทำงานผ่าน Cronjob
    error_log("Start Cronjob Mode");

    $sqlUsers = "SELECT user_id FROM user_alerts WHERE alert_enabled = 1";
    $resultUsers = $conn->query($sqlUsers);

    if ($resultUsers->num_rows > 0) {
        $sqlData = "SELECT weather1_time, weather1_pm25, weather1_temperature, weather1_humidity 
                    FROM weather_location1 
                    ORDER BY weather1_time DESC 
                    LIMIT 1";
        $resultData = $conn->query($sqlData);

        if ($resultData->num_rows > 0) {
            $rowData = $resultData->fetch_assoc();
            $time = $rowData['weather1_time'];
            $pm25 = $rowData['weather1_pm25'];
            $temperature = $rowData['weather1_temperature'];
            $humidity = $rowData['weather1_humidity'];

            // คำนวณค่า AQI จากค่า PM2.5
            if ($pm25 <= 25) { 
                $aqi = ($pm25 / 25) * 25;  
                $airQuality = "คุณภาพ: ดีมาก";
                $description = "ไม่ต้องสวมแมสก็ได้ ทำกิจกรรมกลางแจ้งได้ตามปกติไม่มีผลกระทบต่อสุขภาพ";
                $imageUrl = "https://dufoon.cm.in.th/Image/VeryGoodAQI.png";
            } elseif ($pm25 <= 37) {
                $aqi = ((50 - 26) / (37 - 26)) * ($pm25 - 26) + 26;  
                $airQuality = "คุณภาพ: ดี";
                $description = "สวมหรือไม่สวมแมสก็ได้ ลดระยะเวลาทำกิจกรรมกลางแจ้งกลุ่มเสี่ยงอาจมีอาการระคายเคือง";
                $imageUrl = "https://dufoon.cm.in.th/Image/GoodAQI.png";
            } elseif ($pm25 <= 50) {
                $aqi = ((100 - 51) / (50 - 38)) * ($pm25 - 38) + 51;  
                $airQuality = "คุณภาพ: ปานกลาง";
                $description = "ควรสวมแมส หลีกเลี่ยงการทำกิจกรรมหนักกลางแจ้งทุกคนอาจมีอาการระคายเคือง";
                $imageUrl = "https://dufoon.cm.in.th/Image/MediumAQI.png";
            } elseif ($pm25 <= 90) {
                $aqi = ((200 - 101) / (90 - 51)) * ($pm25 - 51) + 101;  
                $airQuality = "คุณภาพ: แย่";
                $description = "ต้องสวมแมส ลดกิจกรรมกลางแจ้ง และติดตามอาการกลุ่มเสี่ยงมีผลกระทบต่อสุขภาพรุนแรง";
                $imageUrl = "https://dufoon.cm.in.th/Image/BadAQI.png";
            } elseif ($pm25 >= 91) {
                $aqi = ((200 - 101) / (90 - 51)) * ($pm25 - 51) + 101;
                $airQuality = "คุณภาพ: แย่มาก";
                $description = "หลีกเลี่ยงการออกจากบ้านทุกคนมีผลกระทบต่อสุขภาพรุนแรง";
                $imageUrl = "https://dufoon.cm.in.th/Image/WorseAQI.png";
            }
            

            // สร้างข้อความตอบกลับแบบ Flex Message
$replyMessage = [
    'type' => 'flex',
    'altText' => 'ผลรายงานคุณภาพอากาศ',
    'contents' => [
        'type' => 'bubble',
        'hero' => [
            'type' => 'image',
            'url' => $imageUrl,
            'size' => 'full',
            'aspectRatio' => '10:10',
            'aspectMode' => 'cover'
        ],
        'body' => [
            'type' => 'box',
            'layout' => 'vertical',
            'contents' => [
                [
                    'type' => 'text',
                    'text' => 'ผลรายงานคุณภาพอากาศ',
                    'weight' => 'bold',
                    'size' => 'xl',
                    'margin' => 'md'
                ],
                [
                    'type' => 'box',
                    'layout' => 'vertical',
                    'margin' => 'lg',
                    'spacing' => 'sm',
                    'contents' => [
                        [
                            'type' => 'box',
                            'layout' => 'baseline',
                            'contents' => [
                                [
                                    'type' => 'text',
                                    'text' => 'สถานที่',
                                    'color' => '#aaaaaa',
                                    'size' => 'sm',
                                    'flex' => 2
                                ],
                                [
                                    'type' => 'text',
                                    'text' => 'วิทยาลัยเทคนิคเชียงใหม่',
                                    'wrap' => true,
                                    'color' => '#666666',
                                    'size' => 'sm',
                                    'flex' => 5
                                ]
                            ]
                        ],
                        [
                            'type' => 'box',
                            'layout' => 'baseline',
                            'contents' => [
                                [
                                    'type' => 'text',
                                    'text' => 'เวลา',
                                    'color' => '#aaaaaa',
                                    'size' => 'sm',
                                    'flex' => 2
                                ],
                                [
                                    'type' => 'text',
                                    'text' => $time,
                                    'wrap' => true,
                                    'color' => '#666666',
                                    'size' => 'sm',
                                    'flex' => 5
                                ]
                            ]
                        ],
                        [
                            'type' => 'box',
                            'layout' => 'baseline',
                            'contents' => [
                                [
                                    'type' => 'text',
                                    'text' => 'PM2.5',
                                    'color' => '#aaaaaa',
                                    'size' => 'sm',
                                    'flex' => 2
                                ],
                                [
                                    'type' => 'text',
                                    'text' => "$pm25 µg/m³",
                                    'wrap' => true,
                                    'color' => '#666666',
                                    'size' => 'sm',
                                    'flex' => 5
                                ]
                            ]
                        ],
                        [
                            'type' => 'box',
                            'layout' => 'baseline',
                            'contents' => [
                                [
                                    'type' => 'text',
                                    'text' => 'อุณหภูมิ',
                                    'color' => '#aaaaaa',
                                    'size' => 'sm',
                                    'flex' => 2
                                ],
                                [
                                    'type' => 'text',
                                    'text' => "$temperature °C",
                                    'wrap' => true,
                                    'color' => '#666666',
                                    'size' => 'sm',
                                    'flex' => 5
                                ]
                            ]
                        ],
                        [
                            'type' => 'box',
                            'layout' => 'baseline',
                            'contents' => [
                                [
                                    'type' => 'text',
                                    'text' => 'ความชื้น',
                                    'color' => '#aaaaaa',
                                    'size' => 'sm',
                                    'flex' => 2
                                ],
                                [
                                    'type' => 'text',
                                    'text' => "$humidity %",
                                    'wrap' => true,
                                    'color' => '#666666',
                                    'size' => 'sm',
                                    'flex' => 5
                                ]
                            ]
                        ],
                        [
                            'type' => 'box',
                            'layout' => 'baseline',
                            'contents' => [
                                [
                                    'type' => 'text',
                                    'text' => 'ค่า AQI',
                                    'color' => '#aaaaaa',
                                    'size' => 'sm',
                                    'flex' => 2
                                ],
                                [
                                    'type' => 'text',
                                    'text' => "$aqi",
                                    'wrap' => true,
                                    'color' => '#666666',
                                    'size' => 'sm',
                                    'flex' => 5
                                ]
                            ]
                        ],
                        [
                            'type' => 'box',
                            'layout' => 'baseline',
                            'contents' => [
                                [
                                    'type' => 'text',
                                    'text' => 'คุณภาพ',
                                    'color' => '#aaaaaa',
                                    'size' => 'sm',
                                    'flex' => 2
                                ],
                                [
                                    'type' => 'text',
                                    'text' => $airQuality,
                                    'wrap' => true,
                                    'color' => '#666666',
                                    'size' => 'sm',
                                    'flex' => 5
                                    ]
                            ]
                        ],
                        [
                            'type' => 'box',
                            'layout' => 'baseline',
                            'contents' => [
                                ['type' => 'text', 'text' => 'คำแนะนำ', 'color' => '#aaaaaa', 'size' => 'sm', 'flex' => 2],
                                ['type' => 'text', 'text' => $description, 'wrap' => true, 'color' => '#666666', 'size' => 'sm', 'flex' => 5]
                            ]
                        ]
                    ]
                ]
            ]
        ],
        'footer' => [
            'type' => 'box',
            'layout' => 'vertical',
            'spacing' => 'sm',
            'contents' => [
                [
                    'type' => 'button',
                    'style' => 'link',
                    'height' => 'sm',
                    'action' => [
                        'type' => 'uri',
                        'label' => 'เว็บไซต์',
                        'uri' => 'https://dufoon.cm.in.th/'
                    ]
                ]
            ],
            'flex' => 0
        ]
    ]
];


            // ส่งข้อความถึงผู้ใช้
            while ($row = $resultUsers->fetch_assoc()) {
                $userId = $row['user_id'];
                error_log("Sending to user: " . $userId);
                sendPush($userId, $replyMessage);
            }
        } else {
            error_log("No weather data found.");
        }
    } else {
        error_log("No users found.");
    }
} else {
    // การทำงานผ่าน Webhook
    error_log("Webhook request received");

    $content = file_get_contents('php://input');
    $events = json_decode($content, true);

    if (!is_null($events['events'])) {
        foreach ($events['events'] as $event) {
            if ($event['type'] == 'message' && $event['message']['type'] == 'text') {
                $userMessage = strtolower($event['message']['text']);
                $userId = $event['source']['userId'];
                $replyToken = $event['replyToken'];

                if ($userMessage == 'เปิดการแจ้งเตือน') {
                    $updateSql = "INSERT INTO user_alerts (user_id, alert_enabled) VALUES ('$userId', 1) 
                                  ON DUPLICATE KEY UPDATE alert_enabled = 1";
                    $conn->query($updateSql);
                    sendReply($replyToken, ['type' => 'text', 'text' => 'เปิดการแจ้งเตือนสำเร็จ']);
                } elseif ($userMessage == 'ปิดการแจ้งเตือน') {
                    $updateSql = "UPDATE user_alerts SET alert_enabled = 0 WHERE user_id = '$userId'";
                    $conn->query($updateSql);
                    sendReply($replyToken, ['type' => 'text', 'text' => 'ปิดการแจ้งเตือนสำเร็จ']);
                }
            }
        }
    }
}

// ปิดการเชื่อมต่อกับฐานข้อมูล
$conn->close();
?>
