<?php
require_once __DIR__ . '/../config/db.php';

class Unit
{
    public static function generateToken(): string
    {
        return bin2hex(random_bytes(32)); // 64-char secure token
    }

    public static function create(array $data): int
    {
        $sql = "INSERT INTO units 
                (building_id, unit_code, floor, status, qr_token, notes)
                VALUES (?, ?, ?, ?, ?, ?)";

        $stmt = db()->prepare($sql);
        $stmt->execute([
            $data['building_id'],
            $data['unit_code'],
            $data['floor'],
            $data['status'],
            $data['qr_token'],
            $data['notes']
        ]);

        return (int)db()->lastInsertId();
    }

    public static function findByToken(string $token): ?array
{
    $stmt = db()->prepare("
        SELECT u.*, b.name AS building_name
        FROM units u
        JOIN buildings b ON b.id = u.building_id
        WHERE u.qr_token = ?
        LIMIT 1
    ");
    $stmt->execute([$token]);
    $unit = $stmt->fetch();

    return $unit ?: null;
}

}
