<?php

namespace App\Http\Controllers;

use App\Models\Contract;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Inertia\Inertia;

class ContractController extends Controller
{
    public function index(Contract $contract)
    {
        return Inertia::render('Contract/Index', [
            'contracts' => $contract::with(['type', 'debtor'])
                ->where('active', 1)
                ->orderByDesc('created_at')
                ->paginate(10),
            'person_types' => \App\Models\Person\PersonType::all(['id', 'name', 'description'])
                ->where('deleted', 0),
        ]);
    }

    public function show(Contract $contract)
    {
        return inertia('Contract/Show', [
            'contract' => $contract::with(['type', 'client', 'debtor'])->findOrFail($contract->id),
        ]);
    }

    public function store(Request $request)
    {
        $uuid = $request->input('client_case_uuid');

        $clientCase = \App\Models\ClientCase::where('uuid', $uuid)->firstOrFail();

        if (isset($clientCase->id)) {

            \DB::transaction(function () use ($request, $clientCase) {

                // Create contract
                $clientCase->contracts()->create([
                    'reference' => $request->input('reference'),
                    'start_date' => date('Y-m-d', strtotime($request->input('start_date'))),
                    'type_id' => $request->input('type_id'),
                ]);

            });
        }

        return back()->with('success', 'Contract created')->with('flash_method', 'POST');
    }

    public function update(Contract $contract, Request $request)
    {
        $contract->update([
            'referenca' => $request->input('referenca'),
            'type_id' => $request->input('type_id'),
        ]);

    }

    public function segment(Request $request)
    {
        $data = $request->validate([
            'segment_id' => ['required', 'integer', Rule::exists('segments', 'id')->where('active', true)],
            'contracts' => ['required', 'array', 'min:1'],
            'contracts.*' => ['string', Rule::exists('contracts', 'uuid')],
        ]);

        $segmentId = (int) $data['segment_id'];
        $uuids = array_values($data['contracts']);

        $contracts = Contract::query()
            ->whereIn('uuid', $uuids)
            ->get(['id', 'client_case_id']);

        DB::transaction(function () use ($contracts, $segmentId) {
            foreach ($contracts as $contract) {
                // Ensure the segment is attached to the client case and active
                $attached = DB::table('client_case_segment')
                    ->where('client_case_id', $contract->client_case_id)
                    ->where('segment_id', $segmentId)
                    ->first();

                if (! $attached) {
                    DB::table('client_case_segment')->insert([
                        'client_case_id' => $contract->client_case_id,
                        'segment_id' => $segmentId,
                        'active' => true,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                } elseif (! $attached->active) {
                    DB::table('client_case_segment')
                        ->where('id', $attached->id)
                        ->update(['active' => true, 'updated_at' => now()]);
                }

                // Deactivate all current contract segments
                DB::table('contract_segment')
                    ->where('contract_id', $contract->id)
                    ->update(['active' => false, 'updated_at' => now()]);

                // Activate or attach the target segment
                $pivot = DB::table('contract_segment')
                    ->where('contract_id', $contract->id)
                    ->where('segment_id', $segmentId)
                    ->first();

                if ($pivot) {
                    DB::table('contract_segment')
                        ->where('id', $pivot->id)
                        ->update(['active' => true, 'updated_at' => now()]);
                } else {
                    DB::table('contract_segment')->insert([
                        'contract_id' => $contract->id,
                        'segment_id' => $segmentId,
                        'active' => true,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }
        });

        return back()->with('success', __('Pogodbe so bile preusmerjene v izbrani segment.'));
    }
}
