<?php

namespace App\Http\Controllers\Invoices;

use App\Http\Controllers\Controller;
use App\Models\Invoices;
use App\Models\Payments;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PaymentController extends Controller
{
    public function store(Request $request)
    {
        $user = Auth::user();

        $data = $request->validate([
            'invoice_id'     => ['required', 'integer', 'exists:invoices,id'],
            'amount'         => ['required', 'numeric', 'min:0.01'],
            'payment_method' => ['required', 'in:cash,card,bank_transfer,online'],
            'transaction_id' => ['nullable', 'string', 'max:255'],
            'notes'          => ['nullable', 'string', 'max:1000'],
        ], [
            'invoice_id.required' => 'الفاتورة مطلوبة.',
            'amount.required'     => 'برجاء إدخال قيمة المبلغ.',
            'amount.min'          => 'قيمة المبلغ يجب أن تكون أكبر من صفر.',
        ]);

        $invoice = Invoices::where('clinic_id', $user->clinic_id)
            ->findOrFail($data['invoice_id']);

        $remaining = max($invoice->total - $invoice->paid_amount, 0);

        if ($remaining <= 0) {
            return back()->with('error', 'لا يوجد مبلغ متبقي على الفاتورة.')->withInput();
        }

        $amount = (float) $data['amount'];

        if ($amount > $remaining) {
            return back()->with('error', 'قيمة الدفعة لا يمكن أن تتجاوز المتبقي على الفاتورة.')->withInput();
        }

        Payments::create([
            'invoice_id'     => $invoice->id,
            'amount'         => $amount,
            'payment_method' => $data['payment_method'],
            'transaction_id' => $data['transaction_id'] ?? null,
            'paid_at'        => now(),
            'notes'          => $data['notes'] ?? null,
        ]);

        $totalPaid = Payments::where('invoice_id', $invoice->id)->sum('amount');

        $invoice->paid_amount = $totalPaid;

        if ($totalPaid <= 0) {
            $invoice->status = 'unpaid';
        } elseif ($totalPaid < $invoice->total) {
            $invoice->status = 'partial';
        } else {
            $invoice->status = 'paid';
        }

        $invoice->save();

        return back()->with('success', 'تم تسجيل الدفعة بنجاح.');
    }
}
