<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \App\Models\{Sector, SectorOperario, MaterialSector};

class SectoresController extends Controller
{
    public function index()
    {
        return Sector::with('operarios')->with('materiales')->with('supervisor')->get();        
    }

    public function create()
    {
    }

    public function store(Request $request)
    {
        if (! $request->name) {
            return ['status' => 'error', 'message' => 'Debe indicar el nombre'];
        }
        $data = Sector::create($request->all());

        //if ($request->operarios) {
            $this->updateOperators($data, $request->operarios);
        //}
        $this->updateMaterials($data, $request->materiales);

        return ['status' => 'succes', 'data' => Sector::with('operarios')->with('materiales')->with('supervisor')->find($data->id)];
    }

    public function show($id)
    {
    }

    public function edit($id)
    {
    }

    public function update(Request $request, $id)
    {
        $item = Sector::find($id);
        if (! $item) {
            return ['status' => 'error', 'message' => 'Registro No encontrado!'];
        }
        if (! $request->name) {
            return ['status' => 'error', 'message' => 'Debe indicar el nombre'];
        }

        $item->fill($request->all())->save();

        //if ($request->operarios) {
            $this->updateOperators($item, $request->operarios);
        //}
        $this->updateMaterials($item, $request->materiales);

        return ['status' => 'succes', 'data' => Sector::with('operarios')->with('materiales')->with('supervisor')->find($item->id)];
    }

    private function updateOperators($sector, $operators)
    {
        $model = new SectorOperario();
        $model->where('sector_id', $sector->id)->delete();
        foreach ($operators as $item) {
            $model->create([
                'sector_id' => $sector->id,
                'user_id' => $item['id']
            ]);   
        }
    }

    private function updateMaterials($sector, $materials)
    {
        $model = new MaterialSector();
        $model->where('sector_id', $sector->id)->delete();
        foreach ($materials as $item) {
            $model->create([
                'sector_id' => $sector->id,
                'material_id' => $item['id']
            ]);   
        }
    }

    public function destroy($id)
    {
        $item = Sector::find($id);
        (new SectorOperario)->where('sector_id', $item->id)->delete();
        (new MaterialSector)->where('sector_id', $item->id)->delete();
        $item->delete();

        return ['status' => 'succes', 'data' => $id];
    }
}
