<?php
require_once "../config.php";

$body = json_decode(file_get_contents("php://input"), true);
$event = $body['events'][0] ?? null;
if (!$event) exit;

/* ===============================
   FOLLOW EVENT (ผูก LINE USER)
================================ */
if ($event['type'] === 'follow') {

    $lineUserId = $event['source']['userId'];

    // ❗ กรณีง่าย: ผูกกับ user ที่ login ล่าสุด
    // (Production แนะนำให้ใช้ LIFF หรือ token)
    if (isset($_SESSION['uid'])) {
        $stmt = $conn->prepare("
          UPDATE users 
          SET line_user_id=?
          WHERE id=?
        ");
        $stmt->bind_param("si", $lineUserId, $_SESSION['uid']);
        $stmt->execute();
        $stmt->close();
    }

    // ตอบกลับ
    replyText(
        $event['replyToken'],
        "✅ ผูก LINE กับระบบเรียบร้อย\nระบบแจ้งเตือนพร้อมใช้งานแล้ว 🎒"
    );
    exit;
}

if ($event['type'] === 'postback') {
    $data = $event['postback']['data'];
    $lineUserId = $event['source']['userId'];

    if ($data === 'confirm_items') {

        /* ⚠️ ตัวอย่าง map line_user_id → user_id */
        $user_id = 3; // TODO: lookup จริงจาก DB

        $map = [
          'Mon'=>'monday','Tue'=>'tuesday','Wed'=>'wednesday',
          'Thu'=>'thursday','Fri'=>'friday',
          'Sat'=>'saturday','Sun'=>'sunday'
        ];
        $today = $map[date('D')];

        $items = $conn->prepare("
            SELECT id FROM items
            WHERE user_id=? AND day=?
        ");
        $items->bind_param("is", $user_id,$today);
        $items->execute();
        $res = $items->get_result();

        while ($i = $res->fetch_assoc()) {
            $ins = $conn->prepare("
                INSERT IGNORE INTO item_status
                (user_id,item_id,date,status)
                VALUES (?,?,CURDATE(),'done')
            ");
            $ins->bind_param("ii", $user_id,$i['id']);
            $ins->execute();
            $ins->close();
        }
    }
}
