<?php

namespace App\Http\Controllers;

use App\Models\Loan;
use App\Models\Employee;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class LoanController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $query = Loan::with(['employee', 'manager'])->latest();

        $employee = $user->employee;
        if ($user->is_admin || $user->hasRole('systemadmin') || $user->hasRole('superadmin')) {
            // Admins: see all (and they handle 'hr_admin' approvals)
        } elseif ($employee && Employee::where('manager_id', $employee->id)->exists()) {
            // Managers: see own loans AND subordinate loans where authority is manager
            $subordinateIds = Employee::where('manager_id', $employee->id)->pluck('id');
            $query->where(function($q) use ($employee, $subordinateIds) {
                $q->where('employee_id', $employee->id)
                  ->orWhere(function($subQ) use ($subordinateIds) {
                      $subQ->whereIn('employee_id', $subordinateIds)
                           ->whereHas('employee', function($eQ) {
                               $eQ->where('loan_approval_authority', 'manager')
                                  ->orWhereNull('loan_approval_authority');
                           });
                  });
            });
        } else {
            // Normal user: see own loans
            if ($employee) {
                $query->where('employee_id', $employee->id);
            } else {
                $query->whereRaw('1=0');
            }
        }

        $loans = $query->paginate(15);
        return view('loans.index', compact('loans'));
    }
    
    public function create()
    {
        $user = Auth::user();
        $employee = $user->employee;
        if (! $employee) {
            abort(403);
        }
        return view('loans.create', compact('employee'));
    }
    
    public function store(Request $request)
    {
        $user = Auth::user();
        $employee = $user->employee;
        if (! $employee) {
            abort(403);
        }

        $request->validate([
            'amount' => 'required|numeric|min:1',
            'term_months' => 'required|integer|min:1',
            'reason' => 'nullable|string',
        ]);

        $monthly = round(($request->amount / $request->term_months), 2);
        $managerId = $employee->manager_id;

        $loan = Loan::create([
            'employee_id' => $employee->id,
            'amount' => $request->amount,
            'term_months' => $request->term_months,
            'monthly_installment' => $monthly,
            'reason' => $request->reason,
            'status' => 'pending',
            'manager_id' => $managerId,
            'applied_at' => Carbon::now(),
        ]);

        return redirect()->route('loans.index')->with('success', 'Loan request submitted.');
    }
    
    public function show(Loan $loan)
    {
        $loan->load(['employee', 'manager']);
        return view('loans.show', compact('loan'));
    }

    public function edit(Loan $loan)
    {
        abort(404);
    }

    public function update(Request $request, Loan $loan)
    {
        abort(404);
    }
    
    public function destroy(Loan $loan)
    {
        $user = Auth::user();
        if (! $user->is_admin && ! $user->hasRole('systemadmin') && ! $user->hasRole('superadmin')) {
            abort(403);
        }
        $loan->delete();
        return redirect()->route('loans.index')->with('success', 'Loan deleted.');
    }
    
    public function approve(Loan $loan)
    {
        $user = Auth::user();
        $employee = $user->employee;
        if (! $employee || $loan->manager_id !== $employee->id) {
            abort(403);
        }

        $approvedAt = Carbon::now();
        $startDate = $approvedAt->copy()->startOfMonth();
        if ($approvedAt->day > 1) {
            $startDate = $startDate->addMonth();
        }
        $endDate = $startDate->copy()->addMonths($loan->term_months)->subDay();

        $loan->update([
            'status' => 'approved',
            'approved_at' => $approvedAt,
            'start_date' => $startDate->toDateString(),
            'end_date' => $endDate->toDateString(),
            'remaining_balance' => $loan->amount,
            'remaining_months' => $loan->term_months,
        ]);
        return redirect()->route('loans.index')->with('success', 'Loan approved.');
    }

    public function reject(Loan $loan)
    {
        $user = Auth::user();
        $employee = $user->employee;
        if (! $employee || $loan->manager_id !== $employee->id) {
            abort(403);
        }
        $loan->update([
            'status' => 'rejected',
            'approved_at' => null,
        ]);
        return redirect()->route('loans.index')->with('success', 'Loan rejected.');
    }
}
