<?php
/**
 * FCM Token Registration Endpoint
 * Called by Android app when FCM token is generated/refreshed
 */
ob_clean();

header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once __DIR__ . '/../includes/db.php';

$data = json_decode(file_get_contents("php://input"), true);

$device_id = $data['device_id'] ?? '';
$fcm_token = $data['fcm_token'] ?? '';

if (empty($device_id)) {
    echo json_encode(['success' => false, 'message' => 'Missing device_id']);
    exit;
}

if (empty($fcm_token)) {
    echo json_encode(['success' => false, 'message' => 'Missing fcm_token']);
    exit;
}

try {
    // Update FCM token for existing device, or insert new record
    $stmt = $pdo->prepare("
        INSERT INTO devices (device_id, fcm_token, last_seen)
        VALUES (?, ?, NOW())
        ON DUPLICATE KEY UPDATE
            fcm_token = VALUES(fcm_token),
            last_seen = NOW()
    ");

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

    echo json_encode([
        'success' => true,
        'message' => 'FCM token registered',
        'device_id' => $device_id
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
