<?php
    namespace App\Http\Controllers\Admin;
    
    use App\Models\Service;
    use App\Models\Category;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\DB;
    use App\Models\BillingItem;
    
    class AdminCleanController extends Controller
    {
        public function index(Request $request)
        {
            $services = Service::leftJoin('categories','categories.id','=','services.category_id')
            ->select('services.*','categories.category_name')->paginate(15);
            
            if($request->page==''){
                return redirect('admin-clean?page='.$services->lastPage());
            }else{
                return view('admin.admin_clean2',['services'=>$services,'title'=>'AR Clean']);
            }
        }
        
        public function create(Request $request){
            $categories = Category::get();
            return view('admin.admin_clean_create',['categories'=>$categories,'title'=>'Manage Service']);
        }
        
        public function edit(Request $request){
            $categories = Category::get();
            $service = Service::where('id',$request->id)->first();
            return view('admin.admin_clean_create',['service'=>$service,'categories'=>$categories,'title'=>'Manage Service']);
        }
        
        public function modify(Request $request){
            $id = $request->id;
            $name = $request->name;
            $categoryId = $request->category;
            $cost = $request->cost;
            $costLabel = $request->cost_label;
            
            $values = array('name'=>$name,'category_id'=>$categoryId,'cost'=>$cost,'cost_label'=>$costLabel);
            if($id == 0){
                DB::table('services')->insert($values);
            }else{
                DB::table('services')->where('id',$id)->update($values);
            }
            return redirect('admin-clean');
        }
        
        public function delete(Request $request){
            //Periksa apakah service/produk telah digunakan pada invoice.
            $billing_items = DB::table('billing_items')->where('service_id',$request->id)->first();
            if($billing_items){
                return response()->json(['status'=>'Data tidak dapat di hapus! Karena telah di gunakan di kolom invoice']);
            }
            
            //Hapus produk/layanan
            $result = DB::table('services')->where('id',$request->id)->delete();
            if($result){
                return response()->json(['status'=>'Data berhasil di hapus!']);
            }
        }
    
    }
?>