<?php

namespace App\Http\Controllers;

use App\Models\ContractConfig;
use App\Models\ContractType;
use App\Models\Segment;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ContractConfigController extends Controller
{
    public function index()
    {
        return Inertia::render('Settings/ContractConfigs/Index', [
            'configs' => ContractConfig::with(['type:id,name', 'segment:id,name'])->get(),
            'types' => ContractType::query()->get(['id', 'name']),
            'segments' => Segment::query()->where('active', true)->get(['id', 'name']),
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'contract_type_id' => ['required', 'integer', 'exists:contract_types,id'],
            'segment_id' => ['required', 'integer', 'exists:segments,id'],
            'is_initial' => ['sometimes', 'boolean'],
            'active' => ['sometimes', 'boolean'],
        ]);

        // Prevent duplicates for same type/segment
        $exists = ContractConfig::query()
            ->where('contract_type_id', $data['contract_type_id'])
            ->where('segment_id', $data['segment_id'])
            ->exists();
        if ($exists) {
            return back()->withErrors(['segment_id' => 'This segment is already configured for the selected type.']);
        }

        ContractConfig::create([
            'contract_type_id' => $data['contract_type_id'],
            'segment_id' => $data['segment_id'],
            'is_initial' => (bool) ($data['is_initial'] ?? false),
            'active' => (bool) ($data['active'] ?? true),
        ]);

        return back()->with('success', 'Configuration created');
    }

    public function update(ContractConfig $config, Request $request)
    {
        $data = $request->validate([
            'segment_id' => ['required', 'integer', 'exists:segments,id'],
            'is_initial' => ['sometimes', 'boolean'],
            'active' => ['sometimes', 'boolean'],
        ]);

        $config->update([
            'segment_id' => $data['segment_id'],
            'is_initial' => (bool) ($data['is_initial'] ?? $config->is_initial),
            'active' => (bool) ($data['active'] ?? $config->active),
        ]);

        return back()->with('success', 'Configuration updated');
    }

    public function destroy(ContractConfig $config)
    {
        $config->delete();

        return back()->with('success', 'Configuration deleted');
    }
}
