<?php

require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../src/Database/Database.php';
require_once __DIR__ . '/../../src/Classes/User.php';
require_once __DIR__ . '/../../src/Classes/Tribe.php';
require_once __DIR__ . '/../../src/Classes/Kobold.php';
require_once __DIR__ . '/../../src/System/SaveManager.php';

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    if (strpos($apiPath, 'generation') !== false) {
        // Generate initial kobolds for new game
        try {
            $userId = $input['userId'] ?? null;
            if (!$userId) {
                throw new \Exception('User ID required');
            }

            $tribe = Tribe::create($userId, $input['saveName']);

            // Generate 20 random kobolds
            $kobolds = [];
            for ($i = 0; $i < 10; $i++) {
                $kobold = Kobold::generate($userId, $tribe->getSaveId());
                $kobold->setName('Kobold ' . ($i + 1));
                $tribe->addKobold($kobold);

                $kobolds[] = [
                    'id' => $kobold->getId(),
                    'name' => $kobold->getName(),
                    'age' => $kobold->getAge(),
                    'stats' => [
                        'vitality' => $kobold->getStat('vitality'),
                        'intelligence' => $kobold->getStat('intelligence'),
                        'tinkering' => $kobold->getStat('tinkering'),
                        'medicine' => $kobold->getStat('medicine'),
                        'crafting' => $kobold->getStat('crafting'),
                        'personality' => $kobold->getStat('personality'),
                        'will' => $kobold->getStat('will')
                    ]
                ];
            }

            $tribe->save();

            echo json_encode([
                'success' => true,
                'save' => [
                    'id' => $tribe->getSaveId(),
                    'name' => $input['saveName']
                ],
                'kobolds' => $kobolds
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'save') !== false && strpos($apiPath, 'endMonth') === false) {
        // Save tribe setup
        try {
            $userId = $input['userId'] ?? null;
            $saveId = $input['saveId'] ?? null;

            if (!$userId || !$saveId) {
                throw new \Exception('User ID and Save ID required');
            }

            $tribe = Tribe::load($userId, $saveId);

            // TODO: Process leader and members selection
            // For now just save
            $tribe->save();

            echo json_encode([
                'success' => true,
                'tribe' => []
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'event') !== false) {
        // Execute an event
        try {
            $userId = $input['userId'] ?? null;
            $saveId = $input['saveId'] ?? null;

            if (!$userId || !$saveId) {
                throw new \Exception('User ID and Save ID required');
            }

            $tribe = Tribe::load($userId, $saveId);

            // TODO: Execute event and get story
            $story = "An event occurred in the tribe...";

            echo json_encode([
                'success' => true,
                'story' => $story
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'endMonth') !== false) {
        // End the current month
        try {
            $userId = $input['userId'] ?? null;
            $saveId = $input['saveId'] ?? null;

            if (!$userId || !$saveId) {
                throw new \Exception('User ID and Save ID required');
            }

            $tribe = Tribe::load($userId, $saveId);
            $foodStory = $tribe->endMonth();

            echo json_encode([
                'success' => true,
                'save' => [
                    'id' => $tribe->getSaveId(),
                    'current_month' => $tribe->getCurrentMonth(),
                    'current_season' => $tribe->getCurrentSeason(),
                    'food_count' => $tribe->getFoodCount()
                ],
                'monthStory' => $foodStory
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    }
} elseif ($method === 'GET') {
    $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    if (strpos($apiPath, 'sprite') !== false) {
        // Serve a kobold sprite image
        try {
            $userId = $_GET['userId'] ?? null;
            $koboldId = $_GET['koboldId'] ?? null;

            if (!$userId || !$koboldId) {
                throw new \Exception('User ID and Kobold ID required');
            }

            $saveManager = new SaveManager();
            $spritePath = $saveManager->getKoboldSpritePath($userId, $koboldId);
            $ageSprite = $_GET['age'] ?? 'adult';
            $spriteFile = $spritePath . '/' . $ageSprite . '.png';

            if (!file_exists($spriteFile)) {
                throw new \Exception('Sprite not found');
            }

            // Serve the sprite image
            header('Content-Type: image/png');
            header('Cache-Control: public, max-age=3600');
            readfile($spriteFile);
            exit;
        } catch (\Exception $e) {
            http_response_code(404);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'list') !== false) {
        // List saves for user
        try {
            $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;

            if (!$userId) {
                throw new \Exception('Not authenticated');
            }

            $user = new User($userId, '');
            $saves = $user->getSaves();

            echo json_encode([
                'success' => true,
                'saves' => $saves
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'load') !== false) {
        // Load a specific game save
        try {
            $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
            $saveId = $_GET['saveId'] ?? null;

            if (!$userId || !$saveId) {
                throw new \Exception('User ID and Save ID required');
            }

            $tribe = Tribe::load($userId, $saveId);

            // Get kobolds
            $kobolds = [];
            foreach ($tribe->getKobolds() as $kobold) {
                $kobolds[] = [
                    'id' => $kobold->getId(),
                    'name' => $kobold->getName(),
                    'age' => $kobold->getAge(),
                    'ageCategory' => $kobold->getAgeCategory()
                ];
            }

            echo json_encode([
                'success' => true,
                'save' => [
                    'id' => $tribe->getSaveId(),
                    'name' => $tribe->getName(),
                    'current_month' => $tribe->getCurrentMonth(),
                    'current_season' => $tribe->getCurrentSeason(),
                    'food_count' => $tribe->getFoodCount(),
                    'created_at' => $tribe->getCreatedAt(),
                    'last_played' => $tribe->getLastPlayed()
                ],
                'tribe' => [
                    'kobolds' => $kobolds
                ]
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    }
}

