<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/
require_once __DIR__ . '/../../server/server/config/boot_global.php';
require_once __DIR__ . '/../../server/server/config/boot_local.php';

try
{
    $secret = array_key_exists( 'secret', $_GET ) ? $_GET[ 'secret' ] : NULL;
    $accountId = array_key_exists( 'accountId', $_GET ) ? $_GET[ 'accountId' ] : NULL;

    if ( $secret !== '86a21402972efa1d3c63198f853c25b6' )
    {
        die ( "Invalid" );
    }

    /** @var TB_Shared_Ent_Core_Account $acc */
    $account = TB_Shared_Ent_Core_Account::get( $accountId );
    if ( is_null( $account) )
    {
        die( "Err: Account not found." );
    }

    /** @var TB_Shared_Ent_TeamData_Profile $profile */
    $profile = TB_Shared_Ent_TeamData_Profile::getByAccountId( $accountId );

    if ( is_null( $profile ) )
    {
        die( "No Profile found." );
    }

    echo "Processing profile: " . $profile->getName() . " ... <br />";

    $profileId = $profile->id;
    $teams = TB_Shared_Ent_TeamData_Team::getByProfile( $profile );
    if ( $teams )
    {
        /** @var TB_Shared_Ent_TeamData_Team $team */
        foreach( $teams as $team )
        {
            if ( $profile->isOwnerOfTeam( $team->id ) )
            {
                $teamProfiles = TB_Shared_Ent_TeamData_Profile::getProfilesByTeamId( $team->id );
                if ( $teamProfiles )
                {
                    echo "Updating team profiles...<br />";
                    /** @var TB_Shared_Ent_TeamData_Profile $teamProfile */
                    foreach( $teamProfiles as $teamProfile )
                    {
                        if ( $teamProfile->id == $profileId )
                        {
                            continue;
                        }
                        echo "Leave team for profile " . $teamProfile->getName() . " ... <br />";
                        $teamProfile->leaveTeam( $team->id );
                        $teamProfile->save();
                    }
                }
                echo "Deleting team " . $team->display_name . " ... <br />";
                $team->delete();
            }
        }
    }

    echo "Deleting user information... <br />";
    $profile->delete();
    $account->delete();

}
catch ( Exception $e )
{
    echo "EXCEPTION: " . $e->getMessage();
    TB_Server_Utils_Log::get()->log( $e );
}