<?php

namespace Modules\Client\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\Member;
use App\Models\Corporate;
use App\Models\File;
use App\Services\CorporateMemberService;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Client\Transformers\ClaimReport\MemberResources as ClaimReportMemberResources;
use Modules\Client\Transformers\Dashboard\MemberResources as ClaimSubmitMemberResources;
use Modules\Client\Transformers\Dashboard\MemberResources as DashboardMemberResources;
use Modules\Client\Transformers\Dashboard\MemberAlarmCenterResources as DashboardMemberAlarmResources;
use Modules\Client\Transformers\DataMemberResource;
use Illuminate\Support\Facades\DB;

class CorporateCurrentController extends Controller
{
    public function __construct(public CorporateMemberService $corporateMemberService)
    {
    }

    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request, $id)
    {
        $corporates = Corporate::query()
            ->with('currentPolicy', 'subCorporates')
            ->withCount([
                'employees',
                'corporateBenefits',
                'corporatePlans',

                // 'claims'
            ])
            // ->where('type', 'corporate')
            ->where('id', $id)
            ->paginate(1);

        return $corporates;
    }

    public function update(Request $request, $id)
    {
      
        $validate = $request->validate([
                        'reason' => 'required',
                    ]);

      
        try {
            DB::beginTransaction();
            //karena pake formdata
            $linkingRules = $request->linking_rules;
            $linkingRules = explode(',', $linkingRules);
            $corporate = Corporate::findOrFail($id);
            $corporate->fill($request->all());
            $corporate->linking_rules = $linkingRules;
            $corporate->save();

            if ($request->hasFile('logo')) {
                $pathFileAvatar = File::storeFile('avatar', $corporate->id, $request->file('logo'));

                $corporate->files()->updateOrCreate([
                    'type' => 'avatar',
                    'name' => File::getFileName('avatar', $corporate->id, $request->file('logo')),
                    'extension' => $request->file('logo')->getClientOriginalExtension(),
                    'path' => $pathFileAvatar,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

        return $corporate;
    }
}
