<?php

class StranasNewHierarchyController extends BaseController {
    public function index() {
        $this->checkIsAuthenticated();
        $getParams = $this->request->get();

        $per = $this->rawQuery('select * from jaga.str_periode where is_active=true');
        $id_periode = $per[0]['id'];

        $condition = '1=1';
        // $condition = 'deleted_at is null';
        $condition .= (isset($_GET['id_parent']) && $_GET['id_parent'] != '') ? ' and id_parent = '.$_GET['id_parent'] : '';
        $condition .= (isset($_GET['id_level']) && $_GET['id_level'] != '') ? ' and id_level = '.$_GET['id_level'] : '';
        $condition .= (isset($_GET['id_periode']) && $_GET['id_periode'] != '') ? ' and id_periode = '.$_GET['id_periode'] : ' and id_periode = '.$id_periode ;
        $condition .= (isset($_GET['nama']) && $_GET['nama'] != '') ? " and nama ilike '%".$_GET['nama']."%' " : '';

        $getParams['columns'] = $getParams['columns'] ?? '*';
        $getParams['limit'] = $this->getDefaultLimit($getParams);
        $getParams['offset'] = array_key_exists('offset', $getParams) ? $getParams['offset'] : 0;
        $getParams['keyword'] = array_key_exists('keyword', $getParams) ? $getParams['keyword'] : '';
        $getParams['order'] = array_key_exists('order', $getParams) ? $getParams['order'] : '';

        $where = ' 1=1 ';
        if(isset($_GET['is_active'])) {
            if($_GET['is_active'] == 1) {
                $where .= ' and deleted_at is null ';
            } else if($_GET['is_active'] == 0) {
                $where .= ' and deleted_at is not null ';
            }
        }

        $params = $this->validate(
            $getParams,
            [
                'conditions' => $where,
                'limit' => ['validators' => ['digit']],
                'offset' => ['validators' => ['digit']],
                'keyword' => ['validators' => []],
                'order' => ['validators' => []]
            ]
        );
        $order   = (isset($_GET['order']) && $_GET['order'] != '') ? ' order by '.$_GET['order'] : '';
        $offset  = ' offset '.$params['offset'];
        $limit   = ' limit '.$params['limit'];

        $rows = $this->rawQuery("select ".$getParams['columns']." from jaga.str_hierarchy where ".$condition.$order.$limit.$offset);
        $total = $this->rawQuery('select count(1) as total_record from jaga.str_hierarchy where '.$condition);
        return new PaginatedResponse($rows, $total[0]['total_record'], $params['limit'], $params['offset']);


        $hierarchy = $this->rawQuery('select * from jaga.str_hierarchy where '.$condition);
        $rows = StranasNewTarget::find([
            'conditions' => $where,
            'limit' => $params['limit'],
            'offset' => $params['offset'],
            'order' => "{$params['order_by']} {$params['order_direction']}"
        ]);

        $total = $this->rawQuery('select count(1) as total_record from str_target where '.$where);
        return new PaginatedResponse($rows, $total[0]['total_record'], $params['limit'], $params['offset']);

        $response = new \Phalcon\Http\Response();
        $response->setContentType('application/json', 'UTF-8');
        $response->setContent(json_encode([
          'success' => true,
          'data' => [ 'rows' => $hierarchy ]
        ]));

        return $response;
    }
    // C
    public function create() {
        $this->checkScopes(['stranas.admin']);

        $rawBody = $this->request->getJsonRawBody(true);
        $params = $this->validate( $rawBody, [ 
            'id_periode' => ['validators' => ['required', 'numeric']],
            'id_parent' => ['validators' => ['numeric']], // kalau null dia level1
            'id_level' => ['validators' => ['required', 'numeric']],
            'ord' => ['validators' => []],
            'nama' => ['validators' => ['required']],
            'keterangan' => ['validators' => []],
            'kode' => ['validators' => []],
        ] );

        $tbl = new StranasNewHierarchy();
        $tbl->id_periode = $params['id_periode'];
        $tbl->id_parent = $params['id_parent'];
        $tbl->id_level = $params['id_level'];
        $tbl->nama = $params['nama'];
        $tbl->kode = $params['kode'];
        $tbl->keterangan = $params['keterangan'];
        $tbl->ord = $params['ord'];
        $tbl->created_by = $this->shared->user->um_id;
        $status = $tbl->save();

        if (!$status) {
            $errors = $tbl->getMessages();

            $error_messages = [];
            foreach ($errors as $key => $error) {
                $error_messages[] = ["field" => $error->getField(), "message" => $error->getMessage()];
            }
            throw new ValidationException($error_messages);
        } else {
            return new CollectionPaginatedResponse([$tbl]);
        }
    }
    // R
    public function detail($id) {
        $tw  = $this->rawQuery('select * from jaga.str_hierarchy where id='.$id);
        $level = $tw[0]['id_level'];
        
        $per  = $this->rawQuery('select * from jaga.str_periode where is_active=true');
        $periode = $per[0];

        $query = "
                select 
                    p.id as id_periode,
                    ".$level." as current_level,p.level1,p.level2,p.level3,p.level4,l1.id as id_level1,l1.nama as nama_level1,l1.ord,"
                    .(($periode['level_count'] ==4)?'p.level4,':'')
                    .(($level==1)?" '' as id_level2,'' as nama_level2, '' as id_level3, '' as nama_level3, '' as id_level4, '' as nama_level4 ": "")
                    .(($level==2)?" l2.id as id_level2,l2.nama as nama_level2, '' as id_level3, '' as nama_level3, '' as id_level4, '' as nama_level4 ": "")
                    .(($level==3)?" l2.id as id_level2,l2.nama as nama_level2, l3.id as id_level3,l3.nama as nama_level3, null as id_level4, null as nama_level4 ": "")
                    .(($level==4)?" l2.id as id_level2,l2.nama as nama_level2, l3.id as id_level3,l3.nama as nama_level3, l4.id as id_level4,l4.nama as nama_level4":"")
                    ."
                from jaga.str_hierarchy l1
                    join jaga.str_periode p on p.id=l1.id_periode"
                    .(($level==2)?" left join jaga.str_hierarchy l2 on l2.id_parent=l1.id":"")
                    .(($level==3)?" left join jaga.str_hierarchy l2 on l2.id_parent=l1.id left join jaga.str_hierarchy l3 on l3.id_parent=l2.id":"")
                    .(($level==4)?" left join jaga.str_hierarchy l2 on l2.id_parent=l1.id left join jaga.str_hierarchy l3 on l3.id_parent=l2.id left join jaga.str_hierarchy l4 on l4.id_parent=l3.id":"")
                ." where l".$level.".id = ".$id;
        $drill = $this->rawQuery($query);

        $response = new \Phalcon\Http\Response();
        $response->setContentType('application/json', 'UTF-8');
        $response->setContent(json_encode([
          'success' => true,
          'data' => [ 'drill' => $drill ]
          // 'data' => [ 'drill' => $drill, 'rows' => $rows ]
        ]));

        return $response;


        $tbl = StranasNewHierarchy::findFirst($id);
        if (empty($tbl)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Hierarchy tidak ditemukan');
        }
        $result = $tbl;
        return new CollectionPaginatedResponse([$result]);
    }
    // U
    public function update($id) {
        $this->checkScopes(['stranas.admin']);
        $tbl = StranasNewHierarchy::findFirst($id);

        if (empty($tbl)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Hierarchy tidak ditemukan');
        }

        if (!empty($tbl->deleted_at)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Hierarchy sudah terhapus');
        }

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

        $params = $this->validate( $rawBody, [ 
            'id_periode' => ['validators' => ['required', 'numeric']],
            'id_parent' => ['validators' => ['numeric']], // kalau null dia level1
            'id_level' => ['validators' => ['required', 'numeric']],
            'ord' => ['validators' => ['numeric']],
            'nama' => ['validators' => ['required']],
            'keterangan' => ['validators' => []],
            'kode' => ['validators' => []],
        ] );

        // validasi
        $tbl->id_periode = $params['id_periode'];
        $tbl->id_parent = $params['id_parent'];
        $tbl->id_level = $params['id_level'];
        $tbl->nama = $params['nama'];
        $tbl->kode = $params['kode'];
        $tbl->keterangan = $params['keterangan'];
        $tbl->ord = $params['ord'];

        $now = date('Y-m-d H:i:s');
        $tbl->updated_at = $now;
        $tbl->updated_by = $this->shared->user->um_id;
        $status = $tbl->save();

        if (!$status) {
            $errors = $tbl->getMessages();
            $error_messages = [];

            foreach ($errors as $key => $error) {
                $error_messages[] = ["field" => $error->getField(), "message" => $error->getMessage()];
            }

            throw new ValidationException($error_messages);
        } else {
            return new CollectionPaginatedResponse([$tbl]);
        }
    }

