<?php
/**
 * API: Bind LINE User
 * URL: https://pack.iot-cm.com/api/bind_line.php
 * Method: POST
 * Return: JSON
 */

require_once "../config.php";
file_put_contents(
  __DIR__."/debug_login.txt",
  date("Y-m-d H:i:s")."\n".
  "POST: ".print_r($_POST, true)."\n".
  "RAW: ".file_get_contents("php://input")."\n\n",
  FILE_APPEND
);
header("Content-Type: application/json; charset=utf-8");

/* -----------------------------
   Allow only POST
------------------------------ */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        "status" => "error",
        "message" => "Method not allowed"
    ]);
    exit;
}

/* -----------------------------
   Read Input
------------------------------ */
$input = json_decode(file_get_contents("php://input"), true);

$user_id = intval($_POST['user_id'] ?? $input['user_id'] ?? 0);
$line_user_id = trim($_POST['line_user_id'] ?? $input['line_user_id'] ?? '');

if ($user_id <= 0 || $line_user_id === '') {
    echo json_encode([
        "status" => "error",
        "message" => "Missing parameters"
    ]);
    exit;
}


/* -----------------------------
   Check User Exists
------------------------------ */
$chkUser = $conn->prepare("
    SELECT id FROM users WHERE id = ?
");
$chkUser->bind_param("i", $user_id);
$chkUser->execute();
if ($chkUser->get_result()->num_rows === 0) {
    echo json_encode([
        "status" => "error",
        "message" => "User not found"
    ]);
    exit;
}
$chkUser->close();

/* -----------------------------
   Check LINE Already Bound
------------------------------ */
$chkLine = $conn->prepare("
    SELECT id FROM users
    WHERE line_user_id = ? AND id != ?
");
$chkLine->bind_param("si", $line_user_id, $user_id);
$chkLine->execute();
if ($chkLine->get_result()->num_rows > 0) {
    echo json_encode([
        "status" => "error",
        "message" => "LINE account already bound to another user"
    ]);
    exit;
}
$chkLine->close();

/* -----------------------------
   Bind LINE to User
------------------------------ */
$stmt = $conn->prepare("
    UPDATE users
    SET line_user_id = ?
    WHERE id = ?
");
$stmt->bind_param("si", $line_user_id, $user_id);
$stmt->execute();
$stmt->close();

/* -----------------------------
   Response
------------------------------ */
echo json_encode([
    "status" => "ok",
    "message" => "LINE account bound successfully"
]);
