<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Qna
 */


class Qna extends CI_Controller
{

    private $CI;

    function __construct()
    {
        $this->CI = & get_instance();

    }

	function main()
	{

		if ( ! $this->CI->input->post_get('token')) {
			$this->CI->apilib->make_error("토큰 값이 넘어오지 않았습니다");
        }
		$token = $this->CI->input->post_get('token');


        $app_id = (int) trim($this->CI->input->post_get('app_id'));
        if (empty($app_id)) {
			$this->CI->apilib->make_error("어플 아이디가 넘어오지 않았습니다");
        }

		$sessionuser = $this->CI->User_model->get_by_token($app_id, $token);
		if ( ! element('user_id', $sessionuser)) {
			$this->CI->apilib->make_error("로그인 한 회원만 접근이 가능합니다");
		}

		$user_id = element('user_id', $sessionuser);

		$this->CI->load->model(array('Qna_model', 'Upload_file_model'));

        $where = array(
			'app_id' => $app_id,
			'user_id' => $user_id,
		);
		$data = $this->CI->Qna_model->get('', '', $where, '', '', 'qna_id', 'desc');
		$result = array();
		$count = 0;
		if ($data) {
			foreach ($data as $key => $value) {

				$uploadwhere = array(
					'origin_table' => 'qna',
					'origin_id' => element('qna_id', $value),
				);
				$file = $this->CI->Upload_file_model->get('', '', $uploadwhere, '', '', 'ufi_id', 'ASC');
				$files = array();
				if ($file && is_array($file)) {
					foreach ($file as $key2 => $val2) {
						$files[] = site_url('uploads/files/' . element('ufi_filename', $val2));
					}
				}

				$result[$key]['qna_id'] = html_escape(element('qna_id', $value));
				$result[$key]['user_id'] = html_escape(element('user_id', $value));
				$result[$key]['user_name'] = html_escape(element('user_name', $value));
				$result[$key]['qna_title'] = html_escape(element('qna_title', $value));
				$result[$key]['qna_content'] = html_escape(element('qna_content', $value));
				$result[$key]['qna_answer'] = html_escape(element('qna_answer', $value));
				$result[$key]['files'] = $files;
				$result[$key]['created_at'] = html_escape(element('created_at', $value));
				$result[$key]['answer_at'] = html_escape(element('answer_at', $value));
				$result[$key]['has_answer'] = element('has_answer', $value);
				$count++;
			}
		}

		$arr = array(
			'result' => 'ok',
			'token' => $token,
			'app_id' => $app_id,
			'count' => $count,
			'list' => $result,
		);
		return $arr;

	}


}
