<?php

namespace App\Http\Controllers;

use App\Models\Loan;
use App\Models\RemotePaymentSubmission;
use App\Services\AuditService;
use App\Services\BranchContext;
use App\Services\RemotePaymentService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class PublicRemotePaymentController extends Controller
{
    public function create(): View
    {
        return view('remote-payments.public-submit');
    }

    public function store(Request $request, RemotePaymentService $service, BranchContext $context): RedirectResponse
    {
        $data=$request->validate([
            'loan_number'=>['required','string','max:100'],
            'customer_phone'=>['required','string','max:50'],
            'amount'=>['required','decimal:0,2','min:0.01'],
            'payment_channel'=>['required',Rule::in(RemotePaymentSubmission::CHANNELS)],
            'transaction_reference'=>['required','string','max:150'],
            'proof'=>['required','file','mimes:pdf,jpg,jpeg,png,webp','max:10240'],
            'notes'=>['nullable','string','max:2000'],
        ]);

        $loan=$context->systemWide(fn () => Loan::query()
            ->with(['customer','branch'])
            ->where('status','active')
            ->where('loan_number',trim($data['loan_number']))
            ->first());

        if(!$loan || $this->digits($loan->customer->phone)!==$this->digits($data['customer_phone'])) {
            throw ValidationException::withMessages(['loan_number'=>'The loan details could not be verified. Check the loan number and registered customer phone.']);
        }

        $submission=$context->forBranch((int)$loan->branch_id,function () use ($service,$loan,$data): RemotePaymentSubmission {
            $submission=$service->submit($loan,(string)$data['amount'],$data['payment_channel'],$data['transaction_reference'],$data['proof'],$data['notes'] ?? null,'customer');
            AuditService::record('remote_payment.customer_submitted',$submission,[],[
                'submission_number'=>$submission->submission_number,'loan_id'=>$submission->loan_id,'amount'=>(string)$submission->amount,
                'channel'=>$submission->payment_channel,'transaction_reference'=>$submission->transaction_reference,'source'=>'customer',
            ],$submission->branch_id);

            return $submission;
        });

        return redirect()->route('remote-payments.public.create')->with('status','Payment evidence received. Reference '.$submission->submission_number.' is pending verification. No loan balance changes until approval.');
    }

    private function digits(?string $value): string
    {
        return preg_replace('/\D+/', '', (string)$value) ?? '';
    }
}
