<?php

namespace App\Models;

use App\Utils\Database;

/**
 * Trash - 回收站模型
 * 用于管理已删除的笔记和分组
 */
class Trash
{
    private $db;

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

    /**
     * 获取回收站列表
     */
    public function getTrashItems()
    {
        $items = [];

        // 获取已删除的 Markdown 文件
        $stmt = $this->db->prepare("
            SELECT
                id,
                title,
                'markdown' as type,
                deleted_at,
                deleted_by
            FROM markdown_file
            WHERE is_deleted = 1
            ORDER BY deleted_at DESC
        ");
        $stmt->execute();
        $markdownItems = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        // 获取已删除的分组
        $stmt = $this->db->prepare("
            SELECT
                id,
                `grouping` as title,
                'grouping' as type,
                deleted_at,
                deleted_by
            FROM `grouping`
            WHERE is_deleted = 1
            ORDER BY deleted_at DESC
        ");
        $stmt->execute();
        $groupingItems = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        // 合并并按删除时间排序
        $items = array_merge($markdownItems, $groupingItems);
        usort($items, function($a, $b) {
            return strtotime($b['deleted_at']) - strtotime($a['deleted_at']);
        });

        return $items;
    }

    /**
     * 恢复项目
     */
    public function restoreItem($id, $type)
    {
        if ($type === 'markdown') {
            $stmt = $this->db->prepare("
                UPDATE markdown_file
                SET is_deleted = 0, deleted_at = NULL, deleted_by = NULL
                WHERE id = ?
            ");
        } elseif ($type === 'grouping') {
            $stmt = $this->db->prepare("
                UPDATE `grouping`
                SET is_deleted = 0, deleted_at = NULL, deleted_by = NULL
                WHERE id = ?
            ");
        } else {
            throw new \Exception('不支持的类型');
        }

        return $stmt->execute([$id]);
    }

    /**
     * 永久删除项目
     */
    public function permanentlyDeleteItem($id, $type)
    {
        if ($type === 'markdown') {
            $stmt = $this->db->prepare("DELETE FROM markdown_file WHERE id = ?");
        } elseif ($type === 'grouping') {
            $stmt = $this->db->prepare("DELETE FROM `grouping` WHERE id = ?");
        } else {
            throw new \Exception('不支持的类型');
        }

        return $stmt->execute([$id]);
    }

    /**
     * 清空回收站
     */
    public function cleanTrash()
    {
        // 删除所有已标记删除的 Markdown 文件
        $stmt = $this->db->prepare("DELETE FROM markdown_file WHERE is_deleted = 1");
        $stmt->execute();

        // 删除所有已标记删除的分组
        $stmt = $this->db->prepare("DELETE FROM `grouping` WHERE is_deleted = 1");
        $stmt->execute();

        return true;
    }
}
