<?php
/**
 *    [超级活动(xj_event.{modulename})] (C)2012-2099 Powered by 逍遥工作室.
 *    Version: 1.0
 *    Date: 2012-9-15 10:27
 */

if (!defined('IN_DISCUZ')) {
    exit('Access Denied');
}
//判断是否是安米浏览器
if (strpos($_SERVER["HTTP_USER_AGENT"], 'Appbyme') > 0) {
    $Appbyme = true;
}
if (strpos($_SERVER["HTTP_USER_AGENT"], 'MAGAPP') > 0) {
    $magapp = true;
}
if (strpos($_SERVER['HTTP_USER_AGENT'], 'QianFan') > 0) {
    $QianFan = true;
}

if (!$_G['uid']) {
    showmessage('not_loggedin', null, array(), array('login' => 1));
}


//调用核心类
include 'source/plugin/xj_event/include/core.class.php';
$eventcore = new xj_eventcore();




include 'include/sms_func.php';
$tid     = intval($_GET['tid']);
$uid     = intval($_G['uid']);
$items   = DB::fetch(DB::query("SELECT A.*,B.authorid,B.subject FROM " . DB::table('xj_event') . " A LEFT JOIN " . DB::table('forum_thread') . " B ON A.tid = B.tid WHERE A.tid = '$tid'"));
$eid     = $items['eid'];
$setting = unserialize($items['setting']);
//报名返回链接
if (file_exists(DISCUZ_ROOT . './source/plugin/xj_event/module/wsqcenter/event_view.php')) {
    $retrunurl = $_G['siteurl'] . 'plugin.php?id=xj_event:wsqcenter&mod=event_view&tid=' . $tid;
} else {
    $retrunurl = $_G['siteurl'] . 'forum.php?mod=viewthread&tid=' . $tid;
}
if ($_GET['action'] == 'modifyfull') {
    if ($_GET['formhash'] != $_G['formhash']) {
        showmessage('submit_invalid');
    }
    $post = file_get_contents("php://input");
    $post = json_decode($post, true);
    $post = $post[0];
    if ($_G['charset'] == 'gbk') {
        foreach ($post as $key => $value) {
            $post[$key] = iconv('utf-8', 'gbk', $value);
        }
    }

    //验证手机号和身份证
    if (file_exists(DISCUZ_ROOT . './source/plugin/xj_event/module/checkapply/checkapply_single.php')) {
        @include 'module/checkapply/checkapply_single.php';
    }

    $applynumber = intval($post['applynumber']); //本次修改后报名人数
    //判断其它报名费用类型的人数是否比总人数多
    if ($setting['cost']) {
        if ($applynumber <= 0) {
            $result['full']    = 2;
            $result['message'] = lang('plugin/xj_event', 'qxzbmrs');
            $result['message'] = $_G['charset'] == 'gbk' ? iconv('gbk', 'utf-8', $result['message']) : $result['message'];
            echo json_encode($result);
            exit;
        }
        $costapplynumber = 0;
        foreach ($setting['cost'] as $value) {
            $costapplynumber = $costapplynumber + $post['cost' . $value['id']];
        }
        if ($costapplynumber != $applynumber) {
            $result['full']    = 2;
            $result['message'] = lang('plugin/xj_event', 'bmrszsbd');
            $result['message'] = $_G['charset'] == 'gbk' ? iconv('gbk', 'utf-8', $result['message']) : $result['message'];
            echo json_encode($result);
            exit;
        }
    }

    //获取已报名的人数
    $count = DB::result_first("SELECT sum(applynumber) FROM " . DB::table('xj_eventapply') . " WHERE tid='$tid' and uid=$uid");
    if ($count != $applynumber) {
        //如果修改的报名数比以前多
        if ($applynumber > $count) {
            //判断积分够不够
            $member = DB::fetch_first("SELECT extcredits1,extcredits2,extcredits3,extcredits4,extcredits5,extcredits6,extcredits7,extcredits8 FROM " . DB::table('common_member_count') . " WHERE uid = " . $_G['uid']);
            /*
            if($member['extcredits'.$items['use_extcredits']]<($items['use_extcredits_num']*($applynumber-$count))){
            $result['full'] = 2;
            $result['message'] = $_G['setting']['extcredits'][$items['use_extcredits']]['title'].lang('plugin/xj_event', 'bgwfcj');
            $result['message'] = $_G['charset'] == 'gbk'?iconv('gbk','utf-8',$result['message']):$result['message'];
            echo json_encode($result);
            exit;
            }
             */
            //验证报名名额是否够
            $applynum      = DB::result_first("SELECT SUM(applynumber) FROM " . DB::table('xj_eventapply') . " WHERE tid='$tid' and verify=1"); //已报名人数
            $applycountnum = DB::result_first("SELECT event_number FROM " . DB::table('xj_event') . " WHERE tid='$tid'"); //活动总人数
            if ($applycountnum > 0) {
                if (($applynumber - $count) > ($applycountnum - $applynum)) {
                    $result['full']    = 2;
                    $result['message'] = $_G['charset'] == 'gbk' ? iconv('gbk', 'utf-8', lang('plugin/xj_event', 'baomrsym')) : lang('plugin/xj_event', 'baomrsym');
                    echo json_encode($result);
                    exit;
                }
            }
        }
    }
    //删除以前的报名
    DB::query("DELETE FROM " . DB::table('xj_eventapply') . " WHERE tid = $tid and uid = $uid");
    //还原积分操作
    /*
    if($items['use_extcredits_num']>0){
    $extnum = $items['use_extcredits_num']*$count;
    updatemembercount($_G['uid'],array($items['use_extcredits']=>$extnum));
    }
     */

    //获取活动组织人的ID
    $event_uid = $items['authorid'];
    //活动标题
    $event_title = $items['subject'];
    //活动开始时间
    $event_starttime = dgmdate($items['starttime'], 'dt');
    //报名资料入数据库
    $ufielddata = array();
    foreach ($post as $key => $value) {
        if ($key != 'message' && $key != 'session') {
            $ufielddata[$key] = $value;
        }
    }
    //多种费用报名项
    if ($setting['cost']) {
        foreach ($setting['cost'] as $value) {
            $ufielddata['cost' . $value['id']] = intval($post['cost' . $value['id']]);
        }
    }
    //新的报名字段的报名资料入数据库
    if($setting['myuserfield']){
        $myuserfield = $eventcore->GetUserField($setting['myuserfield']);
    }
    foreach ($myuserfield as $value) {
        $ufielddata['myfield' . $value['id']] = $post['myfield' . $value['id']];
    }



    
    $ufielddata                = serialize($ufielddata);
    $eventapply                = array();
    $eventapply['tid']         = $tid;
    $eventapply['eid']         = $items['eid'];
    $eventapply['uid']         = $uid;
    $eventapply['realname']    = addslashes($post['realname']);
    $eventapply['qq']          = addslashes($post['qq']);
    $eventapply['mobile']      = addslashes($post['mobile']);
    $eventapply['bmmessage']   = addslashes($post['message']);
    $eventapply['dateline']    = $_G['timestamp'];
    $eventapply['applynumber'] = intval($post['applynumber']);
    $eventapply['ufielddata']  = $ufielddata;
    $eventapply['seccode']     = random(8, 1);
    $eventapply['session']     = intval($post['session']);
    $eventapply['first']       = 1;
    DB::insert('xj_eventapply', $eventapply);

    //用户活动相关的信息数据表是否存在，不存在就新建
    $num = DB::result_first("SELECT count(*) FROM " . DB::table('xj_event_member_info') . " WHERE uid = '$uid'");
    if ($num == 0) {
        DB::query("INSERT INTO " . DB::table('xj_event_member_info') . " (uid) VALUES ('$uid')");
    }
    //积分操作
    /*
    if($items['use_extcredits_num']>0){
    $extnum = $items['use_extcredits_num'] * $applynumber;
    updatemembercount($_G['uid'],array($items['use_extcredits']=>-$extnum));
    }
     */

    //发通知
    notification_add($event_uid, 'system', 'activity_notice', array('tid' => $tid, 'subject' => $event_title));
    $result['full']    = 1;
    $result['message'] = lang('plugin/xj_event', 'bmzlxgcg');
    $result['message'] = $_G['charset'] == 'gbk' ? iconv('gbk', 'utf-8', $result['message']) : $result['message'];
    echo json_encode($result);
    exit;

}
//用户报名资料
$apply               = DB::fetch_first("SELECT * FROM " . DB::table('xj_eventapply') . " WHERE tid=$tid AND uid=$uid ORDER BY first DESC");
$apply['ufielddata'] = unserialize($apply['ufielddata']);
//报名时可能选择的人数
$items['event_number_max'] = $items['event_number_max'] > 0 ? $items['event_number_max'] : 1;
$applynumber               = array();
for ($i = 1; $i <= $items['event_number_max']; $i++) {
    $applynumber[] = $i;
}

