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

/**
 * Class TB_Shared_Ent_TeamData_Team
 *
 * @property integer $id
 * @property string|NULL $public_id
 * @property string|null $reg_no
 * @property string $display_name
 * @property string $category
 * @property string $emblem_url
 * @property string $emblem_cloud_id
 * @property string $active_premium_package
 * @property int created_ts
 */
class TB_Shared_Ent_TeamData_Team extends Francis_Db_Row {

    /**
     * @param $publicId
     * @return NULL|static
     */
    public static function getByPublicId( $publicId )
    {
        $sql = 'SELECT * FROM ' . self::getTable() . ' WHERE public_id = :public_id ';
        $sql .= 'AND public_id IS NOT NULL LIMIT 1';
        $params = array( ':public_id' => $publicId );
        return self::findOne( $sql, $params );
    }

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

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

    /**
     * Called during deletion
     */
    public function deleteReferences() {

        // Load all profiles
        $profiles = TB_Shared_Ent_TeamData_Profile::getProfilesByTeamId( $this->id );
        // Loop over all profiles
        /** @var TB_Shared_Ent_TeamData_Profile $profile */
        foreach( $profiles as $profile ) {
            $profile->delete();
        }

        // Remaining TeamData Tables:
        // - Appointment
        // - News
        TB_Shared_Ent_TeamData_Appointment::deleteByTeamId( $this->id );
        TB_Shared_Ent_TeamData_News::deleteByTeamId( $this->id );

        // Remaining Core Tables:
        // - Email notification
        // - invitation
        TB_Shared_Ent_Core_EmailNotification::deleteByTeamId( $this->id );
        TB_Shared_Ent_Core_Invitation::deleteByTeamId( $this->id );

        // Delete image from cloud
        if ( !is_null( $this->emblem_cloud_id ) ) {
            $cloudinary = TB_Server_Utils_Cloudinary::get();
            $cloudinary->delete( $this->emblem_cloud_id );
        }

    }

    /**
     * @return bool true if team is active premium, else false
     */
    public function isPremium()
    {
        return ( $this->active_premium_package !== TB_Server_Core_Premium::PREMIUM_PACKAGE_STANDARD );
    }
}