<?php

namespace App\Http\Controllers\Tenant;

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

class PatientController extends Controller
{
    public function index(Request $request): View
    {
        $query = Customer::query()
            ->when($request->search, function ($q, $s) {
                $q->where(function ($q) use ($s) {
                    $q->where('first_name', 'like', "%{$s}%")
                      ->orWhere('last_name', 'like', "%{$s}%")
                      ->orWhere('document_number', 'like', "%{$s}%")
                      ->orWhere('phone', 'like', "%{$s}%")
                      ->orWhere('email', 'like', "%{$s}%");
                });
            })
            ->when($request->status, function ($q, $status) {
                $q->where('is_active', $status === 'active');
            })
            ->withCount(['bookings', 'clinicalEvolutions'])
            ->latest('updated_at')
            ->paginate(15)
            ->withQueryString();

        $stats = [
            'total'    => Customer::count(),
            'active'   => Customer::where('is_active', true)->count(),
            'with_hc'  => Customer::whereHas('clinicalHistory')->count(),
        ];

        return view('tenant.patients.index', compact('query', 'stats'));
    }

    public function show(Customer $patient): View
    {
        $patient->load([
            'clinicalHistory.backgrounds',
            'clinicalHistory.evolutions.employee',
            'clinicalHistory.evolutions.diagnoses',
            'clinicalHistory.prescriptions',
            'clinicalHistory.orders',
            'clinicalHistory.consents',
            'clinicalHistory.files',
            'clinicalHistory.notes',
        ]);

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

    public function create(): View
    {
        return view('tenant.patients.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'first_name'              => ['required', 'string', 'max:100'],
            'second_name'             => ['nullable', 'string', 'max:100'],
            'last_name'               => ['required', 'string', 'max:100'],
            'second_lastname'         => ['nullable', 'string', 'max:100'],
            'document_type'           => ['nullable', 'string', 'max:20'],
            'document_number'         => ['nullable', 'string', 'max:50'],
            'birthdate'               => ['nullable', 'date'],
            'gender'                  => ['nullable', 'in:male,female,other'],
            'phone'                   => ['required', 'string', 'max:25'],
            'email'                   => ['nullable', 'email', 'max:150'],
            'address'                 => ['nullable', 'string', 'max:255'],
            'city'                    => ['nullable', 'string', 'max:100'],
            'country'                 => ['nullable', 'string', 'max:100'],
            'blood_type'              => ['nullable', 'string', 'max:10'],
            'insurance_company'       => ['nullable', 'string', 'max:150'],
            'emergency_contact_name'  => ['nullable', 'string', 'max:150'],
            'emergency_contact_phone' => ['nullable', 'string', 'max:25'],
            'notes'                   => ['nullable', 'string'],
        ]);

        // Validate document uniqueness per company
        if (! empty($data['document_number'])) {
            $exists = Customer::where('document_number', $data['document_number'])->exists();
            if ($exists) {
                return back()->withErrors(['document_number' => 'Ya existe un paciente con ese documento en esta empresa.'])->withInput();
            }
        }

        $patient = Customer::create($data + ['is_active' => true]);

        // Auto-create clinical history
        $patient->clinicalHistory()->create([
            'opening_date' => now(),
            'history_number' => $this->generateHistoryNumber(),
            'created_by' => auth()->id(),
        ]);

        return redirect()->route('tenant.patients.show', $patient)
            ->with('success', 'Paciente registrado y historia clínica creada.');
    }

    public function edit(Customer $patient): View
    {
        return view('tenant.patients.edit', compact('patient'));
    }

    public function update(Request $request, Customer $patient): RedirectResponse
    {
        $data = $request->validate([
            'first_name'              => ['required', 'string', 'max:100'],
            'second_name'             => ['nullable', 'string', 'max:100'],
            'last_name'               => ['required', 'string', 'max:100'],
            'second_lastname'         => ['nullable', 'string', 'max:100'],
            'document_type'           => ['nullable', 'string', 'max:20'],
            'document_number'         => ['nullable', 'string', 'max:50'],
            'birthdate'               => ['nullable', 'date'],
            'gender'                  => ['nullable', 'in:male,female,other'],
            'phone'                   => ['required', 'string', 'max:25'],
            'email'                   => ['nullable', 'email', 'max:150'],
            'address'                 => ['nullable', 'string', 'max:255'],
            'city'                    => ['nullable', 'string', 'max:100'],
            'country'                 => ['nullable', 'string', 'max:100'],
            'blood_type'              => ['nullable', 'string', 'max:10'],
            'insurance_company'       => ['nullable', 'string', 'max:150'],
            'emergency_contact_name'  => ['nullable', 'string', 'max:150'],
            'emergency_contact_phone' => ['nullable', 'string', 'max:25'],
            'notes'                   => ['nullable', 'string'],
            'is_active'               => ['boolean'],
        ]);

        if (! empty($data['document_number']) && $data['document_number'] !== $patient->document_number) {
            $exists = Customer::where('document_number', $data['document_number'])
                ->where('id', '!=', $patient->id)
                ->exists();
            if ($exists) {
                return back()->withErrors(['document_number' => 'Ya existe un paciente con ese documento en esta empresa.'])->withInput();
            }
        }

        $patient->update($data);

        return back()->with('success', 'Datos del paciente actualizados.');
    }

    public function destroy(Customer $patient): RedirectResponse
    {
        $patient->update(['is_active' => false]);
        $patient->delete();

        return redirect()->route('tenant.patients.index')
            ->with('success', 'Paciente desactivado correctamente.');
    }

    private function generateHistoryNumber(): string
    {
        $prefix = 'HC';
        $year = now()->format('Y');
        $count = \App\Models\ClinicalHistory::withoutGlobalScopes()
            ->whereYear('created_at', $year)
            ->count() + 1;

        return sprintf('%s-%s-%05d', $prefix, $year, $count);
    }
}
