<?php

require_once __DIR__ . '/../../src/Events/Event.php';
require_once __DIR__ . '/../../src/Utilities/GameHelper.php';
require_once __DIR__ . '/../../src/Classes/Kobold.php';

class ExplorationEvent extends Event
{
    public function getMinAge()
    {
        return 14;
    }

    public function getMinParticipants()
    {
        return 1;
    }

    public function getMaxParticipants()
    {
        return 10;
    }

    public function getCost()
    {
        return 12;
    }

    public function isAvailable()
    {
        return true;
    }

    public function execute()
    {
        $this->story = "The exploration party ventured forth into uncharted territory...\n\n";

        $available = $this->tribe->getAliveKobolds();

        if (empty($available)) {
            $this->story .= "But there were no kobolds to send exploring!";
            return;
        }

        // Exploration must be started with explicit participants (player-started)
        $participantIds = $this->getParticipants();
        if (empty($participantIds) || !is_array($participantIds)) {
            throw new \Exception('ExplorationEvent requires a participants array of kobold IDs.');
        }

        $explorers = [];
        foreach ($participantIds as $pid) {
            $k = $this->tribe->getKobold($pid);
            if ($k && !$k->isDead())
                $explorers[] = $k;
        }

        if (empty($explorers)) {
            throw new \Exception('No valid living kobolds found in participants list.');
        }

        $this->story .= count($explorers) > 1 ?
            "A group of " . count($explorers) . " intrepid explorers set out:\n"
            : $explorers[0]->getName() . " sets out to explore.\n";

        if (count($explorers) > 1) {
            foreach ($explorers as $explorer) {
                $this->story .= "- " . $explorer->getName() . "\n";
            }
            $this->story .= "\n";
        }

        // Chance to find food (50% base)
        $foodFound = rand(1, 100) <= 50;
        if ($foodFound) {
            $baseFood = rand(5, 15);
            // Intelligence affects food discovery - smarter kobolds find more
            $avgIntelligence = array_sum(array_map(function ($k) {
                return $k->getStat('intelligence');
            }, $explorers)) / count($explorers);

            $foodBonus = intval($avgIntelligence / 20); // Max +5 food from intelligence
            $totalFood = $baseFood + $foodBonus;

            $this->tribe->addFood($totalFood);
            $this->story .= "Success! The explorers discovered edible plants and small game.\n";
            $this->story .= "The tribe gained " . $totalFood . " units of food.\n\n";
        } else {
            $this->story .= "The terrain was barren. No food was found.\n\n";
        }

        $injuryChance = rand(1, 100) <= 20;
        if ($injuryChance && count($explorers) > 0) {

            // Select a random explorer to get injured
            $injuredKobold = $explorers[array_rand($explorers)];

            $this->story .= "Disaster! " . $injuredKobold->getName() . " tripped over a loose stone!\n";

            $injuredKobold->addInjury("brokenLeg");

            $this->story .= $injuredKobold->getName() . " broke a leg!\n";
        }

        $stickFound = rand(1, 100) <= 20;
        if ($stickFound) {
            $bestKobold = GameHelper::findBestKoboldForStat($explorers, "crafting");

            $success = $bestKobold->checkStat("crafting");

            if ($success) {
                $boneItem = GameHelper::loadItem('bone-setting');
                if ($boneItem) {
                    $this->tribe->addToStorage($boneItem);
                    $this->story .= "{$bestKobold->getName()} finds a nice stick and fashions it into a Splint the tribe can use to treat fractures.\n";
                }
            } else {
                $this->story .= "{$bestKobold->getName()} finds a stick suitable to be a splint, but it breaks as {$bestKobold->he()} tries to craft it.\n";
            }
        }

        $eggFound = rand(1, 100) <= 3;
        if ($eggFound) {
            $this->tribe->addKobold(Kobold::generate($this->tribe->getUserId(), $this->tribe->getSaveId(), rand(-6, -1)));
            $this->story .= "The party finds a lost Kobold egg... What might be inside?\n";
        }

        $this->story .= "\nThe exploration party returned to the tribe with their findings.";

        return $this->story;
    }
}
