<?php
include dirname(__FILE__) . '/nocache.php';

include dirname(__FILE__) . '/dbconfig.php';
include dirname(__FILE__) . '/error.php';
include dirname(__FILE__) . '/utils.php';

include dirname(__FILE__) . '/session.php';

function check() {
check_session();

$lang = setTextDomain('myapps');

$options = array(PDO::MYSQL_ATTR_INIT_COMMAND=>"SET CHARACTER SET 'utf8'");
$dbh = new PDO(DB_DSN, DB_USER, DB_PASSWORD, $options);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

error_reporting(E_ALL & ~E_NOTICE);

if ($lang == 'ja_JP') {
  $cat = 'category_ja';
  $title = 'title_ja';
  $desc = 'desc_ja';
} else {
  $cat = 'category_en';
  $title = 'title_en';
  $desc = 'desc_en';
}

$sql = <<<END
SELECT
  t.*,
  c.category_ja,
  c.category_en
FROM (
SELECT
  i.id,
  i.info_date,
  i.category_id,
  i.link,
  i.title_ja,
  i.title_en,
  i.desc_ja,
  i.desc_en,
  IF(i.id>u.info_read,1,0) as unread,
  'G' as `type`
FROM
  information as i
INNER JOIN
  userdata as u
WHERE
  u.member_id=:mid
AND
 i.del_flg='0'
AND
(
  i.info_date >= LEAST(DATE_ADD(NOW(),INTERVAL -30 DAY),
                       IFNULL(u.last_login,NOW()))
or
  i.id > u.info_read
)
UNION
SELECT
  i.id,
  i.info_date,
  i.category_id,
  NULL,
  i.title_ja,
  i.title_en,
  i.desc_ja,
  i.desc_en,
  IF(i.id>u.personal_info_read,1,0) as unread,
  'P' as `type`
FROM
  personal_info as i
INNER JOIN
  userdata as u
ON
  u.id=i.user_id
WHERE
  u.member_id=:mid
AND
 i.del_flg='0'
AND
(
  i.info_date >= LEAST(DATE_ADD(NOW(),INTERVAL -30 DAY),
                       IFNULL(u.last_login,NOW()))
or
  i.id > u.personal_info_read
)) as t
INNER JOIN
  category_master as c
ON
  c.id=t.category_id
AND
  c.del_flg='0'
order by
  info_date desc, id desc
END;

  $stmt = $dbh->prepare($sql);
  $stmt->execute(array(':mid' => $_SESSION['member_id']));
  $list = $stmt->fetchAll(PDO::FETCH_ASSOC);
  $result = array();
  foreach( $list as $item ) {
    $result[] = array(
      'info_id' => $item['id'],
      'date' => $item['info_date'],
      'category_id' => $item['category_id'],
      'category' => $item[$cat],
      'link' => $item['link'],
      'title' => $item[$title],
      'desc' => $item[$desc],
      'unread' => $item['unread'],
      'type' => $item['type']
    );
  }
  echo json_encode(array('info' => $result));
}

wrap('check');
