<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use App\User;

class PerubatanController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(){
        $api_url = config('api.url');
        $auth_user = Auth::user();
        $cawangan_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();

        $paginate = User::paginate(5);

        return view('operasi.perubatan.index',compact('cawangan_info','api_url','auth_user','paginate'));

    }

    public function search(Request $request){
        $api_url = config('api.url');
        $auth_user = Auth::user();
        $cawangan_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();


        $search = $request->input('search');

        $query = User::query();
    
        if ($search) {
            $query->where('name', 'LIKE', "%{$search}%");
        }
        $paginate = $query->paginate(5);
        $paginate->appends($request->all());

        return view('operasi.perubatan.index',compact('cawangan_info','api_url','auth_user','paginate'));
    }

    public function update(Request $request){
        $api_url = config('api.url');
        $auth_user = Auth::user();

        $user = User::where('id', $request->id)->first();
        $user = optional($user)->toArray();

        $amount = str_replace(',', '', $request->amount);

        $total_perubatan = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/panjar/getperubatan/'. $user['cawangan'],[
            'tuntutoleh' => $user['name']
        ])->json();

        $remaining = floatval($amount) - floatval($total_perubatan);

        $response = User::where('id', $request->id)->update(['perubatan_asal' => $amount,'perubatan' => $remaining]);

        return $response;
    }
}
