<?php

namespace App\Http\Controllers\SchoolAdmin\Finance;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Payment;
use App\Models\Invoice;
use App\Models\Student;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class PaymentController extends Controller
{
    public function index()
    {
        $payments = Payment::with(['student', 'invoice'])
            ->where('school_id', Auth::user()->school_id)
            ->latest()
            ->paginate(20);
        return view('schooladmin.finance.payments.index', compact('payments'));
    }

    public function create(Request $request)
    {
        $invoice = null;
        if ($request->has('invoice_id')) {
            $invoice = Invoice::with('student')->where('school_id', Auth::user()->school_id)->findOrFail($request->invoice_id);
        }

        $invoices = Invoice::with('student')
            ->where('school_id', Auth::user()->school_id)
            ->where('status', '!=', 'paid')
            ->get();

        return view('schooladmin.finance.payments.create', compact('invoice', 'invoices'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'invoice_id' => 'required|exists:invoices,id',
            'amount' => 'required|numeric|min:0.01',
            'payment_method' => 'required|string|in:cash,bank,mobile_money',
            'reference_number' => 'nullable|string',
            'payment_date' => 'required|date',
        ]);

        $invoice = Invoice::where('school_id', Auth::user()->school_id)->findOrFail($request->invoice_id);
        
        if ($request->amount > $invoice->balance()) {
            return back()->with('error', 'Payment amount exceeds the outstanding balance (KES ' . number_format($invoice->balance(), 2) . ').');
        }

        try {
            DB::beginTransaction();

            $payment = Payment::create([
                'school_id' => Auth::user()->school_id,
                'student_id' => $invoice->student_id,
                'invoice_id' => $invoice->id,
                'amount' => $request->amount,
                'payment_method' => $request->payment_method,
                'reference_number' => $request->reference_number,
                'payment_date' => $request->payment_date,
                'recorded_by' => Auth::id(),
            ]);

            // Update Invoice
            $invoice->paid_amount += $request->amount;
            
            if ($invoice->paid_amount >= $invoice->total_amount) {
                $invoice->status = 'paid';
            } else {
                $invoice->status = 'partial';
            }
            $invoice->save();

            DB::commit();
            return redirect()->route('schooladmin.finance.payments.index')->with('success', 'Payment recorded successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Error recording payment: ' . $e->getMessage());
        }
    }

    public function show(Payment $payment)
    {
        $payment->load(['student', 'invoice', 'recorder']);
        return view('schooladmin.finance.payments.show', compact('payment'));
    }
}
