<?php
class RumahSakitOnlineController extends BaseController
{
    #region Internal
    public function search() {
        $params = $this->request->get();
        $params = $this->validate(
            $params,
            [
                "provinsi_id" => ["validators" => ["digit"]],
                "kab_kota_id" => ["validators" => ["digit"]],
                "keyword" => ["validators" => []],
                "limit" => ["validators" => ["digit"]],
                "offset" => ["validators" => ["digit"]],
                "order_direction" => ["validators" => [["name" => "inclusion_in", "params" => [null, "asc", "desc"]]]],
                "order_by" => ["validators" => [["name" => "inclusion_in", "params" => [null, "kode", "nama", "modified_at"]]]]
            ]
        );

        $provinsiId = $params["provinsi_id"];
        $kabKotaId = $params["kab_kota_id"];
        $keyword = $params["keyword"];
        $limit = empty($params["limit"]) ? 12 : $params["limit"];
        $offset = empty($params["offset"]) ? 0 : $params["offset"];
        $orderDir = empty($params["order_direction"]) ? "asc" : $params["order_direction"];
        $orderBy = empty($params["order_by"]) ? "nama" : $params["order_by"];
        $where = "1 = 1";
        $bind = [];

        if (!empty($provinsiId)) {
            $where .= " and provinsi_id = :provinsi_id:";
            $bind["provinsi_id"] = $provinsiId;
        }

        if (!empty($kabKotaId)) {
            $where .= " and kab_kota_id = :kab_kota_id:";
            $bind["kab_kota_id"] = $kabKotaId;
        }

        if (!empty($keyword)) {
            $where .= " and nama ilike :keyword:";
            $bind["keyword"] = "%" . $keyword . "%";
        }

        $rows = RumahSakitOnline::find([
            "conditions" => $where,
            "bind" => $bind,
            "limit" => $limit,
            "offset" => $offset,
            "order" => $orderBy . " " . $orderDir
        ]);

        $total = RumahSakitOnline::count([
           "conditions" => $where,
           "bind" => $bind
        ]);

        return new PaginatedResponse($rows, $total, $limit, $offset);
    }

    public function searchNama() {
        $params = $this->request->get();
        $params = $this->validate(
            $params,
            [
                "provinsi_id" => ["validators" => ["digit"]],
                "kab_kota_id" => ["validators" => ["digit"]],
                "keyword" => ["validators" => []],
                "limit" => ["validators" => ["digit"]],
                "offset" => ["validators" => ["digit"]],
                "order_direction" => ["validators" => [["name" => "inclusion_in", "params" => [null, "asc", "desc"]]]],
                "order_by" => ["validators" => [["name" => "inclusion_in", "params" => [null, "kode", "nama", "modified_at"]]]]
            ]
        );

        $provinsiId = $params["provinsi_id"];
        $kabKotaId = $params["kab_kota_id"];
        $keyword = $params["keyword"];
        $limit = empty($params["limit"]) ? 30 : $params["limit"];
        $offset = empty($params["offset"]) ? 0 : $params["offset"];
        $orderDir = empty($params["order_direction"]) ? "asc" : $params["order_direction"];
        $orderBy = empty($params["order_by"]) ? "nama" : $params["order_by"];
        $where = "1 = 1";
        $bind = [];

        if (!empty($provinsiId)) {
            $where .= " and provinsi_id = :provinsi_id:";
            $bind["provinsi_id"] = $provinsiId;
        }

        if (!empty($kabKotaId)) {
            $where .= " and kab_kota_id = :kab_kota_id:";
            $bind["kab_kota_id"] = $kabKotaId;
        }

        if (!empty($keyword)) {
            $where .= " and nama ilike :keyword:";
            $bind["keyword"] = "%" . $keyword . "%";
        }

        $rows = RumahSakitOnline::find([
            "columns" => "kode, nama",
            "conditions" => $where,
            "bind" => $bind,
            "limit" => $limit,
            "offset" => $offset,
            "order" => $orderBy . " " . $orderDir
        ]);

        return new CollectionPaginatedResponse($rows);
    }

