 <?php

    require_once($path["page"] . "Page.php");
    require_once($path["entity"] . "Team.php");

    /**
     * Monster list page.
     */
    class Teams_Page extends Page{

        /**
         * Array of @{see Team}s.
         */
        public $teams = [];

        /**
         * The filters the page can handle.
         */
        public $filters;

        /**
         * List of all units for team creation
         */
        public $units = [];


        /**
         * Constructor.
         *
         * Retrieves the data and initializes the variables.
         *
         * @param SQLite3 $db Connection to the database.
         */
        public function __construct($db){
            global $path;
            global $root;
            global $UID;
            parent::__construct($db);
            $this->view = $path["view"] . "teams.php";
            $this->parse_filters();
            $s = $this->build_query();
            $q = $this->db->query($s);
            while ($r = $q->fetchArray(SQLITE3_ASSOC)){
                array_push($this->teams, new Team($db, $r["id"]));
            }
            $s = "
              SELECT id
              FROM unit
              WHERE unit.uid = '$UID';
            ";
            $q = $this->db->query($s);
            while ($r = $q->fetchArray(SQLITE3_ASSOC)){
                array_push($this->units, new Unit($this->db, $r["id"], false));
            }
            $this->title = "Teams - SWDB";
            $this->description = "Teams";
            $this->canonical = $root . "teams/";
        }

        /**
         * Parses the request looking for the selected filters, validates them
         * and adds them to the $filters array.
         */
        private function parse_filters(){
            global $FILTER_TEAM;
            global $AREA_TYPE;
            $this->filters = $FILTER_TEAM;
            if (isset($_GET["area"]) && in_array($_GET["area"], $AREA_TYPE)){
                $this->filters["area"] = $_GET["area"];
            }
            if (isset($_GET["name"]) && strlen($_GET["name"]) > 0){
                $this->filters["name"] = SQLite3::escapeString($_GET["name"]);
            }
            return;
        }

        /**
         * Builds the query to the rune table using the selected or default
         * filters.
         *
         * @return The query to be executed.
         */
        private function build_query(){
            global $ELEMENT;
            global $UID;
            $s = "
              SELECT id
              FROM team
              WHERE uid = '$UID'
            ";
            if (in_array($this->filters["area"], $ELEMENT)){
                $s = $s . " AND area  = '" . strtoupper($this->filters["area"]) . "') ";
            }
            if ($this->filters["name"] != ""){
                $s = $s . " AND upper(name) LIKE '%" . strtoupper($this->filters["name"]) . "%' ";
            }
            return $s;
        }

    }
?>
