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

/**
 * Class TB_Server_Control_Settings
 */
class TB_Server_Control_Settings
{
    /**
     * @param TB_Server_Core_RequestData $params
     * @return TB_Server_Core_Response
     */
    public static function getPremiumDetails( TB_Server_Core_RequestData $params )
    {
        $resp = new TB_Server_Core_Response();

        $account = TB_Server_Core_Session::get()->getAccount();

        $teams = array();
        $teamsForPremium = array();
        $premiumLogs = array();

        // Get all profiles
        $profiles = TB_Shared_Ent_TeamData_Profile::getByAccountId( $account->id );

        /** @var TB_Shared_Ent_TeamData_Team $team */
        $team = NULL;

        /** @var TB_Shared_Ent_TeamData_PremiumLog $entPremiumLog */
        $entPremiumLog = NULL;

        $entPremiumLogs = TB_Shared_Ent_TeamData_PremiumLog::getAllPremiumLogsForAccount( $account );
        foreach ( $entPremiumLogs as $entPremiumLog )
        {
            array_push( $premiumLogs, $entPremiumLog->asArray() );
        }

        $entPremiumLog = NULL;

        /** @var TB_Shared_Ent_TeamData_Profile $profile */
        foreach ( $profiles as $profile )
        {
            $team = TB_Shared_Ent_TeamData_Team::get( $profile->team_id );

            array_push( $teams, $team->asArray() );

            $entPremiumLog = TB_Shared_Ent_TeamData_PremiumLog::getLastPremiumLogForTeam( $team );
            if ( $entPremiumLog instanceof TB_Shared_Ent_TeamData_PremiumLog )
            {
                if ( TB_Server_Core_Premium::isFreemium( $entPremiumLog->package_id ) ||
                    $entPremiumLog->status == TB_Shared_Ent_TeamData_PremiumLog::STATUS_CLOSED ||
                    $entPremiumLog->status == TB_Shared_Ent_TeamData_PremiumLog::STATUS_CANCELLED )
                {
                    array_push( $teamsForPremium, array(
                        'team' => $team->asArray(),
                        'lastPremiumLog' => $entPremiumLog->asArray()
                    ));
                }
            }
            else
            {
                array_push( $teamsForPremium, array(
                    'team' => $team->asArray(),
                    'lastPremiumLog' => NULL
                ));
            }
        }


        $resp->addData( 'premium_logs', $premiumLogs );
        $resp->addData( 'teams', $teams );
        $resp->addData( 'teams_for_premium', $teamsForPremium );

        return $resp;
    }

    /**
     * @param TB_Server_Core_RequestData $params
     * @return TB_Server_Core_Response
     * @throws Exception
     */
    public static function getPremiumDetail( TB_Server_Core_RequestData $params )
    {
        $resp = new TB_Server_Core_Response();

        $premiumLogId = $params->get( 'premiumLogId' );

        $entPremiumLog = TB_Shared_Ent_TeamData_PremiumLog::get( $premiumLogId );
        $account = TB_Server_Core_Session::get()->getAccount();

        if ( !$entPremiumLog || $account->id !== $entPremiumLog->account_id )
        {
            throw new Exception( "Invalid premium log id" );
        }

        TB_Server_Core_Premium::initBraintree();
        $braintreeSubscription = Braintree_Subscription::find( $entPremiumLog->braintree_subscription_id );
        $resp->addData( 'braintree_subscription', array(
            'firstBillingDate' => $braintreeSubscription->firstBillingDate,
            'nextBillingDate' => $braintreeSubscription->nextBillingDate,
        ));
        $resp->addData( 'premium_log', $entPremiumLog );
        $resp->addData( 'team', TB_Shared_Ent_TeamData_Team::get( $entPremiumLog->team_id ) );

        return $resp;
    }

    /**
     * @param TB_Server_Core_RequestData $params
     * @return TB_Server_Core_Response
     */
    public static function updatePremiumDetail( TB_Server_Core_RequestData $params )
    {
        $resp = new TB_Server_Core_Response();

        /** @var TB_Shared_Ent_Core_Account $account */
        $account = TB_Server_Core_Session::get()->getAccount();
        $premiumLogId = $params->get( 'premiumLogId' );
        $billingData = $params->get( 'billingData' );

        if ( !isset( $premiumLogId ) || !self::isBillingDataValid( $billingData ) )
        {
            throw new Exception( 'Invalid premium details to update.' );
        }

        /** @var TB_Shared_Ent_TeamData_PremiumLog $entPremiumLog */
        $entPremiumLog = TB_Shared_Ent_TeamData_PremiumLog::get( $premiumLogId );

        if ( !isset( $entPremiumLog ) ||
             $account->id != $entPremiumLog->account_id )
        {
            throw new Exception( 'Account not allowed to modify premium log.' );
        }

        if ( $entPremiumLog->status === TB_Shared_Ent_TeamData_PremiumLog::STATUS_DELETED ||
             $entPremiumLog->status === TB_Shared_Ent_TeamData_PremiumLog::STATUS_CANCELLED )
        {
            throw new Exception( 'Premium Log cannot be updated due to status.' );
        }

        $entPremiumLog->billing_company_name = $billingData[ 'company_name' ];
        $entPremiumLog->billing_company_tax_id = $billingData[ 'tax_id' ];
        $entPremiumLog->billing_first_name = $billingData[ 'first_name' ];
        $entPremiumLog->billing_last_name = $billingData[ 'last_name' ];
        $entPremiumLog->billing_street = $billingData[ 'street' ];
        $entPremiumLog->billing_zip = $billingData[ 'zip_code' ];
        $entPremiumLog->billing_city = $billingData[ 'city' ];
        $entPremiumLog->billing_email = $billingData[ 'email' ];
        $entPremiumLog->save();

        return $resp;
    }

