<?php

namespace App\Http\Controllers\Admin;

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

class FinancingController extends Controller
{
    public function index(Request $request)
    {
        $query = FinancingApplication::query();

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('type')) {
            $query->where('application_type', $request->type);
        }
        if ($request->filled('search')) {
            $search = '%' . $request->search . '%';
            $query->where(function($q) use ($search) {
                $q->where('first_name', 'like', $search)
                  ->orWhere('last_name', 'like', $search)
                  ->orWhere('email', 'like', $search);
            });
        }

        $applications = $query->latest()->paginate(10);

        return view('admin.financing.index', compact('applications'));
    }

    public function show($id)
    {
        $application = FinancingApplication::findOrFail($id);
        return view('admin.financing.show', compact('application'));
    }

    public function updateStatus(Request $request, $id)
    {
        $application = FinancingApplication::findOrFail($id);
        $request->validate(['status' => 'required|in:pending,reviewing,approved,rejected']);
        
        $application->update([
            'status' => $request->status,
            'admin_notes' => $request->admin_notes
        ]);
        
        return back()->with('success', 'Application status updated successfully.');
    }

    public function destroy($id)
    {
        $application = FinancingApplication::findOrFail($id);
        $application->delete();
        
        return redirect()->route('admin.financing.index')->with('success', 'Application deleted.');
    }
}
