<?php

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

class GameSessionRepository
{
    private $pdo;

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

    public function findActiveByUserId($userId, $forUpdate = false)
    {
        $sql =
            'SELECT *
             FROM game_sessions
             WHERE user_id = :user_id
               AND status IN ("opening", "active", "closing", "recovery")
             ORDER BY id DESC
             LIMIT 1';

        if ($forUpdate) {
            $sql .= ' FOR UPDATE';
        }

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(array('user_id' => (int) $userId));

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

        return $row ?: null;
    }

    public function create(array $data)
    {
        $stmt = $this->pdo->prepare(
            'INSERT INTO game_sessions (
                session_id,
                user_id,
                api_provider,
                provider_code,
                game_code,
                amount_sent,
                status,
                provider_reference,
                started_at,
                last_activity_at
            ) VALUES (
                :session_id,
                :user_id,
                :api_provider,
                :provider_code,
                :game_code,
                :amount_sent,
                :status,
                :provider_reference,
                NOW(),
                NOW()
            )'
        );

        return $stmt->execute(array(
            'session_id' => $data['session_id'],
            'user_id' => (int) $data['user_id'],
            'api_provider' => $data['api_provider'],
            'provider_code' => $data['provider_code'],
            'game_code' => $data['game_code'],
            'amount_sent' => number_format(
                (float) $data['amount_sent'],
                2,
                '.',
                ''
            ),
            'status' => $data['status'],
            'provider_reference' => isset($data['provider_reference'])
                ? $data['provider_reference']
                : null,
        ));
    }

    public function updateStatus(
        $sessionId,
        $status,
        $providerReference = null
    ) {
        $closedSql = $status === 'closed'
            ? ', closed_at = NOW()'
            : '';

        $stmt = $this->pdo->prepare(
            'UPDATE game_sessions
             SET
                status = :status,
                provider_reference = COALESCE(
                    :provider_reference,
                    provider_reference
                ),
                last_activity_at = NOW()
                ' . $closedSql . '
             WHERE session_id = :session_id'
        );

        return $stmt->execute(array(
            'status' => (string) $status,
            'provider_reference' => $providerReference,
            'session_id' => (string) $sessionId,
        ));
    }
}
