<?php

namespace App\Http\Controllers\Partner;

use App\Http\Controllers\Controller;
use App\Models\Loan;
use App\Models\Repayment;
use Illuminate\Http\Request;

class LoanDocumentController extends Controller
{
    public function sanctionLetter(Loan $loan)
    {
        $this->ensurePartnerOwnership($loan);
        $loan->load(['customer', 'loanScheme', 'scheme', 'partner']);
        return view('partner.loans.documents.sanction-letter', compact('loan'));
    }

    public function noc(Loan $loan)
    {
        $this->ensurePartnerOwnership($loan);
        $loan->load(['customer', 'loanScheme', 'scheme', 'partner']);
        return view('partner.loans.documents.noc', compact('loan'));
    }

    public function repaymentSlip(Repayment $repayment)
    {
        $this->ensurePartnerOwnership($repayment);
        $repayment->load(['loan.customer', 'loan.loanScheme', 'loan.scheme', 'loan.partner', 'customer']);
        return view('partner.loans.documents.repayment-slip', compact('repayment'));
    }

    private function ensurePartnerOwnership($model)
    {
        $partnerId = auth()->user()->partner_id;
        
        if ($model instanceof Loan) {
            if ($model->partner_id !== $partnerId) {
                abort(403);
            }
        } elseif ($model instanceof Repayment) {
            // Check via loan relationship
            $repayment = $model;
            $repayment->load('loan');
            if ($repayment->loan->partner_id !== $partnerId) {
                abort(403);
            }
        }
    }
}
