<?php

namespace App\Http\Controllers\Admin;

use App\Models\Common\KfaccountModel;
use App\Models\Common\MediaModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class KfaccountController extends Controller
{

    public function index(Request $request)
    {
        $build = KfaccountModel::when($request->filled('wxid'), function ($query) use ($request) {
            return $query->where('wxid', $request->wxid);
        })->when($request->filled('nickname'), function ($query) use ($request) {
            return $query->where('nickname', 'like', "%" . $request->nickname . "%");
        });
        $kfaccounts = $build->get();
        $total = $kfaccounts->count();
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => [
                'data' => $kfaccounts,
                'total' => $total,
            ]
        ]);
    }


    public function update(Request $request, $id)
    {
        $kfaccount = KfaccountModel::findOrFail($id);
        $kfaccount->fill($request->all());
        $kfaccount->save();
        if ($request->filled('qrcode')) {
            MediaModel::updateOrCreate(
                ['key' => $kfaccount->wxid],
                ['url' => $request->qrcode, 'public_id' => 'gh_01c089b58dda', 'updated_at' => 0]
            );
        }
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => $kfaccount
        ]);
    }
}
