<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\DTO\SearchData;

class Banner extends Model
{
    protected $table = 'tb_banner';
    protected $primaryKey = 'id';

    public $keyType = 'int';
    public $incrementing = true;
    public $timestamps = true;

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';

    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class)->withDefault();
    }

    public function bannerGroup()
    {
        return $this->belongsTo(BannerGroup::class)->withDefault();
    }

    /**
     * 배너 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select('tb_banner.*');

        if ($params->keyword) {
            switch ($params->field) {
                case 'tb_banner.subject' :
                case 'tb_banner.url' :
                case 'users.name' :
                case 'users.email' :
                    $query->where($params->field, 'LIKE', "%{$params->keyword}%");
                    break;
                case 'tb_banner.id' :
                case 'users.id' :
                case 'users.sid' :
                    $query->where($params->field, '=', $params->keyword);
                    break;
            }
        }

        if ($params->activated != '') {
            $query->where('activated', '=', $params->activated);
        }

        $query->join('tb_banner_group', 'tb_banner_group.id', '=', 'tb_banner.banner_group_id');
        $query->leftJoin('users', 'users.id', '=', 'tb_banner.user_id');
        $query->orderByDesc('tb_banner.created_at');

        $list = $query->paginate($params->perPage, ['*'], 'page', $params->page);
        $total = $this->count();
        $rows = $list->count();

        return (object)[
            'total' => $total,
            'rows' => $rows,
            'list' => $list
        ];
    }

    /**
     * 표시할 배너 조회
     */
    public function list()
    {
        $today = now()->format('Y-m-d');
        $query = $this->query();
        $query->select('*');
        $query->where('start_date', '<=', $today);
        $query->where('end_date', '>=', $today);
        $query->where('activated', 1);
        $query->orderBy('order');
        $query->orderByDesc('created_at');

        return $query->get();
    }
}
