<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\ClinicalOrder;
use App\Models\Customer;
use App\Models\Employee;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ClinicalOrderController extends Controller
{
    public function create(Customer $patient): View
    {
        $employees = Employee::where('is_active', true)->get();
        $types = ClinicalOrder::$types;

        return view('tenant.orders.create', compact('patient', 'employees', 'types'));
    }

    public function store(Request $request, Customer $patient): RedirectResponse
    {
        $history = $patient->clinicalHistory()->firstOrCreate([], ['created_by' => auth()->id()]);

        $data = $request->validate([
            'employee_id'   => ['nullable', 'exists:employees,id'],
            'evolution_id'  => ['nullable', 'exists:clinical_evolutions,id'],
            'type'          => ['required', 'in:' . implode(',', array_keys(ClinicalOrder::$types))],
            'title'         => ['required', 'string', 'max:255'],
            'description'   => ['nullable', 'string'],
            'notes'         => ['nullable', 'string'],
        ]);

        $order = $history->orders()->create([
            'company_id'            => $history->company_id,
            'customer_id'           => $patient->id,
            'clinical_evolution_id' => $data['evolution_id'] ?? null,
            'employee_id'           => $data['employee_id'] ?? null,
            'type'                  => $data['type'],
            'title'                 => $data['title'],
            'description'           => $data['description'] ?? null,
            'notes'                 => $data['notes'] ?? null,
            'status'                => 'draft',
            'created_by'            => auth()->id(),
        ]);

        return redirect()->route('tenant.orders.show', [$patient, $order])
            ->with('success', 'Orden registrada.');
    }

    public function show(Customer $patient, ClinicalOrder $order): View
    {
        abort_unless($order->customer_id === $patient->id, 404);
        $order->load(['employee.user', 'signer']);

        return view('tenant.orders.show', compact('patient', 'order'));
    }

    public function sign(Customer $patient, ClinicalOrder $order): RedirectResponse
    {
        abort_unless($order->customer_id === $patient->id, 404);
        abort_if($order->isSigned(), 403, 'La orden ya está firmada.');

        $order->update([
            'status'    => 'signed',
            'signed_at' => now(),
            'signed_by' => auth()->id(),
        ]);

        activity()->causedBy(auth()->user())->performedOn($order)->log('Orden clínica firmada');

        return back()->with('success', 'Orden firmada correctamente.');
    }

    public function index(Customer $patient): View
    {
        $orders = $patient->clinicalOrders()
            ->with(['employee.user'])
            ->latest()
            ->paginate(10);

        $types = ClinicalOrder::$types;

        return view('tenant.orders.index', compact('patient', 'orders', 'types'));
    }
}
