<?php
/**
 * Register FCM Token API
 */


require_once 'bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$fcm_token = $input['fcm_token'] ?? null;
$user_type = $input['user_type'] ?? 'customer'; // 'customer' or 'admin'

if (!$fcm_token) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'FCM token required']);
    exit;
}

// Determine recipient ID from session
$recipient_id = null;
if ($user_type === 'admin') {
    $recipient_id = $_SESSION['admin_id'] ?? null;
} else {
    $recipient_id = $_SESSION['user_id'] ?? null;
}

if (!$recipient_id) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

try {
    $pdo = getDBConnection();

    if ($user_type === 'admin') {
        $stmt = $pdo->prepare("UPDATE admin_users SET fcm_token = ? WHERE id = ?");
    } else {
        $stmt = $pdo->prepare("UPDATE users SET fcm_token = ? WHERE id = ?");
    }

    $stmt->execute([$fcm_token, $recipient_id]);

    echo json_encode(['success' => true, 'message' => 'FCM token registered successfully']);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Database error', 'message' => $e->getMessage()]);
}
