<?php

namespace App\Http\Controllers\Admin;

use App\CentralLogics\Helpers;
use App\Http\Controllers\Controller;
use App\Services\Courier\CourierSettingsService;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CourierSettingsController extends Controller
{
    public function __construct(
        private readonly CourierSettingsService $courierSettingsService
    ) {
    }

    public function index()
    {
        if (! Helpers::module_permission_check('settings')) {
            Toastr::error(translate('messages.access_denied'));
            return back();
        }

        $providerConfig = $this->courierSettingsService->getProviderConfig('steadfast');

        if (blank(data_get($providerConfig, 'webhook_bearer_token'))) {
            $providerConfig['webhook_bearer_token'] = Str::random(48);
        }

        return view('admin-views.business-settings.courier-index', [
            'integration' => $this->courierSettingsService->getIntegrationSettings(),
            'senderProfile' => $this->courierSettingsService->getSenderProfile(),
            'providerConfig' => $providerConfig,
            'webhookCallbackUrl' => route('courier.steadfast.webhook'),
        ]);
    }

    public function update(Request $request)
    {
        if (env('APP_MODE') === 'demo') {
            Toastr::info(translate('messages.update_option_is_disable_for_demo'));
            return back();
        }

        $validated = $request->validate([
            'enabled' => 'nullable|boolean',
            'provider_enabled' => 'nullable|boolean',
            'mode' => 'required|in:sandbox,live',
            'manual_sync_enabled' => 'nullable|boolean',
            'auto_sync_enabled' => 'nullable|boolean',
            'allowed_booking_statuses' => 'required|array|min:1',
            'allowed_booking_statuses.*' => 'in:confirmed,accepted,processing',
            'sender_name' => 'required|string|max:191',
            'sender_phone' => 'required|string|max:30',
            'sender_address' => 'required|string|max:500',
            'sender_district' => 'nullable|string|max:191',
            'default_parcel_note' => 'nullable|string|max:255',
            'base_url' => 'required|url|max:255',
            'booking_path' => 'required|string|max:255',
            'status_by_consignment_path' => 'required|string|max:255',
            'status_by_invoice_path' => 'required|string|max:255',
            'status_by_tracking_path' => 'required|string|max:255',
            'api_key' => 'nullable|string|max:500',
            'secret_key' => 'nullable|string|max:500',
            'webhook_bearer_token' => 'nullable|string|max:500',
        ]);

        $this->courierSettingsService->saveSettings($validated);

        Toastr::success('Courier settings updated successfully.');
        return back();
    }
}
