<?php

class KorwilFaqController extends BaseController {

    public function list() {
        // get: 
        // 1. list of FAQ
        // 2. list of FAQ Categories
        // 3. number of FAQ for each category

        $getParams = $this->request->get();
        $params = $this->validate($getParams,[
            'id_category' => ['validators' => ['digit']],
            'limit' => ['validators' => ['digit']],
            'offset' => ['validators' => ['digit']],
        ]);
        $params['limit'] = $this->getDefaultLimit($getParams);
        $params['offset'] = array_key_exists('offset', $getParams) ? $getParams['offset'] : 0;

        $categories = []; 
        $faqCounts = [];
        if (is_null($params['id_category'])) {
            // ambil juga korwil FAQ categories, hanya jika id_category kosong (halaman pertama ketika onPageLoad)
            $categories = KorwilFaqCategory::find([
                'columns' => ['id', 'name'],
                'conditions' => 'deleted_at is null',
                'order' => 'id'
            ]);
            if (sizeof($categories) === 0) {
                $output = [
                    'list' => [],
                    'categories' => [],
                    'faqCounts' => []
                ];
                return new PaginatedResponse($output, 0, $params['limit'], $params['offset']);
            }
            foreach($categories as $index => $category) {
                $faqCounts[$index] = KorwilFaq::count([
                    'conditions' => 'deleted_at is null and id_category = :id_category:',
                    'bind' => [
                        'id_category' => $category->id
                    ]
                ]);
            }
            $params['id_category'] = $categories[0]->id; // if no id_category, default: 1
        }
        $where = 'id_category = :id_category: and deleted_at is null';
        $bind = [
            'id_category' => $params['id_category']
        ];

        // get the FAQ list
        $faqList = KorwilFaq::find([
            'columns' => ['id', 'question', 'answer', 'id_category'],
            'conditions' => $where,
            'bind' => $bind,
            'limit' => $params['limit'],
            'offset' => $params['offset'],
            'order' => 'id'
        ]);

        $totalRecords = KorwilFaq::count([
            'columns' => ['id', 'question', 'answer', 'id_category'],
            'conditions' => $where,
            'bind' => $bind
        ]);

        // prepare the output
        $output = [
            'list' => $faqList
        ];
        if (sizeof($categories) > 0) {
            $output['categories'] = $categories;
            $output['faqCounts'] = $faqCounts;
        }

        // send to client
        return new PaginatedResponse($output, $totalRecords, $params['limit'], $params['offset']);
    }

    public function upsertFaq() {
        // insert or update FAQ
        $this->checkScopes(['korsupgah.admin']);
        $post = $this->request->getJsonRawBody(true);
        $params = $this->validate(
            $post,
            [
                'id' => ['validators' => []],
                'question' => ['validators' => ['required']],
                'answer' => ['validators' => ['required']],
                'id_category' => ['validators' => ['required']]
            ]
        );

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

        if (!isset($params['id'])) {
            // insert
            $model = new KorwilFaq();
            $model->question = $params['question'];
            $model->answer = $params['answer'];
            $model->id_category = $params['id_category'];
            $model->created_by = $this->shared->user->um_id;
            $model->created_at = $date;
        } else {
            // update
            $model = KorwilFaq::findFirst([
                'conditions' => 'id = :id:',
                'bind' => [
                    'id' => $params['id']
                ]
            ]);
            if (!$model) {
                throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "Data tidak ditemukan");
            }
            // print_r($model->toArray()); die;
            $model->question = $params['question'];
            $model->answer = $params['answer'];
            $model->id_category = $params['id_category'];
            $model->updated_by = $this->shared->user->um_id;
            $model->updated_at = $date;
        }

        if (!$model->save()) {
            throw new CustomErrorException(BaseResponse::SQL_ERROR, "Gagal menyimpan data");
        }

        $response = [
            'id' => intval($model->id),
            'question' => $model->question, 
            'answer' => $model->answer,
            'id_category' => $model->id_category
        ];

        return new SimpleResponse($response);
    }

    public function upsertFaqCategory() {
        // update / insert jaga.korwil_faq_category

        $this->checkScopes(['korsupgah.admin']);
        $post = $this->request->getJsonRawBody(true);
        $params = $this->validate(
            $post,
            [
                'id' => ['validators' => []],
                'name' => ['validators' => ['required']]
            ]
        );

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

        if (!isset($params['id'])) {
            // insert
            $model = new KorwilFaqCategory();
            $model->name = $params['name'];
            $model->created_by = $this->shared->user->um_id;
            $model->created_at = $date;
        } else {
            // update
            $model = KorwilFaqCategory::findFirst([
                'conditions' => 'id = :id:',
                'bind' => [
                    'id' => $params['id']
                ]
            ]);
            if (!$model) {
                throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "Data tidak ditemukan");
            }
            $model->name = $params['name'];
            $model->updated_by = $this->shared->user->um_id;
            $model->updated_at = $date;
        }

        if (!$model->save()) {
            throw new CustomErrorException(BaseResponse::SQL_ERROR, "Gagal menyimpan data");
        }

        $response = [
            'id' => intval($model->id),
            'name' => $model->name
        ];

        return new SimpleResponse($response);
    }

    public function deleteFaq($id) {
        // soft delete FAQ
        $this->checkScopes(['korsupgah.admin']);
        
        $date = date('Y-m-d H:i:s');
        $model = KorwilFaq::findFirst(intval($id));
        if (!$model) {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "Data tidak ditemukan");
        }
        $model->deleted_by = $this->shared->user->um_id;
        $model->deleted_at = $date;
        if (!$model->save()) {
            throw new CustomErrorException(BaseResponse::SQL_ERROR, "Gagal menghapus FAQ");
        }
        return new SimpleResponse([]);
    }

    public function deleteFaqCategory($id) {
        // soft delete FAQ Category & related FAQ's
        $this->checkScopes(['korsupgah.admin']);
        
        $date = date('Y-m-d H:i:s');
        $model = KorwilFaqCategory::findFirst(intval($id));
        if (!$model) {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "Data tidak ditemukan");
        }
        $model->deleted_by = $this->shared->user->um_id;
        $model->deleted_at = $date;
        if (!$model->save()) {
            throw new CustomErrorException(BaseResponse::SQL_ERROR, "Gagal menghapus FAQ");
        }

        // hapus FAQ's terkait
        $faqList = KorwilFaq::find([
            'conditions' => 'id_category = :id:',
            'bind' => [
                'id' => $id
            ]
        ]);
        if (!$faqList) {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "Data tidak ditemukan");
        }
        foreach($faqList as $faq) {
            $faq->deleted_by = $this->shared->user->um_id;
            $faq->deleted_at = $date;
            if (!$faq->save()) {
                throw new CustomErrorException(BaseResponse::SQL_ERROR, "Gagal menghapus FAQ");
            }
        }
        return new SimpleResponse([]);
    }
}