<?php

namespace App\Services\Pair;

use App\Models\Fpdx\GroupMemberModel;
use App\Models\Fpdx\GroupModel;
use App\Models\Fpdx\PairModel;

class GroupService
{
    public function exitGroup(PairModel $pair)
    {
        try {
            \DB::beginTransaction();
            $other = PairModel::find($pair->assoc_id);
            if ($other) {
                if ($other->group_id > 0) {
                    GroupMemberModel::where('uid', $other->uid)->where('stage_id', $other->stage_id)->where(
                        'type',
                        'pair'
                    )->delete();
                    GroupModel::where('id', $other->group_id)->decrement('total_number');
                    $other->group_id = 0;
                    $other->save();
                }
            }
            $pair = PairModel::find($pair->id);
            if ($pair) {
                if ($pair->group_id > 0) {
                    GroupMemberModel::where('uid', $pair->uid)->where('stage_id', $pair->stage_id)->where(
                        'type',
                        'pair'
                    )->delete();
                    GroupModel::where('id', $pair->group_id)->decrement('total_number');
                    $pair->group_id = 0;
                    $pair->save();
                }
            }
            \DB::commit();

            return true;
        } catch (\Exception $e) {
            \DB::rollBack();

            return false;
        }
    }
}
