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

/**
 * Contents_like
 */


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

        $con_id = (int) trim($this->CI->input->post('con_id'));
        if (empty($con_id)) {
			$this->CI->apilib->make_error("데이터 고유 아이디가 넘어오지 않았습니다");
        }

		$this->CI->load->model(array('Contents_model', 'User_model', 'Contents_like_model'));

		$sessionuser = $this->CI->User_model->get_by_token($app_id, $token);
		//if ( ! element('user_id', $sessionuser)) {
		//	$this->CI->apilib->make_error("로그인 한 회원만 Like 할 수 있습니다");
		//}

		$contents = $this->CI->Contents_model->get_one($con_id);
		if ( ! element('con_id', $contents)) {
			$this->CI->apilib->make_error("존재하지 않는 컨텐츠입니다.");
		}

		$likewhere = array(
			'con_id' => $con_id,
			'user_token' => $token,
		);
		$like = $this->CI->Contents_like_model->get_one('', '', $likewhere);
		if (element('like_id', $like)) {
			$this->CI->Contents_like_model->delete(element('like_id', $like));
			$type = 'N';
			$this->CI->Contents_model->minus_like_count($con_id);
			$like_count = element('con_like', $contents) - 1;
		}
		if ( ! element('like_id', $like)) {
			$user_id = element('user_id', $sessionuser) ? element('user_id', $sessionuser) : 0;

			$insertdata = array(
				'con_id' => element('con_id', $contents),
				'app_id' => $app_id,
				'user_id' => $user_id,
				'user_token' => $token,
				'target_user_id' => element('user_id', $contents),
				'like_at' => cdate('Y-m-d H:i:s'),
			);
			$like_id = $this->CI->Contents_like_model->insert($insertdata);
			$type = 'Y';
			$this->CI->Contents_model->plus_like_count($con_id);
			$like_count = element('con_like', $contents) + 1;
		}

		$arr = array(
			'result' => 'ok',
			'token' => $token,
			'app_id' => $app_id,
			'con_id' => $con_id,
			'type' => $type,
			'like_count' => $like_count,
		);
		return $arr;

	}


}
