<?php

namespace App\Distributor\Controllers;

use App\Distributor\Repositories\DistAdminDistributor;
use App\Http\Controllers\Controller;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Widgets\Form;
use Illuminate\Http\Request;

class SettingsController extends Controller
{

    public function index(Content $content)
    {
        return $content->title(admin_trans( 'admin.domain'))
            ->body(
<<<HTML
<div class="card">{$this->form()->render()}</div>
HTML
            );
    }

    protected function form()
    {
        //查分销商信息
        $distInfo = DistAdminDistributor::getInfo();
        $secondaryDomain = $distInfo->secondary_domain ? $distInfo->secondary_domain : '';
        $customDomain = $distInfo->custom_domain ? $distInfo->custom_domain : '';
        $form = new Form();
        $form->radio('domain_type')
            ->when(0, function (Form $form) use ($secondaryDomain) {
                $form->text('secondary_domain')->width(4,2)->value($secondaryDomain)->readOnly();
            })
            ->when(1, function (Form $form) use ($customDomain){
                $form->text('custom_domain')->width(4,2)->value($customDomain)->required()->help('Please enter the domain name, such as www.example.com,and bind the domain name to the IP address '.env('DIST_SITE_IP'));
            })
            ->options([0=>admin_trans_field('secondary_domain'),1=>admin_trans_field('custom_domain')])
            ->value($distInfo->domain_type)
            ->required();
        return $form;
    }

    /*
     * 保存配置
     */
    public function store(Request $request)  {
        $form = new Form();
        $domainType = $request->input('domain_type');
        $customDomain = $request->input('custom_domain');
        if (!in_array($domainType, [0,1])) {
            return $form->response()->error('Invalid argument');
        }
        if ($domainType == 1) {
            if (str_starts_with($customDomain,env('TOP_DOMAIN'))) {
                return $form->response()->error('Error in domain format');
            }
            if (!isDomainOnly($customDomain)) {
                return $form->response()->error('Error in domain format');
            }
        }

        DistAdminDistributor::updateDomain($domainType,$customDomain);
        return $form->response()->success('Success');
    }


}
