<?php

/**
 * @property UmUser $umUser
 */
class LogNotification extends \Jaga\Models\BaseModel {
    public $id;
    public $um_id;
    public $device_token;
    public $title;
    public $body;
    public $payload;
    public $created_at;
    public $sent_at;
    public $status;
    public $error_message;

    const STATUS_NEW = "NEW";
    const STATUS_SUCCESS = "SUCCESS";
    const STATUS_FAILED = "FAILED";

    const STATUSES = [self::STATUS_NEW, self::STATUS_SUCCESS, self::STATUS_FAILED];

    public function initialize()
    {
        $this->setSchema("jaga");
        $this->setSource("log_notification");
        $this->belongsTo('um_id', 'UmUser', 'um_id');
    }

    public static function insert($um_id, $deviceToken, $title, $body, $payload) {
        $data = new LogNotification();
        $data->um_id = $um_id;
        $data->device_token = $deviceToken;
        $data->title = $title;
        $data->body = $body;
        if (!is_string($payload)) {
            try {
                $payload = json_encode($payload);
            } catch (\Exception $e) {
                throw new CustomErrorException(BaseResponse::INVALID_REQUEST, "Payload Log Notification tidak valid!");
            }
        }
        $data->payload = $payload;
        $data->created_at = date('Y-m-d H:i:s');
        $data->status = self::STATUS_NEW;
        $data->save();
    }

    public function send() {
        try {
            $this->sent_at = date('Y-m-d H:i:s');
            $data = json_decode($this->payload, true);
            FcmHelper::sendNotif(
                $this->device_token,
                $this->title,
                $this->body,
                $data
            );
            $this->delete();
        } catch (\Exception $e) {
            $this->error_message = substr($e->getMessage(), 0 , 3000);
            $this->status = self::STATUS_FAILED;
            $this->save();
        }
    }

    /**
     * @throws CustomErrorException
     */
    public static function retrieve($id) {
        /** @var LogNotification|false $row */
        $row = self::findFirst($id);
        if (!$row) {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "Data tidak ditemukan!");
        }
        $row->payload = json_decode($row->payload, true);
        $res = $row->toArray();
        $res["um_user_name"] = $row->umUser->um_user_name;
        $res["nama"] = $row->umUser->nama;
        return $res;
    }
}
