<?php

namespace App\Models;

use App\Utils\Database;
use PDO;

/**
 * MarkdownFile - 笔记文件模型
 *
 * 数据库表: markdown_file
 * 主要字段:
 * - id (Long) - 笔记ID，自增主键
 * - grouping_id (Long) - 所属分组ID
 * - title (String) - 笔记标题
 * - file_name (String) - 文件名（带.md后缀）
 * - content (String) - Markdown内容
 * - created_at (DateTime) - 创建时间
 * - updated_at (DateTime) - 更新时间
 * - is_deleted (Integer) - 逻辑删除标志
 * - deleted_at (DateTime) - 删除时间
 * - deleted_by (Long) - 删除人ID
 * - is_private (Integer) - 是否私密（0-公开，1-私密）
 */
class MarkdownFile
{
    private $db;

    // 笔记属性
    public $id;
    public $groupingId;
    public $title;
    public $fileName;
    public $content;
    public $createdAt;
    public $updatedAt;
    public $isDeleted;
    public $deletedAt;
    public $deletedBy;
    public $isPrivate;

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

    public function findById($id, $includeDeleted = false)
    {
        $sql = "SELECT * FROM markdown_file WHERE id = ?";
        if (!$includeDeleted) {
            $sql .= " AND is_deleted = 0";
        }
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$id]);
        return $stmt->fetch();
    }

    public function getAll()
    {
        $stmt = $this->db->prepare("SELECT * FROM markdown_file WHERE is_deleted = 0 ORDER BY updated_at DESC");
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function getByGroupingId($groupingId)
    {
        $stmt = $this->db->prepare(
            "SELECT id, title, file_name, created_at, updated_at, is_private, grouping_id
             FROM markdown_file
             WHERE grouping_id = ? AND is_deleted = 0
             ORDER BY updated_at DESC"
        );
        $stmt->execute([$groupingId]);
        return $stmt->fetchAll();
    }

    public function searchByTitle($keyword)
    {
        $stmt = $this->db->prepare(
            "SELECT * FROM markdown_file
             WHERE title LIKE ? AND is_deleted = 0
             ORDER BY updated_at DESC"
        );
        $stmt->execute(['%' . $keyword . '%']);
        return $stmt->fetchAll();
    }

    public function getRecent($limit = 12)
    {
        $stmt = $this->db->prepare(
            "SELECT id, title, file_name, created_at, updated_at, is_private, grouping_id
             FROM markdown_file
             WHERE is_deleted = 0
             ORDER BY updated_at DESC
             LIMIT ?"
        );
        $stmt->execute([$limit]);
        return $stmt->fetchAll();
    }

    public function update($id, $data)
    {
        $fields = [];
        $values = [];

        if (isset($data['title'])) {
            $fields[] = "title = ?";
            $values[] = $data['title'];
        }
        if (isset($data['content'])) {
            $fields[] = "content = ?";
            $values[] = $data['content'];
        }
        if (isset($data['grouping_id'])) {
            $fields[] = "grouping_id = ?";
            $values[] = $data['grouping_id'];
        }
        if (isset($data['is_private'])) {
            $fields[] = "is_private = ?";
            $values[] = $data['is_private'];
        }

        $fields[] = "updated_at = NOW()";
        $values[] = $id;

        $sql = "UPDATE markdown_file SET " . implode(", ", $fields) . " WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute($values);
    }

    public function updateTitle($id, $title)
    {
        $stmt = $this->db->prepare(
            "UPDATE markdown_file SET title = ?, updated_at = NOW() WHERE id = ?"
        );
        return $stmt->execute([$title, $id]);
    }

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

    public function restore($id)
    {
        $stmt = $this->db->prepare(
            "UPDATE markdown_file SET is_deleted = 0, deleted_at = NULL, deleted_by = NULL WHERE id = ?"
        );
        return $stmt->execute([$id]);
    }

    public function permanentDelete($id)
    {
        $stmt = $this->db->prepare("DELETE FROM markdown_file WHERE id = ?");
        return $stmt->execute([$id]);
    }
}
