<?php

require_once __DIR__ . '/../Classes/Kobold.php';

class SaveManager
{
    private $basePath;

    public function __construct()
    {
        $this->basePath = __DIR__ . '/../../data/saves';
        $this->ensureDirectories();
    }

    private function ensureDirectories()
    {
        if (!is_dir($this->basePath)) {
            mkdir($this->basePath, 0755, true);
        }
    }

    /**
     * Get user saves directory
     */
    public function getUserSavesPath($userId)
    {
        $path = $this->basePath . '/' . ($userId);
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }
        return $path;
    }

    /**
     * Get specific save directory
     */
    public function getSavePath($userId, $saveId)
    {
        $path = $this->getUserSavesPath($userId) . '/' . $saveId;
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }
        return $path;
    }

    /**
     * Get kobold sprites directory
     */
    public function getKoboldSpritePathBase($userId, $koboldId, $age)
    {
        $path = $this->basePath . '/' . ($userId) . '/kobolds/' . $koboldId . '/sprites/' . $age . '.png';

        if (!is_dir(dirname($path))) {
            mkdir(dirname($path), 0755, true);
        }
        return $path;
    }
    public function getKoboldSpritePath($userId, $koboldId, $age)
    {
        // Extract saveId from kobold ID (format: kob_{saveId}_{uniqid})
        $parts = explode('_', $koboldId, 3);
        $saveId = $parts[1] ?? null;

        // Load the kobold from the save
        $koboldsPath = $this->getSavePath($userId, $saveId) . '/kobolds.json';
        $kobold = null;

        if (file_exists($koboldsPath)) {
            $koboldsData = $this->loadJson($koboldsPath);
            if ($koboldsData) {
                // Find the kobold with matching ID
                foreach ($koboldsData as $koboldData) {
                    if ($koboldData['id'] === $koboldId) {
                        $kobold = Kobold::fromArray($koboldData, $userId, $saveId);
                        break;
                    }
                }
            }
        }

        $path = $kobold->getSpritePath($age);

        return $path;
    }

    /**
     * Save data to JSON file
     */
    public function saveJson($filePath, $data)
    {
        $dir = dirname($filePath);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        if ($json === false) {
            throw new \Exception('Failed to encode JSON: ' . json_last_error_msg());
        }

        $written = file_put_contents($filePath, $json);
        if ($written === false) {
            throw new \Exception("Failed to write file: {$filePath}");
        }

        return true;
    }

    /**
     * Load data from JSON file
     */
    public function loadJson($filePath)
    {
        if (!file_exists($filePath)) {
            return null;
        }

        $contents = file_get_contents($filePath);
        if ($contents === false) {
            throw new \Exception("Failed to read file: {$filePath}");
        }

        $data = json_decode($contents, true);
        if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
            throw new \Exception('Failed to decode JSON: ' . json_last_error_msg());
        }

        return $data;
    }

    /**
     * Delete a save and all its data
     */
    public function deleteSave($userId, $saveId)
    {
        $path = $this->getSavePath($userId, $saveId);
        return $this->deleteDirectory($path);
    }

    /**
     * Delete directory recursively
     */
    private function deleteDirectory($path)
    {
        if (!is_dir($path)) {
            return true;
        }

        $files = scandir($path);
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') {
                continue;
            }

            $filePath = $path . '/' . $file;
            if (is_dir($filePath)) {
                $this->deleteDirectory($filePath);
            } else {
                unlink($filePath);
            }
        }

        return rmdir($path);
    }

    /**
     * List all saves for a user
     */
    public function listUserSaves($userId)
    {
        $savesPath = $this->getUserSavesPath($userId);
        $saves = [];

        $dirs = scandir($savesPath);
        foreach ($dirs as $dir) {
            if ($dir === '.' || $dir === '..' || $dir === 'kobolds') {
                continue;
            }

            $saveDataPath = $savesPath . '/' . $dir . '/save.json';
            if (file_exists($saveDataPath)) {
                $data = $this->loadJson($saveDataPath);
                if ($data) {
                    $data['id'] = $dir;
                    $saves[] = $data;
                }
            }
        }

        // Sort by last_played descending
        usort($saves, function ($a, $b) {
            $timeA = strtotime($a['last_played'] ?? '2000-01-01');
            $timeB = strtotime($b['last_played'] ?? '2000-01-01');
            return $timeB - $timeA;
        });

        return $saves;
    }

    /**
     * Generate unique save ID
     */
    public function generateSaveId($userId)
    {
        $savesPath = $this->getUserSavesPath($userId);
        $id = 1;

        while (is_dir($savesPath . '/' . $id)) {
            $id++;
        }

        return $id;
    }
}