//获取用户报名字段
if ($_G['mobile']) {
    $userfield       = unserialize($items['userfield']);
    $selectuserfield = unserialize($items['userfield']);
    if ($selectuserfield) {
        if ($selectuserfield) {
            $htmls = $settings = array();
            require_once libfile('function/profile');
            foreach ($selectuserfield as $fieldid) {
                if (empty($ufielddata['userfield'])) {
                    $memberprofile = C::t('common_member_profile')->fetch($_G['uid']);
                    foreach ($selectuserfield as $val) {
                        if ($val == 'birthday') {
                            $ufielddata['userfield']['birthyear']  = $memberprofile['birthyear'];
                            $ufielddata['userfield']['birthmonth'] = $memberprofile['birthmonth'];
                        }
                        $ufielddata['userfield'][$val] = $memberprofile[$val];
                    }
                    unset($memberprofile);
                }
                $html = profile_setting($fieldid, $ufielddata['userfield'], false, true);

                if ($fieldid == 'birthday') {
                    $memberprofile = C::t('common_member_profile')->fetch($_G['uid']);
                    $mybirthday    = $memberprofile['birthyear'] . '-' . $memberprofile['birthmonth'] . '-' . $memberprofile['birthday'];
                    $mybirthday    = strtotime($mybirthday);
                    $mybirthday    = date("Y-m-d", $mybirthday);
                    $html          = '<input name="birthday" type="date" id="birthday" value="' . $mybirthday . '" class="join_text" />';
                }
                if ($fieldid == 'residecity') {
                    $html = '<div><input type="hidden" name="residecity" value=""><span></span> <button class="residecity ui-btn">' . lang('plugin/xj_event', 'select') . '</button><span></span></div>';
                }
                if ($html) {

                    if (strpos($html, '</option>') > 0) {
                        $html = str_replace('selected="selected"', '', $html);
                        $html = str_replace('value="' . $apply['ufielddata'][$fieldid] . '"', 'value="' . $apply['ufielddata'][$fieldid] . '" selected="selected"', $html);

                    }
                    if (strpos($html, 'checkbox') > 0) {
                        $html = '<fieldset data-role="controlgroup">' . $html . '</fieldset>';
                        $html = str_replace(' class="lb"', '', $html);
                        //echo $html;
                        //exit();
                    }
                    $html = preg_replace("/<div class=\"rq mtn\" id=\"showerror.+<\/div>/is", "", $html);
                    if (strpos($html, 'type="text"') > 0) {
                        $html = str_replace('class="px"', 'class="join_text"', $html);
                    }

                    if (strpos($html, '</textarea>') > 0) {
                        $html = str_replace('</textarea>', $apply['ufielddata'][$fieldid] . '</textarea>', $html);
                    }

                    $settings[$fieldid] = $_G['cache']['profilesetting'][$fieldid];
                    $htmls[$fieldid]    = $html;
                }
            }
        }
    } else {
        $selectuserfield = '';
    }
} else {
    $userfield       = unserialize($items['userfield']);
    $selectuserfield = unserialize($items['userfield']);
    if ($selectuserfield) {
        if ($selectuserfield) {
            $htmls = $settings = array();
            require_once libfile('function/profile');
            foreach ($selectuserfield as $fieldid) {
                if (empty($ufielddata['userfield'])) {
                    $memberprofile = C::t('common_member_profile')->fetch($_G['uid']);
                    foreach ($selectuserfield as $val) {
                        if ($val == 'birthday') {
                            $ufielddata['userfield']['birthyear']  = $memberprofile['birthyear'];
                            $ufielddata['userfield']['birthmonth'] = $memberprofile['birthmonth'];
                        }
                        $ufielddata['userfield'][$val] = $memberprofile[$val];
                    }
                    unset($memberprofile);
                }
                $html = profile_setting($fieldid, $ufielddata['userfield'], false, true);
                if ($fieldid == 'birthday') {
                    $memberprofile = C::t('common_member_profile')->fetch($_G['uid']);
                    $mybirthday    = $memberprofile['birthyear'] . '-' . $memberprofile['birthmonth'] . '-' . $memberprofile['birthday'];
                    $html          = '<div style="height:36px;"><input name="birthday" type="text" value="' . $mybirthday . '" class="dateselect" /><div></div></div>';
                }
                if ($fieldid == 'residecity') {
                    $html = '<div style="height:36px;"><input type="hidden" name="residecity" value=""><span></span> <button class="residecity">' . lang('plugin/xj_event', 'select') . '</button><span></span></div>';
                }
                if ($html) {
                    if (strpos($html, '</option>') > 0) {
                        $html = str_replace('selected="selected"', '', $html);
                        $html = str_replace('value="' . $apply['ufielddata'][$fieldid] . '"', 'value="' . $apply['ufielddata'][$fieldid] . '" selected="selected"', $html);

                    }

                    if (strpos($html, '</textarea>') > 0) {
                        $html = str_replace('</textarea>', $apply['ufielddata'][$fieldid] . '</textarea>', $html);
                    }

                    $settings[$fieldid] = $_G['cache']['profilesetting'][$fieldid];
                    $htmls[$fieldid]    = $html;
                }
            }
        }
    } else {
        $selectuserfield = '';
    }
}