    public function detail($kode) {
        /** @var RumahSakitOnline $row */
        $row = RumahSakitOnline::findFirst(["conditions" => "kode like :kode:", "bind" => ["kode" => $kode]]);
        if (!$row) {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "Rumah Sakit tidak ditemukan.");
        }
        $client = new RSOnlineClient($this->config["rs_online_config"]);

        $result = $row->toDetail($client);
        $nakes = [];
        foreach ($result["nakes"] as $nake) {
            $jenis = trim($nake["jenis_nakes"]);
            if (!array_key_exists($jenis, $nakes)) {
                $nakes[$jenis] = 1;
            } else {
                $nakes[$jenis] += 1;
            }
        }
        ksort($nakes);
        $result["nakes"] = $nakes;

        return new SimpleResponse($result);
    }
    #endregion

    #region Eksternal
    public function rsOnlinePost() {
        $this->checkScopes(['admin.view']);
        $json = $this->request->getJsonRawBody(true);
        $params = $json['params'];
        $path = $json['path'];
        $server = ["server" => $json['server']];
        $client = new RSOnlineClient($server);
        $res = $client->doPost($path, $params);

        return new SimpleResponse($res);
    }

    public function rsOnlineGet() {
        $this->checkScopes(['admin.view']);
        $json = $this->request->getJsonRawBody(true);
        $params = $json['params'];
        $path = $json['path'];
        $server = ["server" => $json['server']];
        $client = new RSOnlineClient($server);
        $res = $client->doGet($path, $params);

        return new SimpleResponse($res);
    }

    public function rsOnlineLogin() {
        $this->checkScopes(['admin.view']);
        $client = new RSOnlineClient($this->config["rs_online_config"]);
        $res = $client->login();
        return new SimpleResponse($res);
    }

    public function rsOnlineRumahSakitList() {
        $this->checkScopes(['admin.view']);
        $params = $this->validate(
            $this->request->get(),
            [
                'page' => ['validators' => ['digit']],
                'limit' => ['validators' => ['digit']],
            ]
        );
        $client = new RSOnlineClient($this->config["rs_online_config"]);
        $res = $client->rumahSakits($params);
        return new SimpleResponse($res);
    }

    public function rsOnlineRumahSakitDetail($id) {
        $this->checkScopes(['admin.view']);
        $client = new RSOnlineClient($this->config["rs_online_config"]);
        $res = $client->rumahSakit($id);
        return new SimpleResponse($res);
    }

    public function rsOnlineKetersediaanTempatTidur() {
        $this->checkScopes(['admin.view']);
        $params = $this->validate(
            $this->request->get(),
            [
                'page' => ['validators' => ['digit']],
                'limit' => ['validators' => ['digit']],
                'provinsiId' => ['validators' => ['digit']],
                'kabKotaId' => ['validators' => ['digit']],
                'rsId' => ['validators' => ['digit']],
            ]
        );
        $client = new RSOnlineClient($this->config["rs_online_config"]);
        $res = $client->ketersediaanTempatTidur($params);
        return new SimpleResponse($res);
    }

    public function rsOnlineKetersediaanNakes() {
        $this->checkScopes(['admin.view']);
        $params = $this->validate(
            $this->request->get(),
            [
                'kode_rs' => ['validators' => ['required']],
                'page' => ['validators' => ['digit']],
                'limit' => ['validators' => ['digit']],
            ]
        );
        $client = new RSOnlineClient($this->config["rs_online_config"]);
        $res = $client->ketersediaanNakes($params);
        return new SimpleResponse($res);
    }

    public function rsOnlineKetersediaanPelayanan() {
        $this->checkScopes(['admin.view']);
        $params = $this->validate(
            $this->request->get(),
            [
                'kode_rs' => ['validators' => ['required']],
                'page' => ['validators' => ['digit']],
                'limit' => ['validators' => ['digit']],
            ]
        );
        $client = new RSOnlineClient($this->config["rs_online_config"]);
        $res = $client->ketersediaanPelayanan($params);
        return new SimpleResponse($res);
    }
    #endregion
}
