<?php

class LiveScorerService {
    private $fixtureModel;
    private $eventModel;
    private $fineModel;
    private $suspensionModel;
    private $settingModel;
    private $db;

    public function __construct($fixtureModel, $eventModel, $fineModel, $suspensionModel, $settingModel) {
        $this->fixtureModel = $fixtureModel;
        $this->eventModel = $eventModel;
        $this->fineModel = $fineModel;
        $this->suspensionModel = $suspensionModel;
        $this->settingModel = $settingModel;
        $this->db = new Database();
    }

    public function startMatch($fixture_id) {
        $this->db->query("UPDATE fixtures SET status = 'live', first_half_start_time = NOW() WHERE id = :id");
        $this->db->bind(':id', $fixture_id);
        return $this->db->execute();
    }

    public function endFirstHalf($fixture_id) {
        $this->db->query("UPDATE fixtures SET status = 'half_time', first_half_end_time = NOW() WHERE id = :id");
        $this->db->bind(':id', $fixture_id);
        return $this->db->execute();
    }

    public function startSecondHalf($fixture_id) {
        $this->db->query("UPDATE fixtures SET status = 'live', second_half_start_time = NOW() WHERE id = :id");
        $this->db->bind(':id', $fixture_id);
        return $this->db->execute();
    }

    public function endSecondHalf($fixture_id) {
        $this->db->query("UPDATE fixtures SET status = 'full_time', second_half_end_time = NOW() WHERE id = :id");
        $this->db->bind(':id', $fixture_id);
        return $this->db->execute();
    }

    public function endMatch($fixture_id, $motm_player_id = null) {
        $sql = "UPDATE fixtures SET status = 'finished'";
        if ($motm_player_id) {
            $sql .= ", man_of_the_match_player_id = :motm";
        }
        $sql .= " WHERE id = :id";
        
        $this->db->query($sql);
        $this->db->bind(':id', $fixture_id);
        if ($motm_player_id) {
            $this->db->bind(':motm', $motm_player_id);
        }
        return $this->db->execute();
    }

    public function logEvent($data, $fixture) {
        // Log event
        $eventId = $this->eventModel->log($data);
        if (!$eventId) {
            return ['success' => false, 'message' => 'Failed to save event.'];
        }

        // Update Score
        if ($data['event_type'] === 'goal' || $data['event_type'] === 'penalty_scored') {
            $this->updateScore($fixture->id, $data['team_id'], 1, $fixture);
        } elseif ($data['event_type'] === 'own_goal') {
            $opponentId = ($data['team_id'] == $fixture->home_team_id) ? $fixture->away_team_id : $fixture->home_team_id;
            $this->updateScore($fixture->id, $opponentId, 1, $fixture);
        }

        // Handle Red Card Suspension logic
        if ($data['event_type'] === 'red_card' && !empty($data['player_id'])) {
            if (method_exists($this->suspensionModel, 'create')) {
                $settings = $this->settingModel->getAll();
                $matches = $settings['suspension_red_card'] ?? 1;
                $this->suspensionModel->create([
                    'player_id' => $data['player_id'],
                    'team_id' => $data['team_id'],
                    'reason' => 'Red Card in match vs ' . ($data['team_id'] == $fixture->home_team_id ? $fixture->away_team_name : $fixture->home_team_name),
                    'matches_to_serve' => $matches
                ]);
            }
        }

        // Check for 2nd Yellow Card (Automatic Red)
        if ($data['event_type'] === 'yellow_card' && !empty($data['player_id'])) {
            $this->checkForSecondYellow($data, $fixture);
        }

        return ['success' => true];
    }

    public function undoLastEvent($fixture_id, $fixture) {
        $lastEvent = $this->eventModel->getLatestEventForFixture($fixture_id);
        if (!$lastEvent) {
            return ['success' => false, 'message' => 'No events to undo.'];
        }

        // Revert Score
        if ($lastEvent->event_type === 'goal' || $lastEvent->event_type === 'penalty_scored') {
            $this->updateScore($fixture_id, $lastEvent->team_id, -1, $fixture);
        } elseif ($lastEvent->event_type === 'own_goal') {
            $opponentId = ($lastEvent->team_id == $fixture->home_team_id) ? $fixture->away_team_id : $fixture->home_team_id;
            $this->updateScore($fixture_id, $opponentId, -1, $fixture);
        }

        // Delete event
        if ($this->eventModel->deleteById($lastEvent->id)) {
            return ['success' => true];
        }
        return ['success' => false, 'message' => 'Failed to delete event.'];
    }

    private function updateScore($fixture_id, $team_id, $increment, $fixture) {
        if ($team_id == $fixture->home_team_id) {
            $this->db->query("UPDATE fixtures SET home_team_score = home_team_score + :inc WHERE id = :id");
        } else {
            $this->db->query("UPDATE fixtures SET away_team_score = away_team_score + :inc WHERE id = :id");
        }
        $this->db->bind(':inc', $increment);
        $this->db->bind(':id', $fixture_id);
        $this->db->execute();
    }

    private function checkForSecondYellow($data, $fixture) {
        $this->db->query("SELECT COUNT(*) as count FROM match_events WHERE fixture_id = :fid AND player_id = :pid AND event_type = 'yellow_card'");
        $this->db->bind(':fid', $data['fixture_id']);
        $this->db->bind(':pid', $data['player_id']);
        $res = $this->db->single();

        if ($res && $res->count == 2) {
            // Issue Red Card
            $redCardData = [
                'fixture_id' => $data['fixture_id'],
                'team_id' => $data['team_id'],
                'player_id' => $data['player_id'],
                'event_type' => 'red_card',
                'minute' => $data['minute'],
                'assisted_by_player_id' => null
            ];
            
            // Log the red card (this will recursively trigger suspension logic in logEvent)
            $this->logEvent($redCardData, $fixture);

            // Issue Fine for Automatic Red Card (since live_scorer_process.php only handles fines for the primary event)
            $settings = $this->settingModel->getAll();
            $fine_amount = (float)($settings['fine_red_card'] ?? 0);
            
            if ($fine_amount > 0) {
                $opponent_name = ($data['team_id'] == $fixture->home_team_id ? $fixture->away_team_name : $fixture->home_team_name);
                $this->fineModel->create([
                    'entity_type' => 'player',
                    'entity_id' => $data['player_id'],
                    'reason' => 'Red Card (2nd Yellow) in match vs ' . $opponent_name,
                    'amount' => $fine_amount
                ]);
            }
        }
    }
}