<?php

use Phalcon\Mvc\Controller\Base;

class KorsupgahTeamController extends BaseController
{
    public function list()
    {
        $this->checkIsAuthenticated();

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

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

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

        $teams = KorwilTeam::find([
            'conditions' => 'name ilike :keyword: OR description ilike :keyword:',
            'bind' => [
                'keyword' => '%' . $params['keyword'] . '%'
            ],
            'limit' => $params['limit'],
            'offset' => $params['offset']
        ]);

        $total_record = KorwilTeam::count();

        return new PaginatedResponse($teams, $total_record, $params['limit'], $params['offset']);
    }

    public function update($id)
    {
        $this->checkScopes(['korsupgah.admin']);


        $team = KorwilTeam::findFirst($id);

        if (empty($team)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Team dengan ID #' . $id . 'tidak ditemukan');
        }

        if (!empty($team->deleted_at)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Team dengan ID #' . $id . 'mungkin sudah terhapus');
        }

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

        $params = $this->validate(
            $rawBody,
            [
                'name' => ['validators' => ['required']],
                'description' => ['validators' => []]
            ]
        );

        $team->name = $params['name'];
        $team->description = $params['description'];
        $team->updated_at = date('Y-m-d H:i:s');
        $status = $team->save();

        if (!$status) {
            $errors = $team->getMessage();

            $error_messages = [];

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

            throw new ValidationsException($error_messages);
        } else {

            return new CollectionPaginatedResponse([$team]);
        }
    }

    public function delete($id)
    {
        $this->checkScopes(['korsupgah.admin']);

        $team = KorwilTeam::findFirst($id);

        if (empty($team)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Team dengan ID #' . $id . 'tidak ditemukan');
        }

        if (!empty($team->deleted_at)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Team dengan ID #' . $id . 'mungkin sudah terhapus');
        }

        $date = date('Y-m-d H:i:s');

        $team->updated_at = $date;
        $team->deleted_at = $date;
        $status = $team->save();

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

            $error_messages = [];

            foreach ($errors as $key => $error) :
                $error_messages[] = [
                    "field" => $error->getField(),
                    "message" => $error->getMessages()
                ];
            endforeach;

            throw new ValidationException($error_messages);
        } else {

            return new CollectionPaginatedResponse([$team]);
        }
    }

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

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

        $params = $this->validate(
            $rawBody,
            [
                'name' => ['validators' => ['required']],
                'description' => ['validators' => []],
            ]
        );

        $team = new KorsupgahTemplate();
        $team->name = $params['name'];
        $team->description = $params['description'];
        $team->created_at = date('Y-m-d H:i:s');
        $status = $team->save();

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

            $error_messages = [];

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

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

    public function restore($id)
    {
        $this->checkScopes(['korsupgah.admin']);

        $team = KorwilTeam::findFirst($id);

        if (empty($team)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Team dengan ID #' . $id . 'Tidak Ditemukan');
        }

        if (empty($team->deleted_at)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Team dengan ID #' . $id . 'Sudah Aktif');
        }

        $team->updated_at = date('Y-m-d H:i:s');
        $team->deleted_at = null;
        $status = $team->save();

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

            $error_messages = [];

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

            throw new ValidationException($error_messages);
        } else {

            return new CollectionPaginatedResponse([$team]);
        }
    }

    public function syncUsers()
    {
        $this->checkScopes(['korsupgah.admin']);

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

        $params = $this->validate(
            $rawBody,
            [
                'id' => ['validators' => ['required']],
                'user_ids' => ['validators' => ['required']]
            ]
        );

        if (!is_array($params['user_ids'])) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Format User IDs tidak valid');
        }

        $user_ids = array_unique(array_values($params['user_ids']));

        $team = KorwilTeam::findFirst($params['id']);

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

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


        $users = UmUser::find([
            'conditions' => 'um_id in ({ids:array}) AND deleted_at is NULL',
            'bind' => [
                'ids' => array_values($user_ids)
            ]
        ]);

        // Check Expected sub indikator List exists in master data

        $existing_user_ids = [];

        foreach ($users as $key => $sub_indikator) {
            $existing_user_ids[] = $sub_indikator->id;
        }

        $not_exist_ids = array_diff($user_ids, $existing_user_ids);

        if (!empty($not_exist_ids)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'User dengan ID ' . implode(",", $not_exist_ids) . ' tidak aktif/terdaftar');
        }

        $currentMembers = KorwilTeamUser::find([
            'conditions' => 'team_id=:team_id: AND deleted_at is NULL',
            'bind' => [
                'team_id' => $params['id']
            ]
        ]);


        $current_user_ids = [];

        // Delete all current member that doesn't exist in params
        foreach ($currentMembers as $key => $member) {
            $current_user_ids[] = $member->user_id;
            if (!in_array($member->user_id, $existing_user_ids)) {
                $status = $member->delete();
            }
        }

        // Otherwise, Register new member to this team
        foreach ($existing_user_ids as $key => $userId) {
            if (!in_array($userId, $current_user_ids)) {
                $member = new KorwilTeamUser();
                $member->team_id = $params['id'];
                $member->user_id = $userId;
                $status = $member->save();
            }
        }

        return new CollectionPaginatedResponse([]);
    }

    public function detail($id)
    {
        $this->checkIsAuthenticated();

        $team = KorwilTeam::findFirst($id);

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

        $detail = $team->getDetail();

        return new CollectionPaginatedResponse([$detail]);
    }
}
