<?php

class StranaspkRealizationController extends BaseController {

    public function index() {
        // menampilkan target-target realisasi output
        $this->checkIsAuthenticated();
        $getParams = $this->request->get();
        $params = $this->validate(
            $getParams,
            [
                'id_periode' => ['validators' => ['required', 'digit']],
            ]
        );
        $id_periode = $params['id_periode'];

        $logframeStore = new SleekDbStore('logframe');
        $outputs = $logframeStore->findBy([
            ["id_periode", "=", intval($id_periode)],
            ["level", "=", 3],
            function($output) {
                return !isset($output["is_deleted"]);
            }
        ],["_id" => "asc"]);
        
        $response = [];
        foreach($outputs as $output) {
            $response[] = [
                "_id" => $output["_id"],
                "id_logframe" => $output["id_logframe"],
                "name" => $output["name"]["long"],
                "targets" => $output["targets"]
            ];
        }
        return new SimpleResponse($response);
    }

    public function update() {
        // update target realization
        $this->checkIsAuthenticated();
        $postParams = $this->request->getJsonRawBody(true);
        $params = $this->validate(
            $postParams,
            [
                '_id' => ['validators' => ['digit', 'required']],
                'targets' => ['validators' => ['required']],
            ]
        );
        
        $logframeStore = new SleekDbStore('logframe');
        $output = $logframeStore->findById(intval($params['_id']));
        if (!$output) {
            throw new Exception("Salah parameter: _id");
        }
        $output['targets'] = $params['targets'];
        $success = $logframeStore->update($output);
        
        if (!$success) {
            throw new Exception("Update tidak berhasil");
        } else {
            $response = [
                "_id" => $output["_id"],
                "targets" => $output["targets"]
            ];

            return new SimpleResponse($response);
        }
    }
}