<?php

require_once __DIR__ . '/../../src/Events/MonthEndEvent.php';

class SmallFloodEvent extends MonthEndEvent
{
    public function getMinAge()
    {
        return 0;
    }

    public function getMinParticipants()
    {
        return 0;
    }

    public function getMaxParticipants()
    {
        return 0;
    }

    public function getCost()
    {
        return 35;
    }

    public function isAvailable()
    {
        $season = $this->tribe->getCurrentSeason();
        return $season === 'spring' || $season === 'autumn';
    }

    private function setStorage(array $storage)
    {
        $ref = new ReflectionClass($this->tribe);
        if ($ref->hasProperty('storage')) {
            $prop = $ref->getProperty('storage');
            $prop->setValue($this->tribe, array_values($storage));
        }
    }

    public function execute()
    {
        if (!isset($this->tribe->dataStore)) {
            $this->tribe->dataStore = new stdClass();
        }
        $this->tribe->dataStore->floodedThisMonth = true;

        $storage = $this->tribe->getStorage() ?? [];
        $lostItems = [];
        if (!empty($storage)) {
            shuffle($storage);
            $count = rand(1, min(3, count($storage)));
            $lostItems = array_splice($storage, 0, $count);
            $this->setStorage($storage);
        }

        $currentFood = $this->tribe->getFoodCount();
        $foodLost = 0;
        if ($currentFood > 0) {
            $percent = rand(5, 20);
            $foodLost = (int) floor($currentFood * ($percent / 100));
            if ($foodLost > 0) {
                $this->tribe->removeFood($foodLost);
            }
        }

        $itemNames = [];
        foreach ($lostItems as $item) {
            if (is_array($item)) {
                $itemNames[] = $item['name'] ?? ($item['id'] ?? 'item');
            } elseif (is_object($item) && method_exists($item, 'getName')) {
                $itemNames[] = $item->getName();
            }
        }

        $itemsText = empty($itemNames) ? "No stored items were swept away." : "The flood carried off " . implode(', ', $itemNames) . ".";
        $foodText = $foodLost > 0 ? "Some food was lost, about {$this->tribe->foodTimeStr($foodLost)}." : "Food stores stayed mostly intact.";

        $variations = [
            "A small flood crept into the camp and left the ground slick and heavy. {$itemsText} {$foodText}",
            "Spring waters rose and lapped at the camp, leaving mud and scattered supplies behind. {$itemsText} {$foodText}",
            "A shallow flood swept through the tribe's stores before the waters receded. {$itemsText} {$foodText}"
        ];

        $this->story = $variations[array_rand($variations)];
    }
}
