<?php

    require_once($path["entity"] . "Entity.php");
    require_once($path["entity"] . "Guild_Member.php");


    /**
     * Guild.
     *
     * Represents an object from the table 'guild'.
     */
    class Guild extends Entity{

        /**
         * Guild identifier.
         */
        public $id;

        /**
         * Guild name.
         */
        public $name;

        /**
         * Guild level.
         */
        public $level;

        /**
         * Guild total experience.
         */
        public $experience;

        /**
         * Indicates if the guild is ecruiting.
         */
        public $recruiting;

        /**
         * Number of members.
         */
        public $total_members;

        /**
         * Leader {@see Guild_Member}.
         */
        public $leader;

        /**
         * Guild comment.
         */
        public $comment;

        /**
         * Guild notice.
         */
        public $notice;

        /**
         * List of {@see Guild_Member}s.
         */
        public $members = [];

        /**
         * Constructor.
         *
         * Searches the database and retrieves the information about the
         * guild, populating it and it's items.
         *
         * @param SQLite3 $db Connection to the database.
         * @param int $id Guild identifier.
         */
        public function __construct($db, $id){
            global $path;
            parent::__construct($db);
            $s =
              "SELECT " .
              "  id, " .
              "  name, " .
              "  name, " .
              "  level, " .
              "  experience, " .
              "  recruiting, " .
              "  members, " .
              "  leader, " .
              "  comment, " .
              "  notice " .
              "FROM guild " .
              "WHERE id = $id; ";
            $q = $this->db->query($s);
            $r = $q->fetchArray(SQLITE3_ASSOC);
            if ($r){
                $this->id = $r["id"];
                $this->name = $r["name"];
                $this->level = $r["level"];
                $this->experience = $r["experience"];
                $this->recruiting = $r["recruiting"];
                $this->total_members = $r["members"];
                $this->leader = $r["leader"];
                $this->comment = $r["comment"];
                $this->notice = $r["notice"];
            }
            $s =
              "SELECT id " .
              "FROM guild_member " .
              "WHERE guild = $this->id " .
              "ORDER BY " .
              "  grade = 1 DESC, " .
              "  grade = 3 DESC, " .
              "  grade = 2 DESC, " .
              "  arena_score DESC; ";
            $q = $this->db->query($s);
            while ($r = $q->fetchArray(SQLITE3_ASSOC)){
                array_push($this->members, new Guild_Member($db, $r["id"]));
            }
        }


    }
?>
