<?php

namespace App\Http\Controllers;

use App\Models\Processing;
use App\Models\Cost;
use Illuminate\Http\Request;

class ProcessingController extends Controller
{
    public function index()
    {
        $processings = Processing::with('costs')->get();

        foreach ($processings as $processing) {
            $processing->total_cost = $processing->costs->sum('price');
        }
        return view('processing.index', compact('processings'));
    }

    public function create()
    {
        return view('processing.add');
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'diameter_type' => 'required|in:any,specific',
            'costs.*.name' => 'required|string|max:255',
            'costs.*.price' => 'required|numeric|min:0',
        ]);

        $processing = new Processing();
        $processing->name = $validatedData['name'];
        $processing->diameter_type = $validatedData['diameter_type'];
        $processing->specific_diameter = $request['specific_diameter'] ?? null;
        $processing->save();

        foreach ($validatedData['costs'] as $costData) {
            $cost = new Cost();
            $cost->name = $costData['name'];
            $cost->price = $costData['price'];
            $processing->costs()->save($cost);
        }
        $processing->total_cost = $processing->costs->sum('price');
        $processing->save();


        return redirect()->route('processing.index')->with('success', 'Processing created successfully.');
    }

    public function edit(Processing $processing)
    {
        return view('processing.edit', compact('processing'));
    }

    public function update(Request $request, Processing $processing)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'diameter_type' => 'required|in:any,specific',
            'costs.*.name' => 'required|string|max:255',
            'costs.*.price' => 'required|numeric|min:0',
        ]);

        $processing->name = $validatedData['name'];
        $processing->diameter_type = $validatedData['diameter_type'];
        $processing->specific_diameter = $request['specific_diameter'] ?? null;
        $processing->save();

        $processing->costs()->delete();
        foreach ($validatedData['costs'] as $costData) {
            $cost = new Cost();
            $cost->name = $costData['name'];
            $cost->price = $costData['price'];
            $processing->costs()->save($cost);
        }
        $processing->total_cost = $processing->costs->sum('price');
        $processing->save();
        return redirect()->route('processing.index')->with('success', 'Processing updated successfully.');
    }

    public function destroy(Processing $processing)
    {
        $processing->delete();
        return redirect()->route('processing.index');
    }
}

