<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreFieldJobSettingRequest;
use App\Http\Requests\UpdateFieldJobSettingRequest;
use App\Models\Decision;
use App\Models\FieldJobSetting;
use App\Models\Segment;
use Illuminate\Http\Request;
use Inertia\Inertia;

class FieldJobSettingController extends Controller
{
    public function index(Request $request)
    {
        $settings = FieldJobSetting::query()
            ->with(['action', 'segment', 'initialDecision', 'assignDecision', 'completeDecision', 'cancelDecision', 'returnSegment', 'queueSegment'])
            ->get();

        return Inertia::render('Settings/FieldJob/Index', [
            'settings' => $settings,
            'segments' => Segment::query()->get(),
            'actions' => \App\Models\Action::query()->with(['decisions:id'])->get(),
            'decisions' => Decision::query()->with(['actions:id'])->get(),
        ]);
    }

    public function store(StoreFieldJobSettingRequest $request)
    {
        $attributes = $request->validated();

        FieldJobSetting::create([
            'segment_id' => $attributes['segment_id'],
            'initial_decision_id' => $attributes['initial_decision_id'],
            'assign_decision_id' => $attributes['assign_decision_id'],
            'complete_decision_id' => $attributes['complete_decision_id'],
            'action_id' => $attributes['action_id'] ?? null,
            'cancel_decision_id' => $attributes['cancel_decision_id'] ?? null,
            'return_segment_id' => $attributes['return_segment_id'] ?? null,
            'queue_segment_id' => $attributes['queue_segment_id'] ?? null,
        ]);

        return to_route('settings.fieldjob.index')->with('success', 'Field job setting created successfully!');
    }

    public function update(FieldJobSetting $setting, UpdateFieldJobSettingRequest $request)
    {
        $attributes = $request->validated();

        $setting->update([
            'segment_id' => $attributes['segment_id'],
            'initial_decision_id' => $attributes['initial_decision_id'],
            'assign_decision_id' => $attributes['assign_decision_id'],
            'complete_decision_id' => $attributes['complete_decision_id'],
            'cancel_decision_id' => $attributes['cancel_decision_id'] ?? null,
            'return_segment_id' => $attributes['return_segment_id'] ?? null,
            'queue_segment_id' => $attributes['queue_segment_id'] ?? null,
            'action_id' => $attributes['action_id'] ?? null,
        ]);

        return to_route('settings.fieldjob.index')->with('success', 'Field job setting updated successfully!');
    }
}
