<?php
/**
 * Register/Update Device Endpoint
 * POST /v1/auth/mobile/register-device
 * 
 * Updates push token and device info for an already-authenticated device.
 */

declare(strict_types=1);

use App\Core\Database;
use App\Middleware\AuthMiddleware;
use App\Core\Security;

$decoded = AuthMiddleware::check();
$userId = $decoded['user_id'];
$deviceId = $decoded['device_id'] ?? null;

if (!$deviceId) {
    json_error('هذا الـ endpoint مخصص لتطبيق الهاتف فقط', 403);
}

$data = Security::sanitize(input());

$db = Database::getInstance();

$updateFields = [];
$params = [];

if (isset($data['push_token'])) {
    $updateFields[] = 'push_token = ?';
    $params[] = $data['push_token'];
}

if (isset($data['app_version'])) {
    $updateFields[] = 'app_version = ?';
    $params[] = $data['app_version'];
}

if (isset($data['device_name'])) {
    $updateFields[] = 'device_name = ?';
    $params[] = $data['device_name'];
}

// Always update last_seen
$updateFields[] = 'last_seen_at = NOW()';

if (empty($updateFields)) {
    json_success(null, 'لا يوجد بيانات للتحديث');
    exit;
}

$sql = "UPDATE user_devices SET " . implode(', ', $updateFields) . " WHERE user_id = ? AND device_fingerprint = ?";
$params[] = $userId;
$params[] = $deviceId;

$stmt = $db->prepare($sql);
$stmt->execute($params);

json_success(null, 'تم تحديث بيانات الجهاز');
