<?php

namespace App\Models;

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

class Popup extends Model
{
    protected $table = 'tb_popup';
    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 data(SearchData $params): object
    {
        $query = $this->query();
        $query->select('tb_popup.*');

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

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

        $query->leftJoin('users', 'users.id', '=', 'tb_popup.user_id');
        $query->orderByDesc('tb_popup.id');

        $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->orderByDesc('created_at');

        return $query->get();
    }
}
