<?php
/**
 * いいね！用関数ファイル
 * KUNIHARU Tsujioka 2010/02/01
 * license new BSD style
 */
/**
 * いいね！の表示名称を返す
 * @return mixed
 */
function good_constant()
{
    $data = array(
          array('name' => 'イイネ！'
              , 'ktai_name' => 'イイネ！'
              , 'ktai_total' => '総ｲｲﾈ!数'),
          array('name' => 'ヨシヨシ( ´･ω･)ﾉ(´д｀)'
              , 'ktai_name' => 'ヨシヨシ'
              , 'ktai_total' => '総ﾖｼﾖｼ数'),
        );
    return $data ;
}
/**
 * いいね！の数を返す
 * @param  int c_diary_id
 * @param  int good_type
 * @return mixed
 */
function good_count($c_diary_id, $good_type)
{
    $sql = "SELECT good_count FROM " . MYNETS_PREFIX_NAME . "good WHERE c_diary_id = ? AND good_type = ?";
    $params = array(intval($c_diary_id), intval($good_type));
    return db_get_one($sql, $params);
}

function good_count_all($c_diary_id)
{
    $sql = "SELECT good_type, good_count FROM " . MYNETS_PREFIX_NAME . "good WHERE c_diary_id = ?";
    $params = array(intval($c_diary_id));
    $all = db_get_all($sql, $params);
    
    $result = array() ;
    if ($all) {
        foreach ($all as $key=>$value) {
            $good_type = $value['good_type'] ;
            $good_count = $value['good_count'] ;
            $result[$good_type] = $good_count ;
        }
    }
    
    return $result ;
}

/**
 * いいね！を登録する
 * @param  int c_diary_id
 * @param  int c_member_id
 * @param  int good_type
 * @return bool
 */
function good_insert($c_diary_id, $c_member_id, $good_type)
{
    $sql = "SELECT count(*) as count FROM  " . MYNETS_PREFIX_NAME . "good_user WHERE c_member_id = ? AND c_diary_id = ? AND good_type = ?";
    $params = array(intval($c_member_id), intval($c_diary_id), intval($good_type));
    $result = db_get_one($sql, $params);
    if ($result)
    {
        //すでにGoodしている
        return 0;
    }

    $c_diary = db_diary_get_c_diary4id($c_diary_id);

    $data = array(
        'c_diary_id' => intval($c_diary_id),
        'c_member_id' => intval($c_member_id),
        'c_diary_member_id' => $c_diary['c_member_id'],
        'good_type' => intval($good_type),
        'r_datetime' => db_now()
    );
    $result = db_insert(MYNETS_PREFIX_NAME . 'good_user', $data);
    if ($result)
    {
        return _good_update($c_diary_id, $good_type);
    }
    return FALSE;
}

function _good_update($c_diary_id, $good_type)
{
    $check = good_count($c_diary_id, $good_type);
    if ($check)
    {
        $sql = "UPDATE  " . MYNETS_PREFIX_NAME . "good SET good_count = good_count + 1 WHERE c_diary_id = ? AND good_type = ?";
        $params = array(intval($c_diary_id), intval($good_type));
        db_query($sql, $params);
    }
    else
    {
        $data = array(
            'c_diary_id' => intval($c_diary_id),
            'r_datetime' => db_now(),
            'good_type' => intval($good_type),
            'good_count' => 1
        );
        db_insert(MYNETS_PREFIX_NAME . 'good', $data);
    }
    return TRUE;
}

/**
 * いいね！を登録したユーザデータを取得
 * @param  int c_diary_id
 * @param  int page_size
 * @param  int page
 * @param  int good_type
 * @return bool
 * 一部のユーザー情報を持って返却。$good_user['user']['c_member_id']など
 */
function good_user($c_diary_id, $good_type, $page_size = 25, $page = 1)
{
    $sql = "SELECT * FROM  " . MYNETS_PREFIX_NAME . "good_user WHERE c_diary_id = ? AND good_type = ? ORDER BY r_datetime DESC ";
    $params = array(intval($c_diary_id), intval($good_type));
    $result = db_get_all_page($sql, $page, $page_size, $params);
    if ($result)
    {
        foreach ($result as $key=>$value)
        {
            $user = db_common_c_member4c_member_id_LIGHT($value['c_member_id']);
            //OpenPNE Ver2.12～ ? 関数名が新しくなってる場合はこちら
            //$user = db_member_c_member4c_member_id_LIGHT($value['c_member_id']);
            $result[$key]['nickname'] = $user['nickname'];
            $result[$key]['image_filename'] = $user['image_filename'];
        }
    }
    return $result;
}

