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

/**
 * Qna_write
 */


class Qna_write 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("어플 아이디가 넘어오지 않았습니다");
        }

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


		$sessionuser = $this->CI->User_model->get_by_token($app_id, $token);
		if ( ! element('user_id', $sessionuser)) {
			$this->CI->apilib->make_error("로그인 한 회원만 문의를 작성할 수 있습니다");
		}
		
		if ( ! $this->CI->input->post('qna_title')) {
			$this->CI->apilib->make_error("문의 제목을 입력하여 주십시오.");
		}
		if ( ! $this->CI->input->post('qna_content')) {
			$this->CI->apilib->make_error("문의 내용을 입력하여 주십시오.");
		}



        $uploadfiledata = '';
        $uploadfiledata2 = '';
		$this->CI->load->library('upload');
		if (isset($_FILES) && isset($_FILES['upload_file']) && isset($_FILES['upload_file']['name']) && is_array($_FILES['upload_file']['name'])) {
			$filecount = count($_FILES['upload_file']['name']);
			$upload_path = config_item('uploads_dir') . '/files/';
			if (is_dir($upload_path) === false) {
				mkdir($upload_path, 0707);
				$file = $upload_path . 'index.php';
				$f = @fopen($file, 'w');
				@fwrite($f, '');
				@fclose($f);
				@chmod($file, 0644);
			}
			$upload_path .= cdate('Y') . '/';
			if (is_dir($upload_path) === false) {
				mkdir($upload_path, 0707);
				$file = $upload_path . 'index.php';
				$f = @fopen($file, 'w');
				@fwrite($f, '');
				@fclose($f);
				@chmod($file, 0644);
			}
			$upload_path .= cdate('m') . '/';
			if (is_dir($upload_path) === false) {
				mkdir($upload_path, 0707);
				$file = $upload_path . 'index.php';
				$f = @fopen($file, 'w');
				@fwrite($f, '');
				@fclose($f);
				@chmod($file, 0644);
			}

			foreach ($_FILES['upload_file']['name'] as $i => $value) {
				if ($value) {
					$uploadconfig = '';
					$uploadconfig['upload_path'] = $upload_path;
					$uploadconfig['allowed_types'] = '*';
					$uploadconfig['max_size'] = 10240;
					$uploadconfig['encrypt_name'] = true;

					$this->CI->upload->initialize($uploadconfig);
					$_FILES['userfile']['name'] = $_FILES['upload_file']['name'][$i];
					$_FILES['userfile']['type'] = $_FILES['upload_file']['type'][$i];
					$_FILES['userfile']['tmp_name'] = $_FILES['upload_file']['tmp_name'][$i];
					$_FILES['userfile']['error'] = $_FILES['upload_file']['error'][$i];
					$_FILES['userfile']['size'] = $_FILES['upload_file']['size'][$i];
					if ($this->CI->upload->do_upload()) {
						$filedata = $this->CI->upload->data();

						$uploadfiledata[$i]['ufi_filename'] = cdate('Y') . '/' . cdate('m') . '/' . element('file_name', $filedata);
						$uploadfiledata[$i]['ufi_originname'] = element('orig_name', $filedata);
						$uploadfiledata[$i]['ufi_filesize'] = intval(element('file_size', $filedata) * 1024);
						$uploadfiledata[$i]['ufi_width'] = element('image_width', $filedata) ? element('image_width', $filedata) : 0;
						$uploadfiledata[$i]['ufi_height'] = element('image_height', $filedata) ? element('image_height', $filedata) : 0;
						$uploadfiledata[$i]['ufi_type'] = str_replace('.', '', element('file_ext', $filedata));
						$uploadfiledata[$i]['is_image'] = element('is_image', $filedata) ? element('is_image', $filedata) : 0;
					} else {
						$file_error = $this->CI->upload->display_errors();
						break;
					}
				}
			}
		}
		if (isset($_FILES) && isset($_FILES['upload_file_update'])
			&& isset($_FILES['upload_file_update']['name'])
			&& is_array($_FILES['upload_file_update']['name'])
			&& $file_error === '') {
			$filecount = count($_FILES['upload_file_update']['name']);
			$upload_path = config_item('uploads_dir') . '/files/';
			if (is_dir($upload_path) === false) {
				mkdir($upload_path, 0707);
				$file = $upload_path . 'index.php';
				$f = @fopen($file, 'w');
				@fwrite($f, '');
				@fclose($f);
				@chmod($file, 0644);
			}
			$upload_path .= cdate('Y') . '/';
			if (is_dir($upload_path) === false) {
				mkdir($upload_path, 0707);
				$file = $upload_path . 'index.php';
				$f = @fopen($file, 'w');
				@fwrite($f, '');
				@fclose($f);
				@chmod($file, 0644);
			}
			$upload_path .= cdate('m') . '/';
			if (is_dir($upload_path) === false) {
				mkdir($upload_path, 0707);
				$file = $upload_path . 'index.php';
				$f = @fopen($file, 'w');
				@fwrite($f, '');
				@fclose($f);
				@chmod($file, 0644);
			}

			foreach ($_FILES['upload_file_update']['name'] as $i => $value) {
				if ($value) {
					$uploadconfig = '';
					$uploadconfig['upload_path'] = $upload_path;
					$uploadconfig['allowed_types'] = '*';
					$uploadconfig['max_size'] = 10240;
					$uploadconfig['encrypt_name'] = true;
					$this->CI->upload->initialize($uploadconfig);
					$_FILES['userfile']['name'] = $_FILES['upload_file_update']['name'][$i];
					$_FILES['userfile']['type'] = $_FILES['upload_file_update']['type'][$i];
					$_FILES['userfile']['tmp_name'] = $_FILES['upload_file_update']['tmp_name'][$i];
					$_FILES['userfile']['error'] = $_FILES['upload_file_update']['error'][$i];
					$_FILES['userfile']['size'] = $_FILES['upload_file_update']['size'][$i];
					if ($this->CI->upload->do_upload()) {
						$filedata = $this->CI->upload->data();

						$olduploadfile = $this->CI->Upload_file_model->get_one($i);
						if ((int) element('origin_id', $olduploadfile) !== (int) element('qna_id', $getdata)) {
							alert('잘못된 접근입니다');
						}
						@unlink(config_item('uploads_dir') .  '/files/' . element('ufi_filename', $oldpostfile));

						$uploadfiledata2[$i]['ufi_id'] = $i;
						$uploadfiledata2[$i]['ufi_filename'] = cdate('Y') . '/' . cdate('m') . '/' . element('file_name', $filedata);
						$uploadfiledata2[$i]['ufi_originname'] = element('orig_name', $filedata);
						$uploadfiledata2[$i]['ufi_filesize'] = intval(element('file_size', $filedata) * 1024);
						$uploadfiledata2[$i]['ufi_width'] = element('image_width', $filedata)
							? element('image_width', $filedata) : 0;
						$uploadfiledata2[$i]['ufi_height'] = element('image_height', $filedata)
							? element('image_height', $filedata) : 0;
						$uploadfiledata2[$i]['ufi_type'] = str_replace('.', '', element('file_ext', $filedata));
						$uploadfiledata2[$i]['is_image'] = element('is_image', $filedata)
							? element('is_image', $filedata) : 0;
					} else {
						$file_error = $this->CI->upload->display_errors();
						break;
					}
				}
			}
		}


		$insertdata = array(
			'app_id' => $app_id,
			'user_id' => element('user_id', $sessionuser),
			'user_name' => element('user_username', $sessionuser),
			'qna_title' => $this->CI->input->post('qna_title'),
			'qna_content' => $this->CI->input->post('qna_content'),
			'created_at' => cdate('Y-m-d H:i:s'),
		);
		$qna_id = $this->CI->Qna_model->insert($insertdata);



		$file_updated = false;
		$file_changed = false;
		if (is_array($uploadfiledata) && count($uploadfiledata) > 0) {
			foreach ($uploadfiledata as $pkey => $pval) {
				if ($pval) {
					$fileupdate = array(
						'origin_id' => $qna_id,
						'origin_table' => 'qna',
						'user_id' => $this->CI->userlib->item('user_id'),
						'ufi_originname' => element('ufi_originname', $pval),
						'ufi_filename' => element('ufi_filename', $pval),
						'ufi_filesize' => element('ufi_filesize', $pval),
						'ufi_width' => element('ufi_width', $pval),
						'ufi_height' => element('ufi_height', $pval),
						'ufi_type' => element('ufi_type', $pval),
						'ufi_is_image' => element('is_image', $pval),
						'ufi_datetime' => cdate('Y-m-d H:i:s'),
						'ufi_ip' => $this->CI->input->ip_address(),
					);
					$file_id = $this->CI->Upload_file_model->insert($fileupdate);
					$file_updated = true;
				}
			}
			$file_changed = true;
		}
		if (is_array($uploadfiledata2) && count($uploadfiledata2) > 0) {
			foreach ($uploadfiledata2 as $pkey => $pval) {
				if ($pval) {
					$fileupdate = array(
						'user_id' => $this->userlib->item('user_id'),
						'ufi_originname' => element('ufi_originname', $pval),
						'ufi_filename' => element('ufi_filename', $pval),
						'ufi_filesize' => element('ufi_filesize', $pval),
						'ufi_width' => element('ufi_width', $pval),
						'ufi_height' => element('ufi_height', $pval),
						'ufi_type' => element('ufi_type', $pval),
						'ufi_is_image' => element('is_image', $pval),
						'ufi_datetime' => cdate('Y-m-d H:i:s'),
						'ufi_ip' => $this->CI->input->ip_address(),
					);
					$this->CI->Upload_file_model->update($pkey, $fileupdate);
					$file_changed = true;
				}
			}
		}

		$arr = array(
			'result' => 'ok',
			'token' => $token,
			'app_id' => $app_id,
			'datetime' => cdate('Y-m-d H:i:s'),
		);
		return $arr;

	}


}
