<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Producttype;
use App\Models\Product;

class ProducttypeController extends Controller
{
    public function getProducttype(){
        $data = Producttype::all();
        
        $response = [
            'success'=>true,
            'producttype'=>$data,
        ];
        
        return response($response,200);
    }

    public function getProducttypeDetail(Request $request){
        $data = Producttype::find($request->id);
        
        $response = [
            'success'=>true,
            'producttype'=>$data,
        ];
        
        return response($response,200);
    }

    public function createProducttype(Request $request){
        $request->validate([
            'name' =>'required',
        ]);

        $check = Producttype::where('name', $request->name)->first();
        if($check){
            $response = [
                'success'=>false,
                'message'  => 'Nama sudah dipakai',
            ];
            return response($response,400);
        }

        $data = new Producttype;
        $data->name = $request->name;
        $data->save();
        
        $response = [
            'success'=>true,
            'producttype'=>$data,
        ];
        
        return response($response,200);
    }

    public function editProducttype(Request $request){
        $request->validate([
            'name' =>'required',
        ]);

        $check = Producttype::where('name', $request->name)->first();
        if($check){
            $response = [
                'success'=>false,
                'message'  => 'Nama sudah dipakai',
            ];
            return response($response,400);
        }

        $data = Producttype::find($request->id);
        $data->name = $request->name;
        $data->save();
        
        $response = [
            'success'=>true,
            'producttype'=>$data,
        ];
        
        return response($response,200);
    }

    public function deleteProducttype(Request $request){

        $products = Product::where('producttype', '=', $request->id)
                             ->get()
                             ->map(function ($item) {
                                return $item->name;
                              });

        if(count($products) > 0){
            $response = [
                'success'=>false,
                'message'=> "silahkan hapus produk " . join(", ", json_decode($products, true)) . " terlebih dahulu",
            ];
            
            return response($response,400);
        }

        $data = Producttype::find($request->id);
        $data->delete();
        
        $response = [
            'success'=>true,
            'product'=>$products,
        ];
        
        return response($response,200);
    }
}
