<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Billing;
use App\Models\BillingItem;

class BillingItemsController extends Controller
{
    public function index(Request $request)
    {
        $billings = Billing::leftJoin('customers','customers.id','=','billings.customer_id')
        ->where('billings.id',$request->billing_id)
        ->select('billings.*','customers.name')
        ->get();
        
        $billingItems = DB::table('billing_items')->where('billing_id',$request->billing_id)->get();
        return view('admin/billing_items',['billing'=>$billings[0],'billingItems'=>$billingItems,'title'=>'AR Billing Details']);
    }
    
    public function create(Request $request){
        $billingItems=null;
        return view('admin/billing_item_create',['billingItems'=>$billingItems,'billingId'=>$request->billing_id]);
    }
    
    public function insert(Request $request){
        $description = $request->description;
        $amount = $request->amount;
        $billingId = $request->billing_id;
        $id = $request->id;

        $values = array('description'=>$description,'amount'=>$amount,'billing_id'=>$billingId);
        if($id == null){
            DB::table('billing_items')->insert($values);
            return response()->json(['status'=>'Insert Sukses']);
        }else{
            $values = array('description'=>$description,'amount'=>$amount);
            DB::table('billing_items')->where('id',$id)->update($values);
            return response()->json(['status'=>'Update Sukses ']);
        }
    }
    
    public function delete(Request $request){
        DB::table('billing_items')->where('id',$request->id)->delete();
        return response()->json(['status'=>'sukses']);
    }
    
    public function edit(Request $request){
        $billingItem = DB::table('billing_items')->where('id',$request->id)->first();
        return response()->json(['status'=>'sukses','data'=>$billingItem]);
    }
}
?>