/**
 * いいね！を削除する
 * @param  int c_diary_id
 * @param  int c_member_id
 * @param  int good_type
 * @return bool
 */
function good_delete($c_diary_id, $c_member_id, $good_type)
{

    $result = good_exists($c_diary_id, $c_member_id, $good_type) ;
    if (!$result)
    {
        //すでに取消ししている
        return 0;
    }

    $check = good_count($c_diary_id, $good_type);
    if ($check > 1)
    {
        //Good数をgoodからマイナスしておく
        $sql = "update " . MYNETS_PREFIX_NAME . "good set good_count=good_count-1 where c_diary_id=? AND good_type = ?";
        $params = array(intval($c_diary_id), intval($good_type));
        db_query($sql, $params);
    }
    else
    {
        //goodを削除する
        $sql = "DELETE FROM " . MYNETS_PREFIX_NAME . "good WHERE c_diary_id = ? AND good_type = ? ";
        $params = array(intval($c_diary_id), intval($good_type));

        db_query($sql, $params);
    }

    $sql = "DELETE FROM " . MYNETS_PREFIX_NAME . "good_user WHERE c_member_id = ? AND c_diary_id = ? AND good_type = ? ";
    $params = array(intval($c_member_id), intval($c_diary_id), intval($good_type));

    return db_query($sql, $params);

}

/**
 * いいね！データを削除する（日記削除処理から呼ばれることを想定）
 * @param  int c_diary_id
 * @return bool
 */
function good_data_delete($c_diary_id)
{

    //goodを削除する
    $sql = "DELETE FROM " . MYNETS_PREFIX_NAME . "good WHERE c_diary_id = ? ";
    $params = array(intval($c_diary_id));

    db_query($sql, $params);

    //good_userを削除する
    $sql = "DELETE FROM " . MYNETS_PREFIX_NAME . "good_user WHERE c_diary_id = ? ";

    return db_query($sql, $params);

}


/**
 * いいね！が登録済みか否かを返す
 * @param  int c_diary_id
 * @param  int c_member_id
 * @param  int good_type
 * @return mixed
 */
function good_exists($c_diary_id, $c_member_id, $good_type)
{
    $sql = "SELECT count(*) as count FROM  " . MYNETS_PREFIX_NAME . "good_user WHERE c_member_id = ? AND c_diary_id = ? AND good_type = ? ";
    $params = array(intval($c_member_id), intval($c_diary_id), intval($good_type));
    return db_get_one($sql, $params);
}

function good_exists_all($c_diary_id, $c_member_id)
{
    $sql = "SELECT good_type, count(*) as count FROM  " . MYNETS_PREFIX_NAME . "good_user WHERE c_member_id = ? AND c_diary_id = ? GROUP BY good_type ";
    $params = array(intval($c_member_id), intval($c_diary_id));
    $all = db_get_all($sql, $params);
    
    $result = array() ;
    if ($all) {
        foreach ($all as $key=>$value) {
            $good_type = $value['good_type'] ;
            $count = $value['count'] ;
            $result[$good_type] = $count ;
        }
    }
    
    return $result ;
}

/**
 * いいね！を押した日記データを取得
 * @param  int c_member_id
 * @param  int page_size
 * @param  int page
 * @param  int good_type
 * @return mixed
 */
