<?php

namespace App\Http\Controllers\Admin\Config\Test;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Config;
use App\Models\SmsLib;

class SmsController extends Controller
{
    private Config $configModel;

    public function __construct()
    {
        $this->configModel = new Config();
    }

    /**
     * SMS 발송 확인
     * @method GET
     * @see /admin/config/test/sms
     */
    public function index()
    {
        return view('admin.config.test.sms', [
            'subject' => '문자 발송 확인',
            'smsNumber' => env('SMS_NUMBER')
        ]);
    }

    /**
     * 문자 발송 확인 실행
     * @method POST
     * @see /admin/config/test/sms
     */
    public function store(Request $request, SmsLib $smsLib)
    {
        $rules = [
            'receive_number' => 'required|string|regex:/^(\d+)-(\d+)-(\d+)$/',
        ];

        $attributes = [
            'receive_number' => '받는 번호'
        ];

        $posts = $this->validate($request, $rules, [], $attributes);

        $sendNumber = [ // 수신번호
            UID => $posts['receive_number']
        ];

        // 수신정보
        $sendData = [
            'userID' => UID, // 수신자 PK
            'subject' => '[' . date('Y-m-d H:i:s') . '] 문자 발송 확인',
            'content' => configs('site_title'),
            'isReserve' => 0,
            'reserveAt' => null
        ];

        $result = $smsLib->send($sendNumber, $sendData);
        if(!$result) {
            return back()->withErrors($smsLib->errors())->withInput();
        }

        $message = '문자를 발송하였습니다.';
        return redirect()->route('admin.config.test.sms.index')->with('message', $message);
    }
}
