<?php

namespace App\Http\Controllers\Frontend\User;

use App\Http\Controllers\Controller;
use App\Models\Lab;
use App\Models\Lookups\Stripe_plans;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Laravel\Cashier\Http\Controllers\WebhookController as CashierController;
use Laravel\Cashier\Subscription;

class WebhookController extends CashierController
{
    //
    /**
     * Handle customer changed.
     *
     * @param array $payload
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handleCustomerSubscriptionUpdated(array $payload)
    {
        Log::info('handleCustomerSubscriptionUpdated called');
        $updateStatus = parent::handleCustomerSubscriptionUpdated($payload);

        // check the user's status and do some interesting things with roles
        if ($user = $this->getUserByStripeId($payload['data']['object']['customer'])) {
            // do they have active subscriptions?
            if ($user->current_active_subscriptions->count()) {
                // get the plan
                $plan = Stripe_plans::where(['stripe_plan' => auth()->user()->current_active_subscriptions->last()->stripe_plan])->first();

                // deal with any pending data
                foreach ($user->pending_data as $pending_data) {
                    //rehydrate the data
                    $data = \json_decode($pending_data->pending_data);
                    // fix up the labs
                    if ($user->my_lab) {
                        //  dd(auth()->user()->my_lab);
                        Lab::find($user->my_lab->id)->update(['name' => $data->lab_name]);
                    } else {
                        // make a new lab, make this person an admin
                        $lab = new Lab(['name' => $data->lab_name]);
                        $lab->save();
                        $lab->members()->sync(array($user->id => array('admin' => 'true')));
                    }
                    // clean up the data
                    $pending_data->delete();
                }

                // update the user roles based on the active subscription
                $roles = [$plan->role];
                if ($user->hasRole('lab member')) {
                    $roles[] = 'lab member';
                }
                $user->syncRoles($roles);
            }else{
            // there's no active subscriptions, drop back to free level
                //@TODO make all boards read-only and take any other actions necessary here as well
                $roles = ['user'];
                if ($user->hasRole('lab member')) {
                    $roles[] = 'lab member';
                }
                $user->syncRoles($roles);
            }

        }
        return $updateStatus;
    }
}