function good_diary_list($c_member_id, $good_type, $page, $page_size)
{
    $blocked = db_member_access_block_list4c_member_id_to($c_member_id);
    $blocked[] = $c_member_id;
    $except_ids = implode(',', $blocked);

    $friends = db_friend_c_member_id_list($c_member_id);
    $friend_ids = implode(',', $friends);

    $sql = "SELECT "
                . "SQL_CALC_FOUND_ROWS "
                . "d.c_diary_id, "
                . "d.subject, "
                . "d.c_member_id, "
                . "d.e_datetime, "
                . "gu.r_datetime, "
                . "d.image_filename_1, "
                . "d.image_filename_2, "
                . "d.image_filename_3, "
                . "d.public_flag, "
                . "d.comment_count, "
                . "d.etsuran_count "
         . "FROM "
                . MYNETS_PREFIX_NAME . "c_diary AS d "
         . "INNER JOIN "
                . MYNETS_PREFIX_NAME . "good_user AS gu "
         . "USING "
                . "(c_diary_id) "
         . "WHERE "
                . "gu.c_member_id = ? "
         . "AND "
                . "gu.good_type = ? "
         . "AND "
                . "gu.c_diary_id = d.c_diary_id "
         . "AND "
                . "d.c_member_id NOT IN (" . $except_ids . ") "
         . "AND ("
                . "d.public_flag = 'public' "
                . "OR "
                . "d.public_flag = 'open' "
                . "OR ("
                    . "d.public_flag = 'friend' "
                    . "AND "
                    . "d.c_member_id IN (" . $friend_ids . ")"
                    . ") "
                . ") "
          . "ORDER BY "
                . "gu.r_datetime DESC ";
    $params = array(intval($c_member_id), intval($good_type));
    $list = db_get_all_page($sql, $page, $page_size, $params);

    $sql = "SELECT FOUND_ROWS() ";
    $total_num = db_get_one($sql);

    foreach ($list as $key => $value) {
        $list[$key] += db_common_c_member4c_member_id_LIGHT($value['c_member_id']);
    }

    $is_prev = false;
    $is_next = false;
    if ($total_num) {
        $is_prev = (bool)($page > 1);
        $is_next = (bool)($page < ceil($total_num / $page_size));
    }
    return array($list, $is_prev, $is_next, $total_num);
}

/**
 * いいね！を押された日記データを取得
 * @param  int c_diary_member_id
 * @param  int page_size
 * @param  int page
 * @param  int good_type
 * @return mixed
 * 一部のユーザー情報を持って返却。$good_user['user']['c_member_id']など
 * 日記情報を持って返却。
 */
function good_rev_diary_list($c_member_id, $good_type, $page, $page_size)
{
//    $sql = "SELECT SQL_CALC_FOUND_ROWS  gu.* FROM  " . MYNETS_PREFIX_NAME . "good_user AS gu "
//         . " WHERE c_diary_member_id = ? AND good_type = ? ORDER BY r_datetime DESC ";
    $sql = "SELECT "
                . "SQL_CALC_FOUND_ROWS "
                . "d.c_diary_id, "
                . "d.subject, "
                . "gu.c_member_id, "
                . "d.e_datetime, "
                . "gu.r_datetime, "
                . "d.image_filename_1, "
                . "d.image_filename_2, "
                . "d.image_filename_3, "
                . "d.public_flag, "
                . "d.comment_count, "
                . "d.etsuran_count "
         . "FROM "       . MYNETS_PREFIX_NAME . "c_diary AS d "
         . "INNER JOIN " . MYNETS_PREFIX_NAME . "good_user AS gu "
         . "USING (c_diary_id) "
         . "WHERE gu.c_diary_member_id = ? "
         . "AND   gu.good_type = ? "
//         . "AND   gu.c_diary_id = d.c_diary_id "
         . "ORDER BY gu.r_datetime DESC ";

    $params = array(intval($c_member_id), intval($good_type));
    $list = db_get_all_page($sql, $page, $page_size, $params);

    $sql = "SELECT FOUND_ROWS() ";
    $total_num = db_get_one($sql);

    foreach ($list as $key => $value) {
        $list[$key] += db_common_c_member4c_member_id_LIGHT($value['c_member_id']);
    }

    $is_prev = false;
    $is_next = false;
    if ($total_num) {
        $is_prev = (bool)($page > 1);
        $is_next = (bool)($page < ceil($total_num / $page_size));
    }
    return array($list, $is_prev, $is_next, $total_num);
}


/**
 * Change Log
   1. db_get_one($sql) を db_get_one($sql, $params) に修正
   2. function good_user に ORDER BY 条件を追加、ユーザ情報の持ち方を変更
   3. 各テーブル名に MYNETS_PREFIX_NAME を追加
   4. function good_delete を新規追加
   5. SQL文の囲み文字を""に統一
   6. function good_delete_all を新規追加
   7. diary.php の function p_h_diary_comment_list_c_diary_my_comment_list4c_member_id を
      参考にして、function good_diary_list を追加 ('2010/11/19-20)
   8. いいね! Ver.6 ('2013/03/20)
   8-1. good_data_delete 以外のfunctionのパラメータに、good_type を追加 
   8-2. good_user テーブルの登録値に、日記のメンバIDを追加
   8-3. good_diary_list のヘッダコメントを追加
   8-4. good_reversed_diary_list を追加。
 *
 */
