<?php
header("Content-Type: application/json");

// Include database connection
require_once "../database.php";

// Allow only POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["error" => "Only POST method allowed"]);
    exit;
}

// Get and decode JSON input
$data = json_decode(file_get_contents("php://input"));

// Validate input
if (!isset($data->user_id) || !is_numeric($data->user_id) || empty($data->fcm)) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid or missing user_id or fcm"]);
    exit;
}

$userId = intval($data->user_id);
$fcm = $data->fcm;

try {
    // Check if user exists
    $checkStmt = $conn->prepare("SELECT id FROM users WHERE id = :id");
    $checkStmt->bindParam(':id', $userId);
    $checkStmt->execute();

    if ($checkStmt->rowCount() === 0) {
        http_response_code(404);
        echo json_encode(["error" => "User not found"]);
        exit;
    }

    // Update fcm token
    $updateStmt = $conn->prepare("UPDATE users SET fcm = :fcm WHERE id = :id");
    $updateStmt->bindParam(':fcm', $fcm);
    $updateStmt->bindParam(':id', $userId);
    $updateStmt->execute();

    echo json_encode(["status" => "success", "message" => "FCM updated"]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["error" => "Database error", "details" => $e->getMessage()]);
}
?>
