<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/


/**
 * Class TB_Shared_Ent_Core_Invitation
 *
 * @property integer $id
 * @property integer $team_id
 * @property integer $inviter_profile_id
 * @property string $first_name
 * @property string $last_name
 * @property string $email
 * @property string $role
 * @property string $token
 * @property string $state
 * @property integer $last_update
 */
class TB_Shared_Ent_Core_Invitation extends Francis_Db_Row {

    const STATE_SENDING = 'sending';
    const STATE_DELIVERED = 'delivered';
    const STATE_ACCEPTED = 'accepted';
    const STATE_CANCELLED = 'cancelled';

    const CLEANUP_TIME_AFTER_ACCEPT = 172800; // 2 Tage

    // Enums
    // Note: Needs to be
    const ROLE_TRAINER = TB_Shared_Ent_TeamData_Profile::ROLE_TRAINER;
    const ROLE_COTRAINER = TB_Shared_Ent_TeamData_Profile::ROLE_COTRAINER;
    const ROLE_PLAYER = TB_Shared_Ent_TeamData_Profile::ROLE_PLAYER;
    const ROLE_FAN = TB_Shared_Ent_TeamData_Profile::ROLE_FAN;

    /**
     * Get valid roles
     *
     * @return array<String>
     */
    public static function getValidRoles() {
        return array(
            self::ROLE_TRAINER,
            self::ROLE_COTRAINER,
            self::ROLE_PLAYER,
            self::ROLE_FAN
        );
    }

    /**
     * @param string $token
     * @return NULL|TB_Shared_Ent_Core_Invitation
     */
    public static function getByToken( $token ) {
        $sql = "SELECT * FROM " . self::getTable() . " WHERE token = :token AND state = :state";
        return self::findOne( $sql, array( ':token' => $token, ':state' => TB_Shared_Ent_Core_Invitation::STATE_DELIVERED ) );
    }

    /**
     * @return array
     */
    public static function getForSending() {
        $sql = "SELECT * FROM " . self::getTable() . " WHERE state = :state";
        return self::findMany( $sql, array( ':state' => self::STATE_SENDING ) );
    }

    /**
     * @param integer $teamId
     * @return array
     */
    public static function getByTeamId( $teamId ) {
        $sql = "SELECT * FROM " . self::getTable() . " WHERE team_id = :team_id";
        return self::findMany( $sql, array( ':team_id' => $teamId ) );
    }

    /**
     * Deletes entries for given team id
     *
     * @param int $teamId
     */
    public static function deleteByTeamId( $teamId ) {
        $sql = 'DELETE FROM ' . self::getTable() . ' WHERE team_id = :team_id';
        return self::execute( $sql, array( ':team_id' => $teamId ) );
    }

    /**
     * Return table name
     *
     * @return null|string
     */
    public static function getTable() {
        return 'invitation';
    }

    /**
     * Return db handler
     *
     * @return Francis_Db_MySql|null
     */
    public static function getDbh() {
        return TB_Shared_Db_Core::get();
    }

} 