<?php

namespace App\Http\Controllers\Admin\Sms;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\SmsHistory;
use App\Models\SmsBook;
use App\Models\SmsUser;
use App\Models\SmsLib;
use App\Models\User;
use App\Models\DTO\SearchData;

class SendController extends Controller
{
    private SmsHistory $smsHistoryModel;
    private SmsBook $smsBookModel;
    private SmsUser $smsUserModel;
    private User $userModel;
    private SmsLib $smsLib;

    public function __construct(
        SmsHistory $smsHistory,
        SmsBook $smsBook,
        SmsUser $smsUser,
        User $user,
        SmsLib $smsLib
    ) {
        $this->smsHistoryModel = $smsHistory;
        $this->smsBookModel = $smsBook;
        $this->smsUserModel = $smsUser;
        $this->userModel = $user;
        $this->smsLib = $smsLib;
    }

    /**
     * 문자 발송 관리
     * @method GET
     * @see /admin/sms/send
     */
    public function index()
    {
        return view('admin.sms.send.index', [
            'actionURL' => route('admin.sms.send.store'),
            'csrfToken' => csrf_token(),
            'smsGroups' => $this->smsBookModel->all()
        ]);
    }

    /**
     * 회원 연락처 전체 조회
     * @method GET
     * @see /admin/sms/send/user
     */
    public function user(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $params->receiveSms = 1;
        $params->actionURL = route('admin.sms.send.store');

        $userData = $this->userModel->data($params);

        if ($userData->rows > 0) {
            $num = listNum($userData->total, $params->page, $params->perPage);
            foreach ($userData->list as $i => $row) {
                $row->num = $num--;
                $userData->list[$i] = $row;
            }
        }

        return view('admin.sms.send.contact', [
            'userData' => $userData,
            'params' => $params
        ]);
    }

    /**
     * 회원 연락처 그룹 조회
     * @method GET
     * @see /admin/sms/send/book
     */
    public function book(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $params->smsBookID = $request->get('book');
        $params->actionURL = route('admin.sms.send.store');

        $userData = $this->smsUserModel->data($params);

        if ($userData->rows > 0) {
            $num = listNum($userData->total, $params->page, $params->perPage);
            foreach ($userData->list as $i => $row) {
                $row->num = $num--;
                $row->id = $row->user_id;
                $userData->list[$i] = $row;
            }
        }

        return view('admin.sms.send.contact', [
            'userData' => $userData,
            'params' => $params
        ]);
    }

    /**
     * 문자 발송 저장
     * @method POST
     * @see /admin/sms/send
     */
    public function store(Request $request)
    {
        $rules = [
            'user_ids' => 'required|string',
            'sms_subject' => 'required|string|max:30',
            'sms_content' => 'required|string|max:2000',
            'sms_tel' => 'nullable|required_without:sms_per_tel',
            'sms_per_tel' => 'nullable|required_without:sms_tel',
            'sms_is_reserve' => 'numeric|nullable|in:0,1',
            'sms_reserve_at' => 'string|nullable|date'
        ];

        $attributes = [
            'user_ids' => '수신 회원 PK',
            'sms_subject' => '제목',
            'sms_content' => '내용',
            'sms_tel' => '발신 번호',
            'sms_per_tel' => '발신 번호',
            'sms_is_reserve' => '예약 여부',
            'sms_reserve_at' => '예약 일시'
        ];

        $posts = $this->validate($request, $rules, [], $attributes);
        $userIDs = json_decode($posts['user_ids'], true); // input.hidden 으로 user_id 와 연락처를 받음

        $sendNumber = []; // 수신번호
        foreach ($userIDs as $userID => $tel) {
            if($userID) {
                $sendNumber[$userID] = $tel;
            }else{
                $sendNumber[] = $tel;
            }
        }

        // 개인 발송
        if($posts['sms_per_tel']) {
            foreach(explode(',', $posts['sms_per_tel']) as $tel) {
                $sendNumber[] = $tel;
            }
        }

        $result = $this->smsLib->send($sendNumber, [
            'userID' => UID, // 발신자 PK
            'subject' => $posts['sms_subject'],
            'content' => $posts['sms_content'],
            'isReserve' => ($posts['sms_is_reserve'] ?? 0),
            'reserveAt' => ($posts['sms_reserve_at'] ?? null)
        ]);

        if (!$result) {
            return back()->withErrors($this->smsLib->errors())->withInput();
        }

        $message = $this->smsLib->report();
        return redirect()->route('admin.sms.send.index')->with('message', $message);
    }
}
