<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Models\Tax;

class TaxController extends Controller
{
    public function create(Request $request){
        // Validate Item
        $validator=validator($request->all(),[
            'tax_name'=>'required',
            'tax_rate'=>'required',
            'tax_type'=>'required',
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {

            $obj['tax_name']=$request['tax_name'];
            $obj['tax_rate']=$request['tax_rate'];
            $obj['tax_type']=$request['tax_type'];

            if($request['id']>0){

                try{

                    $tax=Tax::findOrFail(intVal($request['id']));
                    $tax->update($obj);
                    
                } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                    // Return error message in JSON if ID not found
                    return response()->json(['message' => 'Invalid Id to update '], 404);
                }

            }else{
                $tax=Tax::create($obj);
            }

            $response=[
                'success'=>true,
                'tax'=>$tax,
                'message'=>'Successfully Tax Created'
            ];

            return response()->json($response);
        }
    }

    public function list(Request $request){
        
        $tax=Tax::get();

        $response=[
            'success'=>true,
            'tax'=>$tax,
            'message'=>'Successfully tax fetched'
        ];

        return response()->json($response);
    }
}
