<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\UserProject;

class UserProyekController extends Controller
{
    public function assignUserProyek(Request $request)
    {
        $projectId   = $request->project_id;
        $subproyekId = $request->subproyek_id;
        $listUser = $request->user_id;

        if(!$projectId && !$subproyekId){
            return response()->json(['status'=>'failed','message'=>'Required proyek_id or subproyek id','code'=>400],400);
        }
        
        if(is_array($listUser) && count($listUser) > 0){
            $result = 0;
            UserProject::where('proyek_id', $projectId)->delete();
            UserProject::where('proyek_id', $subproyekId)->delete();
            foreach($listUser as $id){
                $data = [
                    'user_id'=>(int)$id
                ];

                if($projectId && $projectId!="" && (int)$projectId > 0){
                    $data['proyek_id'] = $projectId;
                }else if($subproyekId && $subproyekId!="" && (int)$subproyekId > 0){
                    $data['subproyek_id'] = $subproyekId;
                }

                $insert = UserProject::create($data);
                if($insert){
                    $result++;
                }else{
                    $result--;
                }
            }
            if($result > 0){
                return response()->json(['status'=>'success','message'=>'User Project successfull updated','code'=>200], 200);
            }else{
                return response()->json(['status'=>'failed','message'=>'User Project failed updated','code'=>400], 400);
            }
        }else{
            UserProject::where('proyek_id', $projectId)->delete();
            UserProject::where('proyek_id', $subproyekId)->delete();
            return response()->json(['status'=>'success','message'=>'User Project Successfull updated','code'=>200], 200);
        }
    }
}