<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Services\WhmcsSupportService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ManualPaymentController extends Controller
{
    public function __construct(private readonly WhmcsSupportService $support) {}

    public function store(Request $request, Invoice $invoice): RedirectResponse
    {
        abort_unless((int) $invoice->user_id === (int) $request->user()->id, 404);
        abort_if(in_array(strtolower((string) $invoice->status), ['paid', 'cancelled', 'refunded'], true), 422, 'This invoice is not payable.');

        $channels = config('zt.manual_payments.bank_channels', []);

        $data = $request->validate([
            'payment_channel' => ['required', Rule::in(array_keys($channels))],
            'proof' => ['required', 'file', 'mimes:jpg,jpeg,png,webp,pdf', 'max:'.config('zt.manual_payments.max_proof_kb', 5120)],
            'client_note' => ['nullable', 'string', 'max:1000'],
        ]);

        $file = $request->file('proof');
        try {
            $result = $this->support->openPaymentTicket($request->user(), $invoice, $data['payment_channel'], $file, $data['client_note'] ?? null);
        } catch (\RuntimeException $e) {
            report($e);
            return back()->with('error', 'Payment proof could not be submitted. Please try again or contact support.')->withInput();
        }

        $ticketId = data_get($result, 'response.id');
        return $ticketId
            ? redirect()->route('client.support.show', $ticketId)->with('status', 'Payment proof sent to Billing successfully.')
            : back()->with('status', 'Payment proof sent to Billing successfully.');
    }
}
