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

/**
 * Class TB_Shared_Ent_TeamData_Profile
 *
 * @property integer $id
 * @property integer $account_id
 * @property string $role
 * @property integer $team_id
 * @property string|null $pic_url
 * @property string|null $pic_cloud_id
 * @property string $gender
 * @property string $first_name
 * @property string $last_name
 * @property string|null $player_pass_no
 * @property Date|null $birthday
 * @property string|null $street
 * @property string|null $zip_code
 * @property string|null $city
 * @property string|null $phone
 * @property string|null $mobile
 * @property string|null $misc
 * @property string $status
 */
class TB_Shared_Ent_TeamData_Profile extends Francis_Db_Row {

    // Enums
    const ROLE_TRAINER = 'trainer';
    const ROLE_COTRAINER = 'cotrainer';
    const ROLE_PLAYER = 'player';
    const ROLE_FAN = 'fan';

    const STATUS_FIT = 'fit';
    const STATUS_INJURED = 'injured';
    const STATUS_BARRED = 'barred';
    const STATUS_INACTIVE = 'inactive';

    const GENDER_MALE = 'male';
    const GENDER_FEMALE = 'female';

    /**
     * Return valid roles
     *
     * @return array [ (string), (string), ... ]
     */
    public static function getValidRoles() {
        return array(
            self::ROLE_TRAINER,
            self::ROLE_COTRAINER,
            self::ROLE_PLAYER,
            self::ROLE_FAN
        );
    }

    /**
     * Return valid status values
     *
     * @return array [ (string), (string), .. ]
     */
    public static function getValidStatus() {
        return array(
            self::STATUS_FIT,
            self::STATUS_BARRED,
            self::STATUS_INJURED,
            self::STATUS_INACTIVE
        );
    }

    /**
     * Return valid gender values
     *
     * @return array
     */
    public static function getValidGender() {
        return array(
            self::GENDER_MALE,
            self::GENDER_FEMALE
        );
    }

    /**
     * Get first profile by account id
     * @param $accountId
     * @return array
     */
    public static function getByAccountId( $accountId ) {
        $sql = 'SELECT * FROM ' . self::getTable() . ' WHERE account_id = :account_id';
        $params = array( ':account_id' => $accountId );
        return self::findMany( $sql, $params );
    }

    /**
     * @param int $teamId
     * @return array (TB_Shared_Ent_TeamData_Profile)
     */
    public static function getProfilesByTeamId( $teamId ) {
        $sql = 'SELECT * FROM ' . self::getTable() . ' WHERE team_id = :team_id ORDER BY last_name ASC';
        $params = array( ':team_id' => (int)$teamId );
        return self::findMany( $sql, $params );
    }

    /**
     * @param $teamId
     * @return int
     */
    public static function getProfileCountByTeamId( $teamId )
    {
        $db = self::getDbh();

        $stmt = $db->prepare( "SELECT COUNT(id) as 'amount' FROM `" . self::getTable() . "` WHERE team_id = :team_id" );
        $stmt->bindParam( ':team_id', $teamId, PDO::PARAM_INT );
        $stmt->execute();
        $rowCount = $stmt->fetchColumn( 0 );
        return (int)$rowCount;
    }

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

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

    public static function resolveDisplayNameByEmail( $email ) {
        $name = NULL;
        if ( TB_Shared_Utils_Validator::isValidEmail( $email ) ) {
            $parts = explode( "@", $email );
            if ( 0  < count( $parts ) ) {
                $name = $parts[0];
            }
        }
        return $name;
    }

    /**
     * Get timestamp ids
     *
     * @return NULL|TB_Shared_Ent_TeamData_ProfileTimestamp
     */
    public function getTimestamps() {
        return TB_Shared_Ent_TeamData_ProfileTimestamp::getByProfileId( $this->id );
    }

    /**
     * Checks if given db row is owned by current profile instance
     *
     * @param Francis_Db_Row $row
     */
    public function isOwn( Francis_Db_Row $row ) {
        // Default return value
        $isOwn = false;

        // Check author
        switch( get_class( $row ) ) {

            // Appointment
            case 'TB_Shared_Ent_TeamData_Appointment':
                /** @var TB_Shared_Ent_TeamData_Appointment $row */
                $team = TB_Shared_Ent_TeamData_Team::get( $row->team_id );
                if ( $team instanceof TB_Shared_Ent_TeamData_Team &&
                    $team->id == $this->team_id &&
                    $this->role == self::ROLE_TRAINER ) {
                    $isOwn = true;
                }
                break;

            // Team
            case 'TB_Shared_Ent_TeamData_Team':
                /** @var TB_Shared_Ent_TeamData_Team $row */
                if ( $row->id == $this->team_id &&
                    $this->role == self::ROLE_TRAINER ) {
                    $isOwn = true;
                }
                break;

            // Profile
            case 'TB_Shared_Ent_TeamData_Profile':
                /** @var TB_Shared_Ent_TeamData_Profile $row */
                if ( $row->id == $this->id ) {
                    $isOwn = true;
                }
                break;
        }

        return $isOwn;
    }

    /**
     * @return bool
     */
    public function isPlayer() {
        return ( $this->role == self::ROLE_PLAYER );
    }

    /**
     * @return bool
     */
    public function isTrainer() {
        return ( $this->role == self::ROLE_TRAINER );
    }

    /**
     * @return bool
     */
    public function isCoTrainer() {
        return ( $this->role == self::ROLE_COTRAINER );
    }

    /**
     * Get first + last name
     * @return string
     */
    public function getName() {
        return trim( $this->first_name . ' ' . $this->last_name );
    }

    /**
     * Called during deletion
     */
    public function deleteReferences() {
        // Delete team data
        TB_Shared_Ent_TeamData_Attendee::deleteAllForProfileId( $this->id );
        TB_Shared_Ent_TeamData_ProfileTimestamp::deleteAllForProfileId( $this->id );
        TB_Shared_Ent_TeamData_News::deleteByAuthorProfileId( $this->id );

        // Delete image from cloud
        if ( !is_null( $this->pic_cloud_id ) ) {
            $cloudinary = TB_Server_Utils_Cloudinary::get();
            $cloudinary->delete( $this->pic_cloud_id );
        }
        
        // Delete related account data (core db)

        $dbc = TB_Shared_Db_Core::get();
        if ( !$dbc->inTransaction() ) {
            $dbc->beginTransaction();
        }
        try {

            // Profile related
            TB_Shared_Ent_Core_Session::deleteByAccountIdAndProfileId( $this->account_id, $this->id );
            TB_Shared_Ent_Core_EmailNotification::deleteByProfileId( $this->id );

            // Delete related account if this is the only profile
            $remainingProfiles = TB_Shared_Ent_TeamData_Profile::getByAccountId( $this->account_id );
            if ( is_array( $remainingProfiles ) && 0 == count( $remainingProfiles ) ) {
                TB_Shared_Ent_Core_DeviceReg::deleteByAccountId( $this->account_id );
                TB_Shared_Ent_Core_EmailValidation::deleteByAccountId( $this->account_id );
                TB_Shared_Ent_Core_EmailChange::deleteByAccountId( $this->account_id );
                TB_Shared_Ent_Core_Account::deleteByAccountId( $this->account_id );
            }

            $dbc->commit();
        } catch ( Exception $e ) {
            $dbc->rollBack();
            throw $e;
        }
    }
}