//checkbox处理

if (!empty($selectuserfield)) {
    foreach ($selectuserfield as $fieldid) {
        if ($settings[$fieldid]['available']) {
            if ($settings[$fieldid]['formtype'] == 'checkbox') {
                $apply['ufielddata'][$fieldid] = $htmls[$fieldid];
                $tmp                           = explode(',', $value['ufielddata'][$fieldid]);
                foreach ($tmp as $cbvalue) {
                    $apply['ufielddata'][$fieldid] = str_replace($cbvalue . '"', $cbvalue . '" checked', $apply['ufielddata'][$fieldid]);
                }
            }
        }
    }
}

//过滤掉自动填入的数据
/*
foreach($htmls as $key=>$value){
$htmls[$key] =      preg_replace("/value=\"[^\"]+\"/", "value=\"\"", $value);
}
 */
$applyysq = intval(DB::result_first("SELECT sum(applynumber) FROM " . DB::table('xj_eventapply') . " WHERE tid='$tid'"));
$applyytg = intval(DB::result_first("SELECT sum(applynumber) FROM " . DB::table('xj_eventapply') . " WHERE tid='$tid' AND verify=1"));
$applysy  = $items['event_number'] - $applyytg;
if ($items['event_number'] == 0) {
    $applysy               = lang('plugin/xj_event', 'buxian');
    $items['event_number'] = lang('plugin/xj_event', 'buxian');
}

//新的报名字段
if($setting['myuserfield']){
    $myuserfield = $eventcore->GetUserField($setting['myuserfield'],$apply['ufielddata']);
}
include template('xj_event:event_join_modify_single');
