<?php

namespace Mtc\Modules\B2B\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Mtc\Modules\B2B\Services\TradeRegistrationService;

class TradeRegistrationController extends Controller
{
    public function __construct(private TradeRegistrationService $service) {}

    public function showForm()
    {
        return template('b2b/register.twig', [
            'page_meta' => ['title' => 'Trade Account Application'],
            'old'       => session('_old_input', []),
            'errors'    => session('errors', []),
            'success'   => session('success'),
        ]);
    }

    public function submitForm(Request $request)
    {
        try {
            $request->validate([
                'company_name'      => 'required|string|max:255',
                'billing_firstname' => 'required|string|max:100',
                'billing_lastname'  => 'required|string|max:100',
                'email'             => 'required|email|max:255',
                'phone'             => 'required|string|max:30',
                'address_1'         => 'required|string|max:255',
                'address_2'         => 'nullable|string|max:255',
                'city'              => 'required|string|max:100',
                'postcode'          => 'nullable|string|max:20',
                'billing_postcode'  => 'nullable|string|max:20',
                'message'           => 'nullable|string|max:2000',
                'password'          => 'required|string|min:8',
                'password2'         => 'required|string|same:password',
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json(['errors' => $e->validator->errors()->all()]);
        }

        $data = $request->only([
            'company_name', 'billing_firstname', 'billing_lastname',
            'email', 'phone', 'address_1', 'address_2',
            'city', 'postcode', 'billing_postcode', 'message', 'password', 'password2',
        ]);

        // PAF submits billing_postcode — normalise to postcode for the service
        if (empty($data['postcode']) && !empty($data['billing_postcode'])) {
            $data['postcode'] = $data['billing_postcode'];
        }

        $tradeCustomer = $this->service->register($data);

        if (!$tradeCustomer) {
            return response()->json(['errors' => $this->service->getErrors()]);
        }

        session()->flash('success', 'Your trade account application has been submitted. We will review it and get back to you shortly.');
        return response()->json(['success' => ['redirect' => '/trade/register']]);
    }
}
