<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Loan;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoanController extends Controller
{
    public function index()
    {
        $loans = Loan::with(['user', 'approver'])
            ->orderBy('created_at', 'desc')
            ->paginate(20);

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

    public function create()
    {
        $users = User::whereHas('role', function($q) {
            $q->where('name', 'Sales Representative');
        })->get();

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

    public function store(Request $request)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'total_amount' => 'required|numeric|min:0',
            'total_installments' => 'required|integer|min:1',
            'loan_date' => 'required|date',
            'start_deduction_date' => 'required|date',
            'purpose' => 'nullable|string',
        ]);

        $monthlyInstallment = round($request->total_amount / $request->total_installments, 2);

        Loan::create([
            'user_id' => $request->user_id,
            'total_amount' => $request->total_amount,
            'monthly_installment' => $monthlyInstallment,
            'total_installments' => $request->total_installments,
            'remaining_amount' => $request->total_amount,
            'loan_date' => $request->loan_date,
            'start_deduction_date' => $request->start_deduction_date,
            'purpose' => $request->purpose,
            'approved_by' => Auth::id(),
            'status' => 'active',
        ]);

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

    public function show($id)
    {
        $loan = Loan::with(['user', 'approver'])->findOrFail($id);
        return view('admin.loans.show', compact('loan'));
    }

    public function edit($id)
    {
        $loan = Loan::findOrFail($id);
        $users = User::whereHas('role', function($q) {
            $q->where('name', 'Sales Representative');
        })->get();

        return view('admin.loans.edit', compact('loan', 'users'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'total_amount' => 'required|numeric|min:0',
            'total_installments' => 'required|integer|min:1',
            'loan_date' => 'required|date',
            'start_deduction_date' => 'required|date',
            'purpose' => 'nullable|string',
        ]);

        $loan = Loan::findOrFail($id);
        
        $monthlyInstallment = round($request->total_amount / $request->total_installments, 2);
        
        // Recalculate remaining amount
        $paidAmount = $loan->paid_installments * $monthlyInstallment;
        $remainingAmount = $request->total_amount - $paidAmount;

        $loan->update([
            'total_amount' => $request->total_amount,
            'monthly_installment' => $monthlyInstallment,
            'total_installments' => $request->total_installments,
            'remaining_amount' => max(0, $remainingAmount),
            'loan_date' => $request->loan_date,
            'start_deduction_date' => $request->start_deduction_date,
            'purpose' => $request->purpose,
        ]);

        return redirect()->route('admin.loans.index')
            ->with('success', 'Loan updated successfully');
    }

    public function destroy($id)
    {
        $loan = Loan::findOrFail($id);
        
        if ($loan->paid_installments > 0) {
            return back()->with('error', 'Cannot delete a loan that has started repayment');
        }

        $loan->delete();

        return redirect()->route('admin.loans.index')
            ->with('success', 'Loan deleted successfully');
    }

    public function cancel($id)
    {
        $loan = Loan::findOrFail($id);
        $loan->status = 'cancelled';
        $loan->save();

        return back()->with('success', 'Loan cancelled successfully');
    }
}
