<?php

namespace App\Models;

use App\Utils\Database;
use PDO;

/**
 * Grouping - 分组模型
 *
 * 数据库表: grouping
 * 主要字段:
 * - id (Long) - 分组ID，雪花算法生成
 * - parentId (Long) - 上级分组ID（支持分组嵌套）
 * - grouping (String) - 分组名称
 * - is_deleted (Integer) - 逻辑删除标志（0-未删除，1-已删除）
 * - deleted_at (DateTime) - 删除时间
 * - deleted_by (Long) - 删除人ID
 */
class Grouping
{
    private $db;

    // 分组属性
    public $id;
    public $parentId;
    public $grouping;
    public $isDeleted;
    public $deletedAt;
    public $deletedBy;

    public function __construct()
    {
        $this->db = Database::getInstance()->getConnection();
    }

    public function getAll($parentId = null)
    {
        if ($parentId === null) {
            $stmt = $this->db->prepare("SELECT * FROM `grouping` WHERE is_deleted = 0 ORDER BY id");
        } else {
            $stmt = $this->db->prepare("SELECT * FROM `grouping` WHERE parentId = ? AND is_deleted = 0 ORDER BY id");
            $stmt->execute([$parentId]);
            return $stmt->fetchAll();
        }
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function findById($id)
    {
        $stmt = $this->db->prepare("SELECT * FROM `grouping` WHERE id = ? AND is_deleted = 0");
        $stmt->execute([$id]);
        return $stmt->fetch();
    }

    public function create($grouping, $parentId = 0)
    {
        $stmt = $this->db->prepare("INSERT INTO `grouping` (`grouping`, parentId) VALUES (?, ?)");
        $stmt->execute([$grouping, $parentId]);
        return $this->db->lastInsertId();
    }

    public function update($id, $grouping)
    {
        $stmt = $this->db->prepare("UPDATE `grouping` SET `grouping` = ? WHERE id = ?");
        return $stmt->execute([$grouping, $id]);
    }

    public function delete($id)
    {
        $stmt = $this->db->prepare(
            "UPDATE `grouping` SET is_deleted = 1, deleted_at = NOW() WHERE id = ?"
        );
        return $stmt->execute([$id]);
    }

    public function softDelete($id, $userId)
    {
        $stmt = $this->db->prepare(
            "UPDATE `grouping` SET is_deleted = 1, deleted_at = NOW(), deleted_by = ? WHERE id = ?"
        );
        return $stmt->execute([$userId, $id]);
    }
}
