<?php

namespace App\Models;

use App\Utils\Database;
use PDO;

/**
 * User - 用户模型
 *
 * 数据库表: user
 * 主要字段:
 * - id (Long) - 用户ID，自增主键
 * - username (String) - 用户名
 * - password (String) - 密码（加密存储）
 * - email (String) - 邮箱
 * - created_at (DateTime) - 创建时间
 * - updated_at (DateTime) - 更新时间
 * - token (String) - 用户token
 * - token_enddata (DateTime) - token过期时间
 */
class User
{
    private $db;

    // 用户属性
    public $id;
    public $username;
    public $password;
    public $email;
    public $createdAt;
    public $updatedAt;
    public $token;
    public $tokenEnddata;

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

    public function findByUsername($username)
    {
        $stmt = $this->db->prepare("SELECT * FROM user WHERE username = ?");
        $stmt->execute([$username]);
        return $stmt->fetch();
    }

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

    public function create($username, $password, $email)
    {
        $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
        $stmt = $this->db->prepare(
            "INSERT INTO user (username, password, email, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())"
        );
        $stmt->execute([$username, $hashedPassword, $email]);
        return $this->db->lastInsertId();
    }

    public function updateToken($userId, $token, $expireTime)
    {
        $stmt = $this->db->prepare("UPDATE user SET token = ?, token_enddata = ? WHERE id = ?");
        return $stmt->execute([$token, $expireTime, $userId]);
    }

    public function updatePassword($userId, $newPassword)
    {
        $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
        $stmt = $this->db->prepare("UPDATE user SET password = ?, updated_at = NOW() WHERE id = ?");
        return $stmt->execute([$hashedPassword, $userId]);
    }

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

    public function verifyPassword($password, $hashedPassword)
    {
        return password_verify($password, $hashedPassword);
    }
}
