<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header("Access-Control-Allow-Headers: X-Requested-With");

if(isset($_POST['user_id']) && isset($_POST['auth']) && isset($_POST['token'])) {
require_once 'db/config.php'; // should set $con (PDO)

    $user_id = trim($_POST['user_id']);
    $auth    = trim($_POST['auth']);
    $token   = trim($_POST['token']);

    // ✅ Verify user credentials
    $stmt = $con->prepare("SELECT user_id FROM users WHERE user_id = ? AND auth = ? LIMIT 1");
    $stmt->bind_param("ss", $user_id, $auth);
    $stmt->execute();
    $result = $stmt->get_result();

    if($result && $result->num_rows === 1) {
        // ✅ Update Firebase token
        $stmt2 = $con->prepare("UPDATE users SET firebase_token = ? WHERE user_id = ?");
        $stmt2->bind_param("ss", $token, $user_id);

        if($stmt2->execute()) {
            $output = ['status' => true, 'success' => 'Firebase token updated successfully'];
        } else {
            $output = ['status' => false, 'success' => 'Failed to update Firebase token'];
        }

        $stmt2->close();
    } else {
        $output = ['status' => false, 'success' => 'Invalid credentials'];
    }

    $stmt->close();
    $con->close();
} else {
    $output = ['status' => false, 'success' => 'user_id, auth, and token required'];
}

echo json_encode($output);
?>
