<?php

defined('APP_BOOTSTRAPPED') or exit('No direct access.');

class UserRepository
{
    private $pdo;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function findById($userId)
    {
        $stmt = $this->pdo->prepare(
            'SELECT * FROM users WHERE id = :id LIMIT 1'
        );

        $stmt->execute(array('id' => (int) $userId));

        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        return $row ?: null;
    }

    public function getPlayerCode($userId, $apiProvider)
    {
        $apiProvider = strtolower(trim((string) $apiProvider));

        if ($apiProvider === 'sgx') {
            $column = 'player_code_sgx';
        } elseif ($apiProvider === 'nexus') {
            $column = 'player_code_nexus';
        } else {
            throw new InvalidArgumentException(
                'API provider tidak valid.'
            );
        }

        $stmt = $this->pdo->prepare(
            'SELECT ' . $column . ' AS player_code
             FROM users
             WHERE id = :id
             LIMIT 1'
        );

        $stmt->execute(array('id' => (int) $userId));

        $playerCode = $stmt->fetchColumn();

        return $playerCode !== false
            ? trim((string) $playerCode)
            : null;
    }

    public function savePlayerCode($userId, $apiProvider, $playerCode)
    {
        $apiProvider = strtolower(trim((string) $apiProvider));

        if ($apiProvider === 'sgx') {
            $column = 'player_code_sgx';
        } elseif ($apiProvider === 'nexus') {
            $column = 'player_code_nexus';
        } else {
            throw new InvalidArgumentException(
                'API provider tidak valid.'
            );
        }

        $stmt = $this->pdo->prepare(
            'UPDATE users
             SET ' . $column . ' = :player_code
             WHERE id = :id'
        );

        return $stmt->execute(array(
            'player_code' => (string) $playerCode,
            'id' => (int) $userId,
        ));
    }
}
