<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Fpdx\MediaModel;
use App\Models\Fpdx\MediaFeeLogModel;
use App\Models\Fpdx\MediaOrderModel;
use Illuminate\Http\Request;

class MediaFeeController extends Controller
{
    public function getFeeLogs()
    {
        $data = array();
        $feelogModel = new MediaFeeLogModel();
        $feelogs = $feelogModel->groupBy('tag')->get(['tag']);
        foreach ($feelogs as $fee) {
            $data[$fee->tag] = $feelogModel->where('tag', $fee->tag)->get();
        }
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $data
        ]);
    }

    public function createFee(Request $request)
    {
        $this->validate($request, [
            'media_id' => 'required',
            'tag' => 'required',
            'fee' => 'required',
        ]);
        $data = $request->all();
        $media = MediaModel::where('media_id', $data['media_id'])->firstOrFail(['public_name']);
        $data['public_name'] = $media->public_name;
        \DB::beginTransaction();
        try {
            $mediaFee = MediaFeeLogModel::create($data);
            $media->increment('fpdx_money', $request->input('fee'));
            MediaOrderModel::create([
                'media_id' => $request->media_id,
                'type' => 'bonus',
                'amount' => $request->fee * 100,
                'tag' => '分配对象',
                'describe' => "【奖金】分配对象活动"
            ]);
            \DB::commit();
            return response([
                'code' => 200,
                'message' => 'success',
                'data' => $mediaFee
            ]);
        } catch (\Exception $e) {
            \DB::rollBack();
            return response([
                'code' => 500,
                'message' => $e->getMessage()
            ]);
        }
    }
}
