<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Models\Patient;
use App\Models\User;
use App\Models\Visit;
use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function index(Request $request)
    {
        $this->authorize('viewAny', Invoice::class);

        $q = Invoice::query()->with(['patient', 'visit', 'doctor']);

        // Filter by status
        if ($status = $request->input('status')) {
            $q->where('payment_status', $status);
        }

        // Quick search
        if ($search = $request->input('q')) {
            $q->whereHas('patient', function ($query) use ($search) {
                $query->where('full_name', 'like', '%' . $search . '%')
                    ->orWhere('patient_code', 'like', '%' . $search . '%');
            })->orWhere('invoice_number', 'like', '%' . $search . '%');
        }

        $invoices = $q->latest()->paginate(15)->withQueryString();

        return view('invoices.index', compact('invoices'));
    }

    public function create(Request $request)
    {
        $this->authorize('create', Invoice::class);

        $patientId = $request->input('patient_id');
        $patient = null;
        if ($patientId) {
            $patient = Patient::findOrFail($patientId);
            $this->authorize('view', $patient);
        }

        $visitId = $request->input('visit_id');
        $visit = null;
        if ($visitId) {
            $visit = Visit::findOrFail($visitId);
            $this->authorize('view', $visit);
        }

        $patients = Patient::where('status', 'active')->orderBy('full_name')->get();
        $doctors = User::where('company_id', auth()->user()->company_id)->get();
        
        // Fetch only visits for this patient that don't have an invoice yet
        $visits = [];
        if ($patient) {
            $visits = Visit::where('patient_id', $patient->id)
                ->whereDoesntHave('invoice')
                ->latest()
                ->get();
        }

        return view('invoices.create', compact('patient', 'visit', 'patients', 'doctors', 'visits'));
    }

    public function store(Request $request)
    {
        $this->authorize('create', Invoice::class);

        $validated = $request->validate([
            'patient_id' => 'required|exists:patients,id',
            'visit_id' => 'nullable|exists:visits,id',
            'doctor_id' => 'nullable|exists:users,id',
            'consultation_price' => 'required|numeric|min:0',
            'services_total' => 'nullable|numeric|min:0',
            'discount' => 'nullable|numeric|min:0',
            'paid_amount' => 'required|numeric|min:0',
            'payment_method' => 'required|string|in:cash,wallet,card,bank_transfer',
            'notes' => 'nullable|string',
        ]);

        // Check tenancy
        $patient = Patient::findOrFail($validated['patient_id']);
        $this->authorize('view', $patient);

        if (!empty($validated['visit_id'])) {
            $visit = Visit::findOrFail($validated['visit_id']);
            $this->authorize('view', $visit);
        }

        $consultationPrice = (float) $validated['consultation_price'];
        $servicesTotal = (float) ($validated['services_total'] ?? 0.0);
        $discount = (float) ($validated['discount'] ?? 0.0);
        $paidAmount = (float) $validated['paid_amount'];

        $totalAmount = $consultationPrice + $servicesTotal - $discount;
        if ($totalAmount < 0) $totalAmount = 0.0;

        $remainingAmount = $totalAmount - $paidAmount;
        if ($remainingAmount < 0) $remainingAmount = 0.0;

        $paymentStatus = 'unpaid';
        if ($paidAmount > 0) {
            $paymentStatus = $remainingAmount <= 0 ? 'paid' : 'partial';
        }

        $invoice = Invoice::create([
            'patient_id' => $validated['patient_id'],
            'visit_id' => $validated['visit_id'] ?? null,
            'doctor_id' => $validated['doctor_id'] ?? null,
            'consultation_price' => $consultationPrice,
            'services_total' => $servicesTotal,
            'discount' => $discount,
            'total_amount' => $totalAmount,
            'paid_amount' => $paidAmount,
            'remaining_amount' => $remainingAmount,
            'payment_status' => $paymentStatus,
            'payment_method' => $validated['payment_method'],
            'notes' => $validated['notes'] ?? null,
        ]);

        return redirect()->route('patients.show', $invoice->patient_id)
            ->with('success', __('clinic.success_message'));
    }

    public function show(Invoice $invoice)
    {
        $this->authorize('view', $invoice);
        $invoice->load(['patient', 'visit', 'doctor']);
        return view('invoices.show', compact('invoice'));
    }
}
