<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */



namespace Core\Lib;

class Model
{
    protected $db;
    protected $table;
    protected $primaryKey = 'id';
    protected $timestamps = true;
    
    public function __construct()
    {
        $this->db = \Core\Db\DB::getInstance();
    }
    
    /**
     * 获取所有记录
     */
    public function getAll($where = '1=1', $order = '', $fields = '*')
    {
        $sql = "SELECT {$fields} FROM {$this->db->table($this->table)} WHERE {$where}";
        if ($order) {
            $sql .= " ORDER BY {$order}";
        }
        return $this->db->fetchAll($sql);
    }
    
    /**
     * 获取单条记录
     */
    public function getOne($where, $fields = '*')
    {
        $sql = "SELECT {$fields} FROM {$this->db->table($this->table)} WHERE {$where} LIMIT 1";
        return $this->db->fetch($sql);
    }
    
    /**
     * 根据主键获取记录
     */
    public function find($id)
    {
        $sql = "SELECT * FROM {$this->db->table($this->table)} WHERE {$this->primaryKey} = ? LIMIT 1";
        return $this->db->fetch($sql, [$id]);
    }
    
    /**
     * 插入数据
     */
    public function add($data)
    {
        // 自动时间戳
        if ($this->timestamps && !isset($data['create_time'])) {
            $data['create_time'] = time();
        }
        
        return $this->db->insert($this->table, $data);
    }
    
    /**
     * 更新数据
     */
    public function update($data, $where)
    {
        // 自动更新时间戳
        if ($this->timestamps && !isset($data['update_time'])) {
            $data['update_time'] = time();
        }
        
        return $this->db->update($this->table, $data, $where);
    }
    
    /**
     * 删除数据
     */
    public function delete($where, $params = [])
    {
        return $this->db->delete($this->table, $where, $params);
    }
    
    /**
     * 根据主键删除
     */
    public function remove($id)
    {
        return $this->db->delete($this->db->table($this->table), "{$this->primaryKey} = ?", [$id]);
    }
    
    /**
     * 统计数量
     */
    public function count($where = '1=1')
    {
        $sql = "SELECT COUNT(*) as total FROM {$this->db->table($this->table)} WHERE {$where}";
        $result = $this->db->fetch($sql);
        return $result ? $result['total'] : 0;
    }
    
    /**
     * 分页查询
     */
    public function getList($where = '1=1', $order = 'id DESC', $page = 1, $pageSize = 20, $fields = '*')
    {
        $offset = ($page - 1) * $pageSize;
        
        $sql = "SELECT {$fields} FROM {$this->db->table($this->table)} WHERE {$where} ORDER BY {$order} LIMIT {$offset}, {$pageSize}";
        $list = $this->db->fetchAll($sql);
        
        $total = $this->count($where);
        
        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'page_size' => $pageSize,
            'total_pages' => ceil($total / $pageSize)
        ];
    }
    
    /**
     * 获取子级记录
     */
    public function getChildren($parentId, $order = 'sort_order ASC, id ASC')
    {
        $sql = "SELECT * FROM {$this->db->table($this->table)} WHERE parent_id = ? ORDER BY {$order}";
        return $this->db->fetchAll($sql, [$parentId]);
    }
    
    /**
     * 获取祖先链
     */
    public function getAncestors($id, $fields = '*')
    {
        $ancestors = [];
        $current = $this->find($id);
        
        while ($current && $current['parent_id'] > 0) {
            $ancestors[] = $current;
            $current = $this->find($current['parent_id']);
        }
        
        return array_reverse($ancestors);
    }
    
    /**
     * 检查是否存在
     */
    public function exists($where)
    {
        $sql = "SELECT 1 FROM {$this->db->table($this->table)} WHERE {$where} LIMIT 1";
        $result = $this->db->fetch($sql);
        return !empty($result);
    }
    
    /**
     * 执行原生SQL（危险，请谨慎使用）
     */
    public function query($sql, $params = [])
    {
        return $this->db->query($sql, $params);
    }
    
    /**
     * 获取表名
     */
    public function table()
    {
        return $this->db->table($this->table);
    }
}