<?php
namespace App\Services;

class HistoryService
{
    protected $path;
    protected $pdo;

    public function __construct()
    {
        $this->path = __DIR__ . '/../../data';
        if (!is_dir($this->path)) {
            mkdir($this->path, 0755, true);
        }
        $dbFile = $this->path . '/history.sqlite';
        $this->pdo = new \PDO('sqlite:' . $dbFile);
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->init();
    }

    protected function init()
    {
        $this->pdo->exec("CREATE TABLE IF NOT EXISTS generations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            created_at TEXT,
            school_name TEXT,
            class_level TEXT,
            subject TEXT,
            metadata TEXT,
            content TEXT
        )");
    }

    public function save(array $meta, string $content)
    {
        $stmt = $this->pdo->prepare('INSERT INTO generations (created_at, school_name, class_level, subject, metadata, content) VALUES (:created_at, :school_name, :class_level, :subject, :metadata, :content)');
        $stmt->execute([
            ':created_at' => date('c'),
            ':school_name' => $meta['school_name'] ?? null,
            ':class_level' => $meta['class_level'] ?? null,
            ':subject' => $meta['subject'] ?? null,
            ':metadata' => json_encode($meta),
            ':content' => $content
        ]);
        return (int)$this->pdo->lastInsertId();
    }
}
