<?php

class UserController {

    // ─── GET /api/user/status ─────────────────────────────────────────────────
    public static function checkStatus(): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $db     = getDb();

        // Ensure status is current before checking
        require_once __DIR__ . '/../services/RentalService.php';
        RentalService::updateStatuses($db, $userId);

        $stmt = $db->prepare("SELECT status FROM users WHERE id = ? LIMIT 1");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$row) sendError('User not found', 404);

        sendSuccess([
            'status' => $row['status'] ?? 'active'
        ]);
    }
    // ─── POST /api/user/fcm-token ─────────────────────────────────────────────
    public static function updateFcmToken(): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $body   = getJsonBody();
        $token  = trim($body['fcm_token'] ?? '');

        // DEBUG LOGGING
        file_put_contents(__DIR__ . '/../debug_fcm.txt', "User: $userId | Token: $token | Body: " . json_encode($body) . "\n", FILE_APPEND);

        if (!$token) {
            sendError('FCM Token is required', 400);
        }

        $db   = getDb();
        $stmt = $db->prepare("UPDATE users SET fcm_token = ? WHERE id = ?");
        $stmt->bind_param('si', $token, $userId);
        
        if ($stmt->execute()) {
            sendSuccess(null, 'FCM token updated successfully');
        } else {
            sendError('Failed to update FCM token', 500);
        }
        $stmt->close();
    }
}
?>
