<?php

$setupSQL = "";

// mc_members 表及字段（创建时包含所有最新字段）
$tablename = tablename('mc_members');
if (!pdo_tableexists('mc_members')){
    $setupSQL .= <<<EOF
CREATE TABLE IF NOT EXISTS $tablename (
  `uid` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `uniacid` int(10) UNSIGNED NOT NULL,
  `mobile` varchar(18) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` varchar(32) NOT NULL,
  `api_token` varchar(80) NULL DEFAULT null,
  `salt` varchar(8) NOT NULL,
  `groupid` int(11) NOT NULL,
  `credit1` decimal(10,2) UNSIGNED NOT NULL,
  `credit2` decimal(10,2) UNSIGNED NOT NULL,
  `credit3` decimal(10,2) UNSIGNED NOT NULL,
  `credit4` decimal(10,2) UNSIGNED NOT NULL,
  `credit5` decimal(10,2) UNSIGNED NOT NULL,
  `credit6` decimal(10,2) NOT NULL,
  `createtime` int(10) UNSIGNED NOT NULL,
  `realname` varchar(10) NOT NULL,
  `nickname` varchar(20) NOT NULL,
  `avatar` varchar(255) NOT NULL,
  `qq` varchar(15) NOT NULL,
  `vip` tinyint(3) UNSIGNED NOT NULL,
  `gender` tinyint(1) NOT NULL,
  `birthyear` smallint(6) UNSIGNED NOT NULL,
  `birthmonth` tinyint(3) UNSIGNED NOT NULL,
  `birthday` tinyint(3) UNSIGNED NOT NULL,
  `constellation` varchar(10) NOT NULL,
  `zodiac` varchar(5) NOT NULL,
  `telephone` varchar(15) NOT NULL,
  `idcard` varchar(30) NOT NULL,
  `studentid` varchar(50) NOT NULL,
  `grade` varchar(10) NOT NULL,
  `address` varchar(255) NOT NULL,
  `zipcode` varchar(10) NOT NULL,
  `nationality` varchar(30) NOT NULL,
  `resideprovince` varchar(30) NOT NULL,
  `residecity` varchar(30) NOT NULL,
  `residedist` varchar(30) NOT NULL,
  `graduateschool` varchar(50) NOT NULL,
  `company` varchar(50) NOT NULL,
  `education` varchar(10) NOT NULL,
  `occupation` varchar(30) NOT NULL,
  `position` varchar(30) NOT NULL,
  `revenue` varchar(10) NOT NULL,
  `affectivestatus` varchar(30) NOT NULL,
  `lookingfor` varchar(255) NOT NULL,
  `bloodtype` varchar(5) NOT NULL,
  `height` varchar(5) NOT NULL,
  `weight` varchar(5) NOT NULL,
  `alipay` varchar(30) NOT NULL,
  `msn` varchar(30) NOT NULL,
  `taobao` varchar(30) NOT NULL,
  `site` varchar(30) NOT NULL,
  `bio` text NOT NULL,
  `interest` text NOT NULL,
  `pay_password` varchar(30) NOT NULL,
  `user_from` tinyint(1) NOT NULL,
  PRIMARY KEY (`uid`),
  KEY `groupid` (`groupid`),
  KEY `uniacid` (`uniacid`),
  KEY `email` (`email`),
  KEY `mobile` (`mobile`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
EOF;
}else{
    //数据表存在时检查表结构完整性
    if(!pdo_fieldexists('mc_members', 'api_token')){
        $setupSQL .= "ALTER TABLE $tablename ADD `api_token` VARCHAR(80) NULL DEFAULT null AFTER `password`;";
    }
}


// mc_groups 表及字段
$tableGroup = tablename('mc_groups');
if (!pdo_tableexists('mc_groups')){
    $setupSQL .= <<<EOF
CREATE TABLE $tableGroup (
  `groupid` int(11) NOT NULL AUTO_INCREMENT,
  `uniacid` int(11) NOT NULL,
  `title` varchar(20) NOT NULL,
  `credit` int(10) UNSIGNED NOT NULL,
  `price` decimal(10,2) NOT NULL DEFAULT '0.00',
  `paytype` int(1) NOT NULL DEFAULT '0',
  `isdefault` tinyint(4) NOT NULL,
  PRIMARY KEY (`groupid`),
  KEY `uniacid` (`uniacid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
EOF;
}
if (pdo_tableexists('mc_groups') && !pdo_fieldexists('mc_groups','price')){
    $setupSQL .= "ALTER TABLE $tableGroup ADD `price` DECIMAL(10,2) NOT NULL DEFAULT '0.00' AFTER `credit`;";
}
if (pdo_tableexists('mc_groups') && !pdo_fieldexists('mc_groups','paytype')){
    $setupSQL .= "ALTER TABLE $tableGroup ADD `paytype` int(1) NOT NULL DEFAULT '0' AFTER `price`;";
}

// mc_member_fields 表及字段
$table_mc_member_fields = tablename('mc_member_fields');
if (!pdo_tableexists('mc_member_fields')){
    $setupSQL .= <<<EOF
CREATE TABLE $table_mc_member_fields (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `uniacid` int(11) NOT NULL,
  `name` varchar(20) NOT NULL DEFAULT '',
  `fieldid` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `available` tinyint(1) NOT NULL,
  `displayorder` smallint(6) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_uniacid` (`uniacid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
EOF;
}else{
    if(!pdo_fieldexists('mc_member_fields', 'name')){
        $setupSQL .= "ALTER TABLE $table_mc_member_fields ADD `name` VARCHAR(20) NOT NULL DEFAULT '' AFTER `uniacid`;";
    }
}

// mc_credits_record 表及字段
$table_credits_record = tablename('mc_credits_record');
$has_balance_after = true;
if (!pdo_tableexists('mc_credits_record')){
    $setupSQL .= <<<EOF
CREATE TABLE $table_credits_record (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` int(11) UNSIGNED NOT NULL,
  `uniacid` int(11) NOT NULL,
  `credittype` varchar(10) NOT NULL,
  `num` decimal(10,2) NOT NULL,
  `balance_after` decimal(10,2) UNSIGNED NULL DEFAULT NULL COMMENT '积分变动后的账户余额',
  `operator` int(11) UNSIGNED NOT NULL,
  `module` varchar(30) NOT NULL,
  `clerk_id` int(11) UNSIGNED NOT NULL,
  `store_id` int(11) UNSIGNED NOT NULL,
  `clerk_type` tinyint(1) NOT NULL,
  `createtime` int(11) UNSIGNED NOT NULL,
  `remark` varchar(200) NOT NULL,
  `real_uniacid` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `uid` (`uid`),
  KEY `uniacid` (`uniacid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
EOF;
}else{
    if(!pdo_fieldexists('mc_credits_record', 'balance_after')){
        $setupSQL .= "ALTER TABLE $table_credits_record ADD `balance_after` DECIMAL(10,2) UNSIGNED NULL DEFAULT NULL COMMENT '积分变动后的账户余额' AFTER `num`;";
        $has_balance_after = false;
    }
}

if (!empty($setupSQL)){
    pdo_query($setupSQL);
}

// 数据修复逻辑（balance_after 字段填充）
if (!$has_balance_after) {
    $unfilled_count = pdo_fetchcolumn("SELECT COUNT(*) FROM $table_credits_record WHERE balance_after IS NULL");
    if ($unfilled_count > 0) {
        $records = pdo_fetchall("SELECT * FROM $table_credits_record WHERE balance_after IS NULL ORDER BY uid, credittype, createtime ASC");
        $userBalances = array();
        foreach ($records as $record) {
            $key = $record['uid'] . '_' . $record['credittype'];
            if (!isset($userBalances[$key])) {
                $userBalances[$key] = 0;
            }
            $balance_after = $userBalances[$key] + $record['num'];
            pdo_update('mc_credits_record',
                array('balance_after' => $balance_after),
                array('id' => $record['id'])
            );
            $userBalances[$key] = $balance_after;
        }
    }
}

if (file_exists(MICRO_SERVER . 'ucenter/install.php')){
    @unlink(MICRO_SERVER . 'ucenter/install.php');
}
if (file_exists(MICRO_SERVER . 'ucenter/upgrade.php')){
    @unlink(MICRO_SERVER . 'ucenter/upgrade.php');
}

$finish = true;
