<?php

namespace App\Http\Controllers\Membership\Admin;

use App\Http\Controllers\Controller;
use App\Models\LoanProduct;
use App\Models\LoanApplication;
use App\Models\LoanDocument;
use App\Services\LoanService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class LoanProductController extends Controller
{
    protected LoanService $loanService;

    public function __construct(LoanService $loanService)
    {
        $this->loanService = $loanService;
    }

    /**
     * Display all loan products.
     */
    public function index()
    {
        abort_unless(auth()->user()->can('view loan products'), 403);

        $products = LoanProduct::withCount('loanApplications')
            ->ordered()
            ->get();

        return view('loans.admin.products.index', compact('products'));
    }

    /**
     * Show form to create a new loan product.
     */
    public function create()
    {
        abort_unless(auth()->user()->can('create loan products'), 403);

        $categories = \App\Models\MembershipCategory::active()->get();

        return view('loans.admin.products.create', compact('categories'));
    }

    /**
     * Store a new loan product.
     */
    public function store(Request $request)
    {
        abort_unless(auth()->user()->can('create loan products'), 403);

        $request->validate([
            'name' => 'required|string|max:191|unique:loan_products,name',
            'description' => 'nullable|string|max:5000',
            'terms_and_conditions' => 'nullable|string|max:10000',
            'interest_type' => 'required|in:fixed,reducing_balance,flat_rate',
            'interest_rate' => 'required|numeric|min:0|max:100',
            'interest_rate_display' => 'nullable|string|max:50',
            'min_amount' => 'required|numeric|min:0',
            'max_amount' => 'required|numeric|gt:min_amount',
            'default_amount' => 'nullable|numeric|min:0',
            'currency' => 'required|in:USD,SSP,KES,UGX',
            'min_term_months' => 'required|integer|min:1',
            'max_term_months' => 'required|integer|gte:min_term_months',
            'default_term_months' => 'nullable|integer|min:1',
            'processing_fee' => 'nullable|numeric|min:0',
            'processing_fee_percentage' => 'nullable|numeric|min:0|max:100',
            'late_payment_penalty' => 'nullable|numeric|min:0',
            'is_active' => 'nullable|boolean',
            'is_featured' => 'nullable|boolean',
            'requires_collateral' => 'nullable|boolean',
            'requires_guarantor' => 'nullable|boolean',
            'min_guarantors' => 'nullable|integer|min:0',
            'min_membership_months' => 'nullable|integer|min:0',
            'min_contribution_balance' => 'nullable|numeric|min:0',
            'theme_color' => 'nullable|string|max:50',
            'icon' => 'nullable|string|max:100',
        ], [
            'name.required' => 'Product name is required.',
            'name.unique' => 'A product with this name already exists.',
            'interest_rate.required' => 'Interest rate is required.',
            'min_amount.required' => 'Minimum amount is required.',
            'max_amount.required' => 'Maximum amount is required.',
            'max_amount.gt' => 'Maximum amount must be greater than minimum amount.',
        ]);

        $validated = $request->all();
        $validated['name'] = strip_tags($validated['name']);
        $validated['slug'] = Str::slug($validated['name']);
        $validated['created_by'] = auth()->id();
        $validated['eligible_categories'] = $request->eligible_categories ?? null;
        // Normalise checkbox booleans (unchecked = not sent = false)
        $validated['is_active']           = $request->boolean('is_active');
        $validated['is_featured']         = $request->boolean('is_featured');
        $validated['requires_collateral'] = $request->boolean('requires_collateral');
        $validated['requires_guarantor']  = $request->boolean('requires_guarantor');

        LoanProduct::create($validated);

        return redirect()->route('admin.loan-products.index')
            ->with('success', 'Loan product created successfully.');
    }

    /**
     * Display loan product details.
     */
    public function show(LoanProduct $loanProduct)
    {
        abort_unless(auth()->user()->can('view loan products'), 403);

        $loanProduct->loadCount('loanApplications');
        $statistics = [
            'total_applications' => $loanProduct->loanApplications()->count(),
            'approved' => $loanProduct->loanApplications()->whereIn('status', ['approved', 'disbursed', 'active'])->count(),
            'pending' => $loanProduct->loanApplications()->pending()->count(),
            'total_disbursed' => $loanProduct->loanApplications()->whereIn('status', ['disbursed', 'active', 'completed'])->sum('amount_disbursed'),
        ];

        return view('loans.admin.products.show', compact('loanProduct', 'statistics'));
    }

    /**
     * Show form to edit a loan product.
     */
    public function edit(LoanProduct $loanProduct)
    {
        abort_unless(auth()->user()->can('edit loan products'), 403);

        $categories = \App\Models\MembershipCategory::active()->get();

        return view('loans.admin.products.edit', compact('loanProduct', 'categories'));
    }

    /**
     * Update a loan product.
     */
    public function update(Request $request, LoanProduct $loanProduct)
    {
        abort_unless(auth()->user()->can('edit loan products'), 403);

        $request->validate([
            'name' => 'required|string|max:191|unique:loan_products,name,' . $loanProduct->id,
            'description' => 'nullable|string|max:5000',
            'terms_and_conditions' => 'nullable|string|max:10000',
            'interest_type' => 'required|in:fixed,reducing_balance,flat_rate',
            'interest_rate' => 'required|numeric|min:0|max:100',
            'interest_rate_display' => 'nullable|string|max:50',
            'min_amount' => 'required|numeric|min:0',
            'max_amount' => 'required|numeric|gt:min_amount',
            'default_amount' => 'nullable|numeric|min:0',
            'currency' => 'required|in:USD,SSP,KES,UGX',
            'min_term_months' => 'required|integer|min:1',
            'max_term_months' => 'required|integer|gte:min_term_months',
            'default_term_months' => 'nullable|integer|min:1',
            'processing_fee' => 'nullable|numeric|min:0',
            'processing_fee_percentage' => 'nullable|numeric|min:0|max:100',
            'late_payment_penalty' => 'nullable|numeric|min:0',
            'is_active' => 'nullable|boolean',
            'is_featured' => 'nullable|boolean',
            'requires_collateral' => 'nullable|boolean',
            'requires_guarantor' => 'nullable|boolean',
            'min_guarantors' => 'nullable|integer|min:0',
            'min_membership_months' => 'nullable|integer|min:0',
            'min_contribution_balance' => 'nullable|numeric|min:0',
            'theme_color' => 'nullable|string|max:50',
            'icon' => 'nullable|string|max:100',
        ]);

        $validated = $request->all();
        $validated['name'] = strip_tags($validated['name']);
        $validated['slug'] = Str::slug($validated['name']);
        $validated['eligible_categories'] = $request->eligible_categories ?? null;
        // Normalise checkbox booleans (unchecked = not sent = false)
        $validated['is_active']           = $request->boolean('is_active');
        $validated['is_featured']         = $request->boolean('is_featured');
        $validated['requires_collateral'] = $request->boolean('requires_collateral');
        $validated['requires_guarantor']  = $request->boolean('requires_guarantor');

        $loanProduct->update($validated);

        return redirect()->route('admin.loan-products.show', $loanProduct)
            ->with('success', 'Loan product updated successfully.');
    }

    /**
     * Delete a loan product.
     */
    public function destroy(LoanProduct $loanProduct)
    {
        abort_unless(auth()->user()->can('delete loan products'), 403);

        if ($loanProduct->loanApplications()->exists()) {
            return redirect()->back()
                ->withErrors(['error' => 'Cannot delete product with existing applications.']);
        }

        $loanProduct->delete();

        return redirect()->route('admin.loan-products.index')
            ->with('success', 'Loan product deleted.');
    }
}
