<?php

namespace App\Http\Controllers\Admin\Sms\Book;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use App\Models\SmsBook;
use App\Models\DTO\SearchData;

class ListController extends Controller
{
    private SmsBook $smsBookModel;

    public function __construct(SmsBook $smsBook)
    {
        $this->smsBookModel = $smsBook;
    }

    /**
     * 주소록 관리 목록
     * @method GET
     * @see /admin/sms/send
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $smsBookData = $this->smsBookModel->data($params);

        if ($smsBookData->rows > 0) {
            $num = listNum($smsBookData->total, $params->page, $params->perPage);
            foreach ($smsBookData->list as $i => $row) {
                $row->num = $num--;
                $row->bookUserListURL = route('admin.sms.book.user.index') . '?book=' . $row->id;
                $row->editURL = route('admin.sms.book.list.edit', $row->id);
                $smsBookData->list[$i] = $row;
            }
        }

        return view('admin.sms.book.list.index', [
            'smsBookData' => $smsBookData
        ]);
    }

    /**
     * 주소록 관리 등록
     * @method GET
     * @see /admin/sms/send/create
     */
    public function create()
    {
        return view('admin.sms.book.list.write', [
            'actionURL' => route('admin.sms.book.list.store'),
            'smsBookData' => [],
            'smsBookID' => null
        ]);
    }

    /**
     * 주소록 관리 수정
     * @method GET
     * @see /admin/sms/send/{pk}/edit
     */
    public function edit(int $smsBookID)
    {
        return view('admin.sms.book.list.write', [
            'actionURL' => route('admin.sms.book.list.update', $smsBookID),
            'smsBookData' => $this->smsBookModel->find($smsBookID),
            'smsBookID' => $smsBookID
        ]);
    }

    /**
     * 주소록 관리 등록
     * @method POST
     * @see /admin/sms/send/create
     */
    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255|unique:tb_sms_book,name',
            'order' => 'required|numeric'
        ];

        $attributes = [
            'name' => '이름',
            'order' => '순서'
        ];

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

        $this->smsBookModel->insert([
            'name' => $posts['name'],
            'order' => $posts['order'],
            'created_at' => now()
        ]);

        $message = '주소록이 등록되었습니다.';
        return redirect()->route('admin.sms.book.list.index')->with('message', $message);
    }

    /**
     * 주소록 관리 수정
     * @method PUT
     * @see /admin/sms/send
     */
    public function update(Request $request)
    {
        $smsBookID = $request->post('sms_book_id');

        $rules = [
            'sms_book_id' => 'required|numeric|exists:tb_sms_book,id',
            'name' => 'required|string|max:255' . Rule::unique('tb_sms_book', 'name')->ignore($smsBookID, 'id'),
            'order' => 'required|numeric'
        ];

        $attributes = [
            'sms_book_id' => 'PK',
            'name' => '이름',
            'order' => '순서'
        ];

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

        $this->smsBookModel->find($posts['sms_book_id'])->update([
            'name' => $posts['name'],
            'order' => $posts['order'],
            'updated_at' => now()
        ]);

        $message = '주소록이 수정되었습니다.';
        return redirect()->route('admin.sms.book.list.edit', $posts['sms_book_id'])->with('message', $message);
    }

    /**
     * 주소록 관리 삭제
     * @method DELETE
     * @see /admin/sms/send/destroy
     */
    public function destroy(Request $request)
    {
        $chk = $request->post('chk');

        if ($chk) {
            foreach ($chk as $smsBookID) {
                $smsBook = $this->smsBookModel->find($smsBookID);

                // 연락처 그룹에 회원이 등록되면 삭제 불가
                $userRows = $smsBook->smsUser->count();
                if($userRows > 0) {
                    return back()->withErrors("{$smsBookID}번 주소록은 삭제할 수 없습니다.")->withInput();
                }

                $smsBook->delete();
            }
        }

        $message = '주소록이 삭제되었습니다.';
        return redirect()->route('admin.sms.book.list.index')->with('message', $message);
    }
}
