<?php

namespace Modules\Client\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\CorporatePolicy;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Modules\Client\Transformers\Dashboard\TopUpLimitResources;

class TopUpController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index($corporate_id)
    {
        $data = Auth::user()
            ->managedCorporates()
            ->with(['currentPolicy'])
            ->withCount(['employees', 'claims' => function ($query) {
                $query->where('claims.status', 'paid');
            }])
            ->find($corporate_id);

        return Helper::responseJson(TopUpLimitResources::make($data));
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request, $corporate_id)
    {

        $data = $request->validate([
            'topup' => 'required|numeric',
        ]);

        $corporatePolicy = CorporatePolicy::query()->where('corporate_id', $corporate_id)->firstOrFail();
        if (!$corporatePolicy) {
            return response()->json(['message' => 'Corporate policy not found'], 404);
        }

        $corporatePolicy->total_premi += $data['topup'];
        $corporatePolicy->save();

        return response()->json(['message' => 'Amount added to total_premi successfully'], 200);
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        return view('client::show');
    }

    public function get($corporate_id)
    {
        $data = CorporatePolicy::query()
            ->where('corporate_id', $corporate_id)
            ->with(['currentPolicy', 'employees'])
            ->withCount(['employees', 'claims' => function ($query) {
                $query->where('claims.status', 'paid');
            }])
            ->first();

        if (!$data) {
            return response()->json(['message' => 'Corporate policy not found'], 404);
        }

        return Helper::responseJson(TopUpLimitResources::make($data));
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        //
    }
}