    /**
     * @param TB_Server_Core_RequestData $params
     * @return TB_Server_Core_Response
     * @throws Exception
     */
    public static function cancelSubscription(  TB_Server_Core_RequestData $params )
    {
        $resp = new TB_Server_Core_Response();

        $cancelSuccess = false;
        $lastPremiumDate = NULL;
        $nowDt = new DateTime();

        /** @var TB_Shared_Ent_Core_Account $account */
        $account = TB_Server_Core_Session::get()->getAccount();
        $premiumLogId = $params->get( 'premiumLogId' );

        if ( !isset( $premiumLogId ) )
        {
            throw new Exception( 'Invalid premium log id.' );
        }

        /** @var TB_Shared_Ent_TeamData_PremiumLog $entPremiumLog */
        $entPremiumLog = TB_Shared_Ent_TeamData_PremiumLog::get( $premiumLogId );

        if ( !isset( $entPremiumLog ) ||
            $account->id != $entPremiumLog->account_id )
        {
            throw new Exception( 'Account not allowed to modify premium log.' );
        }

        if ( $entPremiumLog->status === TB_Shared_Ent_TeamData_PremiumLog::STATUS_DELETED ||
            $entPremiumLog->status === TB_Shared_Ent_TeamData_PremiumLog::STATUS_CANCELLED )
        {
            throw new Exception( 'Premium Log cannot be cancelled due to status.' );
        }


        TB_Server_Core_Premium::initBraintree();
        $braintreeRes = Braintree_Subscription::cancel( $entPremiumLog->braintree_subscription_id );

        if ( $braintreeRes && $braintreeRes->success )
        {
            if ( $entPremiumLog->status === TB_Shared_Ent_TeamData_PremiumLog::STATUS_PENDING ||
                 $braintreeRes->subscription->firstBillingDate > $nowDt )
            {
                $entPremiumLog->valid_until_dt = $entPremiumLog->valid_from_dt;
                $entPremiumLog->status = TB_Shared_Ent_TeamData_PremiumLog::STATUS_DELETED;
            }
            else if ( $braintreeRes->subscription->billingPeriodEndDate )
            {
                $entPremiumLog->valid_until_dt = $braintreeRes->subscription->billingPeriodEndDate->setTime( 23, 59, 59 );
                $entPremiumLog->status = TB_Shared_Ent_TeamData_PremiumLog::STATUS_CANCELLED;
            }
            else
            {
                // Unknown use case - add some buffer as time
                $untilDt = new DateTime();
                $untilDt->modify('+7 day' );
                $entPremiumLog->valid_until_dt = $untilDt;
                $entPremiumLog->status = TB_Shared_Ent_TeamData_PremiumLog::STATUS_DELETED;
            }

            $entPremiumLog->save();

            $cancelSuccess = true;
        }

        $resp->addData( 'cancel_success', $cancelSuccess );

        return $resp;
    }

    /**
     * @param TB_Server_Core_RequestData $params
     * @return TB_Server_Core_Response
     */
    public static function getBilling( TB_Server_Core_RequestData $params )
    {
        $resp = new TB_Server_Core_Response();

        $account = TB_Server_Core_Session::get()->getAccount();
        $invoices = array();

        $entInvoices = TB_Shared_Ent_TeamData_Invoice::getAllForAccount( $account );

        $resp->addData( 'invoices', $entInvoices );

        return $resp;
    }

    public static function getBillingDetail( TB_Server_Core_RequestData $params )
    {
        $resp = new TB_Server_Core_Response();

        $invoiceId = $params->get( 'id' );
        $account = TB_Server_Core_Session::get()->getAccount();
        /** @var TB_Shared_Ent_TeamData_Invoice $entInvoice */
        $entInvoice = TB_Shared_Ent_TeamData_Invoice::get( $invoiceId );
        if ( is_null( $entInvoice ) )
        {
            throw new Exception( 'Invoice not found.' );
        }
        $resp->addData( 'invoice', $entInvoice );

        return $resp;
    }

    /**
     * @param array $bData
     * @return bool
     */
    private static function isBillingDataValid( array $bData )
    {
        if ( !isset( $bData[ 'first_name' ] ) ) return false;
        if ( !isset( $bData[ 'last_name' ] ) ) return false;
        if ( !isset( $bData[ 'street' ] ) ) return false;
        if ( !isset( $bData[ 'zip_code' ] ) ) return false;
        if ( !isset( $bData[ 'city' ] ) ) return false;
        if ( !isset( $bData[ 'email' ] ) ) return false;

        // @todo
        return true;
    }

}