<?php
class NotificationBlastController extends BaseController
{
    public function submitNotificationBlast()
    {
        $this->checkScopes(['notification_blast.create']);

        $params = $this->request->getJsonRawBody(true);

        $validatedRequest = $this->validate(
            $params,
            [
                'judul' => ['validators' => ['required']],
                'konten' => ['validators' => ['required']],
                'keterangan' => ['validators' => ['required']],
                'parameter' => ['validators' => ['required']]
            ]
        );

        $notif = new NotificationBlast();
        $notif->judul = $params['judul'];
        $notif->konten = $params['konten'];
        $notif->keterangan = $params['keterangan'];
        $notif->parameter = $params['parameter'];
        $notif->user_id = $this->shared->user->um_id;

        if ($notif->create()) {
            $this->sendNotifBlast($notif);
            return new ObjectResponse(
                [
                    "success" => true,
                    "data" => [$notif]
                ]
            );
        } else {
            throw new CustomErrorException(BaseResponse::SQL_ERROR, "SQL Error", $notif->getJsonErrMessages());
        }

    }

    public function getNotificationBlastDetail($id)
    {
        $this->checkScopes(['notification_blast.create']);

        $notif = NotificationBlast::findFirst(
            [
                "id = :id:",
                "bind" => [
                    "id" => $id
                ]
            ]
        );
        if ($notif) {
            return new PaginatedResponse($notif, 1, 1, 0);
        } else {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, 'Notification Blast not found');
        }
    }

    public function editNotificationBlast($id)
    {
        $this->checkScopes(['notification_blast.create']);

        $params = $this->request->getJsonRawBody(true);

        $validatedRequest = $this->validate(
            $params,
            [
                'judul' => ['validators' => ['required']],
                'konten' => ['validators' => ['required']],
                'keterangan' => ['validators' => ['required']],
                'parameter' => ['validators' => ['required']]
            ]
        );

        $notif = NotificationBlast::findFirst(
            [
                "id = :id:",
                "bind" => [
                    "id" => $id
                ]
            ]
        );
        if ($notif) {
            $notif->judul = $params['judul'];
            $notif->konten = $params['konten'];
            $notif->keterangan = $params['keterangan'];
            $notif->parameter = $params['parameter'];
            $notif->updated_at = "now()";

            if ($notif->update()) {
                $this->sendNotifBlast($notif);
                return new ObjectResponse(
                    [
                        "success" => true,
                        "data" => [$notif]
                    ]
                );
            } else {
                throw new CustomErrorException(BaseResponse::SQL_ERROR, "SQL Error", $notif->getJsonErrMessages());
            }
        } else {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, 'Notification Blast not found');
        }
    }

    public function deleteNotificationBlast($id)
    {
        $this->checkScopes(['notification_blast.create']);

        $notif = NotificationBlast::findFirst(
            [
                "id = :id:",
                "bind" => [
                    "id" => $id
                ]
            ]
        );

        if ($notif) {
            $notif->deleted_at = "now()";
            if ($notif->update()) {
                return new ObjectResponse(
                    [
                        "success" => true,
                        "data" => [$notif]
                    ]
                );
            } else {
                throw new CustomErrorException(BaseResponse::SQL_ERROR, "SQL Error", $notif->getJsonErrMessages());
            }
        } else {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, 'Notification Blast not found');
        }
    }

    public function listNotificationBlast()
    {
        $this->checkScopes(['notification_blast.create']);

        $params = $this->request->get();

        $params['limit'] = $this->getDefaultLimit($params);
        $params["offset"] = array_key_exists("offset", $params) ? $params["offset"] : 0;
        $params["judul"] = array_key_exists("judul", $params) ? $params["judul"] : "";
        $params["filter"] = array_key_exists("offset", $params) ? $params["filter"] : "";
        $params["sortBy"] = array_key_exists("sortBy", $params) ? $params["sortBy"] : "created_at";
        $params["descending"] = array_key_exists("descending", $params) ? ($params["descending"] === "true" ? "DESC" : "ASC") : "DESC";

        $validatedRequest = $this->validate(
            $params,
            [
                'limit' => ['validators' => ['digit']],
                'offset' => ['validators' => ['digit']]
            ]
        );

        $strWhere = "";
        $bind = [];
        if (strlen($params["filter"]) > 0) {
            $strWhere = "lower(judul) like :judul:";
            $bind["judul"] = "%" . strtolower($params["filter"]) . "%";
        }

        $notifs = NotificationBlast::find(
            [
                "limit" => $params["limit"],
                "offset" => $params["offset"],
                $strWhere,
                "bind" => $bind,
                "order" => $params["sortBy"] . " " . $params["descending"]
            ]
        );

        $res = [];
        foreach ($notifs as $notif) {
            $res[] = $notif->listJsonDetail();
        }

        return new PaginatedResponse($res, NotificationBlast::count(), $params["limit"], $params["offset"]);
    }

    private function sendNotifBlast($notif)
    {
        $receivers = FcmDeviceToken::find(
            [
                "columns" => "distinct device_token"
            ]
        )
            ->toArray();

        foreach ($receivers as $receiver) {
            FcmHelper::sendNotifBg(
                $receiver["device_token"],
                $notif->judul,
                $notif->konten,
                [
                    "success" => true
                ],
                $notif->parameter
            );

        }
    }
}
?>
