<?php
namespace boru\boruai\UI;

use boru\boruai\BoruAI;

class Reference {
    private $reference;
    private $userId;
    private $userName;

    public function __construct($reference=null,$userId=null) {
        $this->reference = $reference;
        if($userId) {
            $this->userId = $userId;
        } else {
            $user = User::login();
            if(!$user) {
                throw new \Exception("User not logged in");
            }
            $this->userId = $user->id();
        }
    }


    private static $references = [];
    /**
     * 
     * @param bool $force 
     * @return array 
     * @throws Exception 
     */
    public static function forUser($user,$force=false,$limit=10) {
        $user = new User($user);
        $userId = $user->id() ? $user->id() : 0;
        if(isset(self::$references[$userId]) && !$force) {
            return self::$references[$userId];
        }
        $table = BoruAI::table("responses");
        $sql = "select distinct `reference` from ".$table." where `reference` != '' and `user`=? order by `id` desc";
        if($limit) {
            $sql .= " limit " . intval($limit);
        }
        $db = BoruAI::db();
        $result = $db->query($sql, [$userId]);
        static::$references[$userId] = [];
        while($row = $db->next($result)) {
            static::$references[$userId][] = $row["reference"];
        }
        return static::$references[$userId];
    }

    public static function listReferences($limit=10) {
        $table = BoruAI::table("responses");
        $sql = "select distinct `reference` from ".$table." where `reference` != '' order by `id` desc";
        if($limit) {
            $sql .= " limit " . intval($limit);
        }
        $db = BoruAI::db();
        $result = $db->query($sql, []);
        $references = [];
        while($row = $db->next($result)) {
            $references[] = $row["reference"];
        }
        return $references;
    }

}