<?php

namespace App\Http\Controllers;

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

class ToolsProjectController extends Controller
{
    public function assignTools(Request $request)
    {
        $projectId   = $request->project_id;
        $subproyekId = $request->subproyek_id;
        $listToolsId = $request->tools_id;

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

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

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