<?php

namespace App\Models;

use App\Utils\Database;
use PDO;

/**
 * RegistrationCode - 注册码模型
 *
 * 数据库表: registration_codes
 * 主要字段:
 * - id (Long) - 主键ID，自增
 * - code (String) - 注册码
 * - expiry_time (DateTime) - 过期时间
 * - created_by (String) - 创建者
 * - created_at (DateTime) - 创建时间
 */
class RegistrationCode
{
    private $db;

    // 注册码属性
    public $id;
    public $code;
    public $expiryTime;
    public $createdBy;
    public $createdAt;

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

    public function generateCode($createdBy)
    {
        $code = bin2hex(random_bytes(16));
        $expiryTime = date('Y-m-d H:i:s', strtotime('+7 days'));

        $stmt = $this->db->prepare(
            "INSERT INTO registration_codes (code, expiry_time, created_by, created_at) VALUES (?, ?, ?, NOW())"
        );
        $stmt->execute([$code, $expiryTime, $createdBy]);

        return $code;
    }

    public function generateCodeWithId($createdBy)
    {
        $code = bin2hex(random_bytes(16));
        $expiryTime = date('Y-m-d H:i:s', strtotime('+7 days'));

        $stmt = $this->db->prepare(
            "INSERT INTO registration_codes (code, expiry_time, created_by, created_at) VALUES (?, ?, ?, NOW())"
        );
        $stmt->execute([$code, $expiryTime, $createdBy]);

        // 返回包含 id 的完整记录
        return $this->getCodeByCode($code);
    }

    public function getCodeByCode($code)
    {
        $stmt = $this->db->prepare(
            "SELECT id, code, expiry_time, created_by, created_at FROM registration_codes WHERE code = ?"
        );
        $stmt->execute([$code]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function getCodeById($id)
    {
        $stmt = $this->db->prepare(
            "SELECT id, code, expiry_time, created_by, created_at FROM registration_codes WHERE id = ?"
        );
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function validateCode($code)
    {
        $stmt = $this->db->prepare(
            "SELECT * FROM registration_codes WHERE code = ? AND expiry_time > NOW()"
        );
        $stmt->execute([$code]);
        return $stmt->fetch() !== false;
    }

    public function validateCodeWithDetails($code)
    {
        $stmt = $this->db->prepare(
            "SELECT id, code, expiry_time, created_by, created_at FROM registration_codes WHERE code = ? AND expiry_time > NOW()"
        );
        $stmt->execute([$code]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
}
