<?php

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

function check() {
$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);
setTimezone($dbh);

error_reporting(E_ALL & ~E_NOTICE);

$sql = "select distinct IFNULL(CONCAT('[',IF(u.exp_flg='1','',GROUP_CONCAT(distinct(CONCAT('\"',a.serial,'PC1\"')))),']'),'[]') as serial,u.member_id,u.member_pass from credential c inner join userdata u on u.member_id=c.member_id and u.del_flg='0' left outer join mqtt_auth a on a.member_id=c.member_id and a.del_flg='0' where c.token=:token and c.del_flg='0'";
$stmt = $dbh->prepare($sql);
$params = array(':token' => $_GET['token']);
$stmt->execute($params);

$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$result) {
  http_response_code(404);
  exit(0);
}

$sql = "select custom_code FROM user_custom WHERE member_id=:mids AND del_flg='0'";
$stmt = $dbh->prepare($sql);
$stmt->execute(array(':mids'=>$result['member_id']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$custom_map = array();
foreach($rows as $row) {
    if ($row['custom_code'] != '') {
        $custom_map[$row['custom_code']] = true;
    }
}

$sql = <<<EOF
SELECT
  pc.custom_code
FROM
  userdata as u
INNER JOIN
  activation as a
ON
  a.used=u.id
AND
  a.del_flg='0'
INNER JOIN
  plan_custom_master as pc
ON
  pc.plan_id=a.plan_id
AND
  pc.del_flg='0'
WHERE
  u.member_id=:mids
EOF;
$stmt = $dbh->prepare($sql);
$stmt->execute(array(':mids'=>$result['member_id']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) {
  $custom_map[$row['custom_code']] = true;
}

$custom_codes = array_keys($custom_map);

$array = [
  'clientId' => json_decode($result['serial'],true),
  'user' => $result['member_id'],
  'pass' => $result['member_pass'],
  'customCode' => $custom_codes
];
header('Content-Type: application/json');
echo json_encode($array);
}

try {
 check();
}
catch(Exception $e) {
  http_response_code(400);
  error_log($e->getMessage());
  error_log($e->getTraceAsString());
}
