<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\CareItem;
use App\Models\OrderItem;

class AdminCareDetailsController extends Controller
{
    public function index(Request $request)
    {
        $careItems = CareItem::where('product_id','=',$request->id)->orderBy('care_items.size','asc')->get();
        return view('admin/admin_care_details',
            [
                'items'=>$careItems,
                'name'=>$request->name,
                'product_id'=>$request->id,
                'title'=>'AR-Care Details',
            ]
        );
    }
    
    public function show(Request $request){
        $careItems = CareItem::where('id','=',$request->id)->first();

        return response()->json([
            'success' => true,
            'message' => "",
            'data' => $careItems,
        ]);
    }

    public function store(Request $request){
        date_default_timezone_set("Asia/Jakarta");

        $id = $request->id;

        $values = array(
            'product_id'=>$request->product_id,
            'size'=>$request->size,
            'quantity'=>$request->quantity,
            'price'=>$request->price,
            'weight'=>$request->weight,
            'specifications'=>$request->specifications,
        );

        if($id === '' || $id === null){
            $insertedId = CareItem::insertGetId($values);
            $values['id'] = $insertedId;

            return response()->json([
                'success' => true,
                'message' => "Insert data berhasil",
                'data'    => $values
            ]);

        }else{
            $values['id'] = $id;
            CareItem::where('id',$id)->update($values);

            return response()->json([
                'success' => true,
                'message' => "Update data berhasil",
                'data'    => $values
            ]);
        }
    }    
    
    public function destroy(Request $request){
        $orderItems = OrderItem::where('product_items_id','=',$request->id)->get();
        if(count($orderItems) > 0){
            return response()->json([
                'success' => false,
                'message' => "Data tidak dapat di hapus, karena sedang di gunakan."
            ]);
        }else{
            CareItem::where('id',$request->id)->delete();
            return response()->json([
                'success' => true,
                'message' => "Hapus data berhasil"
            ]);
        }
    }
}

?>