<?php

class LiveScorerService
{
    private Fixture $fixtureModel;
    private MatchEvent $eventModel;

    public function __construct(Fixture $fixtureModel, MatchEvent $eventModel)
    {
        $this->fixtureModel = $fixtureModel;
        $this->eventModel = $eventModel;
    }

    public function logEvent(array $data, stdClass $current_fixture): array
    {
        // Basic validation
        $playerless_events = ['corner', 'foul']; // Events that don't require a player
        if (empty($data['team_id']) || empty($data['event_type']) || (!in_array($data['event_type'], $playerless_events) && empty($data['player_id']))) {
            throw new InvalidArgumentException('Missing required event data (team_id, event_type, player_id).');
        }

        // Trust the minute sent from the client-side timer
        $data['minute'] = $data['minute'] ?? 0;

        // 1. Log the event
        $event_id = $this->eventModel->log($data);
        if (!$event_id) {
            throw new RuntimeException('Failed to log event.');
        }

        // 2. If it's a goal, update the score
        $score_data = null;
        $scoring_events = ['goal', 'penalty_scored', 'own_goal'];

        if (in_array($data['event_type'], $scoring_events)) {
            $team_to_credit = $data['team_id'];
            if ($data['event_type'] === 'own_goal') {
                // For an own goal, the *other* team gets the score
                $team_to_credit = ($data['team_id'] == $current_fixture->home_team_id) ? $current_fixture->away_team_id : $current_fixture->home_team_id;
            }

            if ($this->fixtureModel->incrementScore($data['fixture_id'], $team_to_credit)) {
                // Instead of re-fetching, calculate the new score
                $is_home_goal = ($team_to_credit == $current_fixture->home_team_id);
                $score_data = [
                    'home' => $current_fixture->home_team_score + ($is_home_goal ? 1 : 0),
                    'away' => $current_fixture->away_team_score + (!$is_home_goal ? 1 : 0)
                ];
            }
        }

        $logged_event = $this->eventModel->getEventById($event_id);

        return [
            'success' => true,
            'event' => $logged_event,
            'score' => $score_data
        ];
    }
}