    public function restored($id) {
        $this->checkScopes(['stranas.admin']);
        $tbl = StranasNewHierarchy::findFirst($id);

        if (empty($tbl)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Hierarchy tidak ditemukan');
        }

        $tbl->deleted_at = NULL;
        $tbl->deleted_by = NULL;
        $status = $tbl->save();

        if (!$status) {
            $errors = $tbl->getMessages();
            $error_messages = [];

            foreach ($errors as $key => $error) {
                $error_messages[] = ["field" => $error->getField(), "message" => $error->getMessage()];
            }

            throw new ValidationException($error_messages);
        } else {
            return new CollectionPaginatedResponse([$tbl]);
        }
    }
    // D
    public function delete($id) {
        $this->checkScopes(['stranas.admin']);

        $tbl = StranasNewHierarchy::findFirst($id);
        if (empty($tbl)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Hierarchy tidak ditemukan');
        }
        
        if (!empty($tbl->deleted_at)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Hierarchy sudah terhapus');
        }

        $now = date('Y-m-d H:i:s');
        $tbl->deleted_at = $now;
        $tbl->deleted_by = $this->shared->user->um_id;
        $status = $tbl->save();

        if (!$status) {
            $errors = $tbl->getMessages();
            $error_messages = [];

            foreach ($errors as $key => $error) {
                $error_messages[] = ["field" => $error->getField(), "message" => $error->getMessage()];
            }

            throw new ValidationException($error_messages);
        } else {
            return new CollectionPaginatedResponse([$tbl]);
        }
    }
}
