<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

header('Content-Type: application/json');

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

try {
    $user_id = Auth::check();
    $data = json_decode(file_get_contents("php://input"));
    
    if (!isset($data->token)) {
        throw new Exception("Missing token");
    }

    $token = $data->token;
    $platform = isset($data->platform) ? $data->platform : 'android';

    // Update or Insert
    // Delete old token if exists to prevent duplicates for same device on different account?
    // For now simple UPSERT logic (MySQL style)
    
    $stmt = $pdo->prepare("SELECT id FROM push_devices WHERE token = ?");
    $stmt->execute([$token]);
    $exists = $stmt->fetch();

    if ($exists) {
        $stmt = $pdo->prepare("UPDATE push_devices SET user_id = ?, last_active = NOW() WHERE token = ?");
        $stmt->execute([$user_id, $token]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO push_devices (user_id, token, platform) VALUES (?, ?, ?)");
        $stmt->execute([$user_id, $token, $platform]);
    }
    
    echo json_encode(['status' => 'success', 'message' => 'Device registered']);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
