<?php

namespace App\Http\Controllers\Admin\Sms;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\SmsHistory;
use App\Models\DTO\SearchData;

class HistoryController extends Controller
{
    private SmsHistory $smsHistoryModel;

    public function __construct(SmsHistory $smsHistory)
    {
        $this->smsHistoryModel = $smsHistory;
    }

    /**
     * SMS > 전송 내역
     * @method GET
     * @see /admin/sms/history
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $smsHistoryData = $this->smsHistoryModel->data($params);

        if ($smsHistoryData->rows > 0) {
            $num = listNum($smsHistoryData->total, $params->page, $params->perPage);
            foreach ($smsHistoryData->list as $i => $row) {
                $row->num = $num--;
                $row->isReserveStr = ($row->is_reserve ? 'Y' : 'N');
                $row->reserveAt = dateBr($row->reserve_at, '-');
                $row->createdAt = dateBr($row->created_at);

                $smsHistoryData->list[$i] = $row;
            }
        }

        return view('admin.sms.history.index', [
            'smsHistoryData' => $smsHistoryData,
            'params' => $params
        ]);
    }

    /**
     * 전송내역 삭제
     * @method DELETE
     * @see /admin/sms/history
     */
    public function destroy(Request $request)
    {
        $chk = $request->post('chk');

        if ($chk) {
            foreach ($chk as $historyID) {
                $this->smsHistoryModel->find($historyID)->delete();
            }
        }

        $message = '전송 내역이 삭제되었습니다.';
        return redirect()->route('admin.sms.history.index')->with('message', $message);
    }
}
