<?php
namespace app\models;

use app\app;

class categories
{
    public static function init()
    {
        app::$db->exec("CREATE TABLE IF NOT EXISTS categories (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            parent_id INTEGER REFERENCES categories(id),
            label TEXT UNIQUE NOT NULL,
            value TEXT UNIQUE NOT NULL
        );");
    }

    public static function add($label, $value, $parent_id = null): string
    {
        $stmt = app::$db->prepare("INSERT INTO categories (label, value, parent_id) VALUES (:label, :value, :parent_id)");
        $stmt->bindParam(':label', $label);
        $stmt->bindParam(':value', $value);
        $stmt->bindParam(':parent_id', $parent_id);
        $stmt->execute();
        return app::$db->lastInsertId();
    }

    public static function updateById($id, $label, $value, $parent_id = null)
    {
        $stmt = app::$db->prepare("UPDATE categories SET label = :label, value = :value, parent_id = :parent_id WHERE id = :id");
        $stmt->bindParam(':id', $id, \PDO::PARAM_INT);
        $stmt->bindParam(':label', $label);
        $stmt->bindParam(':value', $value);
        $stmt->bindParam(':parent_id', $parent_id);
        return $stmt->execute();
    }

    public static function getById($id)
    {
        $stmt = app::$db->prepare("SELECT * FROM categories WHERE id = :id");
        $stmt->bindParam(':id', $id, \PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    public static function getTree(): array
    {
        $stmt       = app::$db->query("SELECT * FROM categories");
        $categories = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        $tree       = [];
        $map        = [];
        foreach ($categories as &$category) {
            $category['children'] = [];
            $map[$category['id']] = &$category;
        }
        foreach ($categories as &$category) {
            if (! $category['parent_id']) {
                $tree[] = &$category;
            } else {
                if (isset($map[$category['parent_id']])) {
                    $map[$category['parent_id']]['children'][] = &$category;
                }
            }
        }
        return $tree;
    }

    public static function getOptions(): array
    {
        $stmt       = app::$db->query("SELECT * FROM categories");
        $categories = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $flattened = [];
        foreach ($categories as $category) {
            $depth   = 0;
            $current = $category;
            while ($current['parent_id'] !== null) {
                $depth++;
                $current = array_filter($categories, function ($cat) use ($current) {
                    return $cat['id'] === $current['parent_id'];
                });
                $current = reset($current);
                if (! $current) {
                    break;
                }
            }
            $flattened[] = [
                'label' => str_repeat('-', $depth) . ' ' . $category['label'],
                'value' => $category['id'],
            ];
        }
        return $flattened;
    }

}
