<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WorkCenterController extends Controller
{
    public function index()
    {
        $workcenters = DB::table('work_centers')
            ->orderBy('name')
            ->paginate(20);

        return view('manufacturing.workcenters.index', compact('workcenters'));
    }

    public function create()
    {
        return view('manufacturing.workcenters.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|unique:work_centers,code',
            'capacity' => 'required|numeric|min:0.1',
        ]);

        DB::table('work_centers')->insert([
            'name' => $request->name,
            'code' => $request->code,
            'capacity' => $request->capacity,
            'time_efficiency' => $request->time_efficiency ?? 100,
            'costs_hour' => $request->costs_hour ?? 0,
            'active' => $request->has('active'),
            'color' => $request->color ?? 0,
            'created_at' => now(),
        ]);

        return redirect()->route('manufacturing.workcenters')
            ->with('success', 'Work center created successfully!');
    }

    public function edit($id)
    {
        $workcenter = DB::table('work_centers')->where('id', $id)->first();
        
        if (!$workcenter) {
            return redirect()->route('manufacturing.workcenters')->with('error', 'Work center not found.');
        }

        return view('manufacturing.workcenters.edit', compact('workcenter'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'capacity' => 'required|numeric|min:0.1',
        ]);

        DB::table('work_centers')->where('id', $id)->update([
            'name' => $request->name,
            'capacity' => $request->capacity,
            'time_efficiency' => $request->time_efficiency ?? 100,
            'costs_hour' => $request->costs_hour ?? 0,
            'active' => $request->has('active'),
            'color' => $request->color ?? 0,
        ]);

        return redirect()->route('manufacturing.workcenters')
            ->with('success', 'Work center updated successfully!');
    }
}