<?php
ob_start();
date_default_timezone_set('Asia/Shanghai');
session_cache_limiter('private');
header("Cache-Control: private");
header("Expires: ");
ini_set('session.cookie_httponly',1);
session_start();
//【新增】实时预览宾客姓名接口
if(isset($_POST['preview_guest_name'])){
    $name = trim($_POST['preview_guest_name'] ?? '');
    $_SESSION['preview_guest_name'] = $name;
    echo json_encode(['ok'=>true],JSON_UNESCAPED_UNICODE);
    exit;
}
//大屏远程翻页指令接口
if(isset($_POST['screen_page_cmd'])){
    $cmd = trim($_POST['screen_page_cmd'] ?? '');
    if(in_array($cmd,['prev','next'])){
        $_SESSION['screen_page_cmd'] = $cmd;
    }
    echo json_encode(['ok'=>true]);
    exit;
}
if(isset($_GET['m']) && $_GET['m'] === 'userdata'){
    require __DIR__.'/userdata.php';
    exit;
}
if(isset($_POST['ctrl_big_qrcode'])){
    $val = intval($_POST['ctrl_big_qrcode']);
    $_SESSION['big_screen_qrcode_visible'] = ($val ===1);
    echo json_encode(['ok'=>true]);
    exit;
}
if(isset($_POST['action']) && $_POST['action'] === 'voice_switch'){
    $_SESSION['voice_switch'] = ((int)$_POST['val']) === 1;
    echo json_encode(['ok'=>true]);
    exit;
}
if(!isset($_SESSION['voice_switch'])){
    $_SESSION['voice_switch'] = true;
}
if(isset($_POST['do_logout'])){
    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 4200,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    session_destroy();
    session_write_close();
    ob_clean();
    echo '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>';
    echo '<script>window.location.replace("gift_book_main.php");</script>';
    echo '</body></html>';
    exit;
}
if(isset($_GET['back_event'])){
    $_SESSION['curr_event_id'] = 0;
    session_write_close();
    header("Location: gift_book_main.php");
    exit;
}
$baseDataDir = __DIR__ . DIRECTORY_SEPARATOR . 'data';
$uploadQrDir = $baseDataDir . DIRECTORY_SEPARATOR . 'upload_qrcode';
$userFile = $baseDataDir . DIRECTORY_SEPARATOR . 'giftbook_users.json';
if(!is_dir($baseDataDir)){
    mkdir($baseDataDir,0755,true);
}
if(!is_dir($uploadQrDir)){
    mkdir($uploadQrDir,0755,true);
}
if(!file_exists($userFile)){
    file_put_contents($userFile,json_encode([],JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
}
function safeReadJson(string $filePath):array
{
    if(!file_exists($filePath)) return [];
    $fp = fopen($filePath,'r');
    flock($fp,LOCK_SH);
    $raw = fread($fp,filesize($filePath));
    flock($fp,LOCK_UN);
    fclose($fp);
    $data = json_decode($raw,true);
    return is_array($data) ? $data : [];
}
function safeWriteJson(string $filePath, array $data):bool
{
    $fp = fopen($filePath,'c+');
    if(!$fp) return false;
    flock($fp,LOCK_EX);
    ftruncate($fp,0);
    $json = json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
    fwrite($fp,$json);
    fflush($fp);
    flock($fp,LOCK_UN);
    fclose($fp);
    return true;
}
$userList = safeReadJson($userFile);
$userId = $_SESSION['giftbook_uid'] ?? 0;
$isLogin = $userId > 0;
$currEventId = $_SESSION['curr_event_id'] ?? 0;
$msg = '';
if(isset($_SESSION['flash_msg'])){
    $msg = $_SESSION['flash_msg'];
    unset($_SESSION['flash_msg']);
}
if(isset($_GET['saved']) && intval($_GET['saved']) === 1){
    $msg = "✅管账人员/事务信息修改完成，已生效！";
}
$oldInput = [
    'name' => '',
    'money' => '',
    'pay_way' => '现金',
    'gift' => '',
    'remark' => ''
];
$showAlertRemain = -1;
if(isset($_GET['saved_remain'])){
    $showAlertRemain = intval($_GET['saved_remain']);
}
$userDir = '';
$myEvents = [];
if($isLogin){
    $userDir = $baseDataDir . DIRECTORY_SEPARATOR . 'user_' . $userId;
    if(!is_dir($userDir)){
        mkdir($userDir,0755,true);
    }
    $files = glob($userDir . DIRECTORY_SEPARATOR . 'event_*.json');
    if($files){
        foreach($files as $f){
            $basename = basename($f);
            preg_match('/event_(\d+)\.json/',$basename,$m);
            if(!$m) continue;
            $eid = intval($m[1]);
            $data = safeReadJson($f);
            $myEvents[] = [
                'event_id'=>$eid,
                'event_name'=>$data['event_name'],
                'event_type'=>$data['event_type'],
                'create_at'=>$data['create_at'],
                'account_person'=>$data['account_person'] ?? '',
                'qrcode_img'=>$data['qrcode_img'] ?? '',
                'is_closed'=>intval($data['is_closed']??0)
            ];
        }
    }
    $urlSelectEvent = filter_input(INPUT_GET,'select_event',FILTER_VALIDATE_INT,['options'=>['min_range'=>1]]);
    if($urlSelectEvent !== false){
        $found = false;
        foreach($myEvents as $ev){
            if($ev['event_id'] === $urlSelectEvent){
                $found = true;
                break;
            }
        }
        if($found){
            $_SESSION['curr_event_id'] = $urlSelectEvent;
            $currEventId = $urlSelectEvent;
        }else{
            $_SESSION['curr_event_id'] = 0;
            $currEventId = 0;
        }
    }
}
function moneyToChinese($num)
{
    $cnNum = ["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"];
    $unit = ["","拾","佰","仟","万","拾","佰","仟","亿"];
    $intVal = intval($num);
    if ($intVal <= 0) {
        return "零元整";
    }
    $str = (string)$intVal;
    $len = strlen($str);
    $out = '';
    $lastZero = false;
    for ($i = 0; $i < $len; $i++) {
        $digit = intval($str[$i]);
        $pos = $len - 1 - $i;
        if ($digit !== 0) {
            if ($lastZero) {
                $out .= $cnNum[0];
            }
            $out .= $cnNum[$digit] . $unit[$pos];
            $lastZero = false;
        } else {
            $lastZero = true;
        }
    }
    $out = rtrim($out, "零");
    $out .= "元整";
    return $out;
}
if(isset($_POST['register'])){
    $username = trim($_POST['reg_user']);
    $pwd = trim($_POST['reg_pwd']);
    $realname = trim($_POST['reg_realname']);
    $phone = trim($_POST['reg_phone']);
    if(empty($username)||empty($pwd)||empty($realname)||empty($phone)){
        $_SESSION['flash_msg'] = "账号、密码、注册人姓名、手机号全部不能为空";
        header("Location: gift_book_main.php");
        exit;
    }
    $exist = false;
    foreach($userList as $u){
        if(trim($u['username']) === $username){
            $exist = true;
            break;
        }
    }
    if($exist){
        $_SESSION['flash_msg'] = "⚠️ 该账号【".$username."】已经存在，请更换账号名后重试";
        header("Location: gift_book_main.php");
        exit;
    }else{
        $newUid = 0;
        foreach($userList as $u) $newUid = max($newUid,$u['user_id']);
        $newUid = $newUid + 1;
        $userList[] = [
            "user_id"=>$newUid,
            "username"=>$username,
            "password"=>password_hash($pwd,PASSWORD_DEFAULT),
            "realname"=>$realname,
            "phone"=>$phone,
            "create_at"=>date('Y-m-d H:i:s')
        ];
        safeWriteJson($userFile,$userList);
        $_SESSION['flash_msg'] = "✅ 注册成功，请使用账号【".$username."】登录";
        header("Location: gift_book_main.php");
        exit;
    }
}
if(isset($_POST['login'])){
    $un = trim($_POST['user']);
    $pw = trim($_POST['pwd']);
    $loginOk = false;
    foreach($userList as &$u){
        if($u['username'] === $un){
            if(md5($pw) === $u['password']){
                $u['password'] = password_hash($pw,PASSWORD_DEFAULT);
                safeWriteJson($userFile,$userList);
                $_SESSION['giftbook_uid'] = $u['user_id'];
                $_SESSION['curr_event_id'] = 0;
                $userId = $u['user_id'];
                $isLogin = true;
                $loginOk = true;
                break;
            }elseif(password_verify($pw,$u['password'])){
                $_SESSION['giftbook_uid'] = $u['user_id'];
                $_SESSION['curr_event_id'] = 0;
                $userId = $u['user_id'];
                $isLogin = true;
                $loginOk = true;
                break;
            }
        }
    }
    unset($u);
    if(!$loginOk){
        $_SESSION['flash_msg'] = "❌ 账号或密码错误，请重新输入";
    }
    header("Location: gift_book_main.php");
    exit;
}
if($isLogin && isset($_POST['saveEvent'])){
    $eventName = trim($_POST['event_name']);
    $eventType = trim($_POST['event_type']);
    $accountPerson = trim($_POST['account_person'] ?? '');
    $qrcodeSavePath = '';
    if(isset($_FILES['qrcode_img']) && $_FILES['qrcode_img']['error'] === 0){
        $ext = pathinfo($_FILES['qrcode_img']['name'],PATHINFO_EXTENSION);
        $newName = date("YmdHis")."_".mt_rand(1000,9999).".".strtolower($ext);
        $destFile = $uploadQrDir . DIRECTORY_SEPARATOR . $newName;
        move_uploaded_file($_FILES['qrcode_img']['tmp_name'],$destFile);
        $qrcodeSavePath = "data/upload_qrcode/".$newName;
    }
    if(empty($eventName)){
        $msg = "事务名称不能为空";
    }else{
        $maxEid = 0;
        foreach($myEvents as $ev){
            if($ev['event_id'] > $maxEid) $maxEid = $ev['event_id'];
        }
        $newEid = $maxEid + 1;
        $eventFile = $userDir . DIRECTORY_SEPARATOR . 'event_'.$newEid.'.json';
        $initData = [
            "event_id"=>$newEid,
            "event_name"=>$eventName,
            "event_type"=>$eventType,
            "account_person" => $accountPerson,
            "qrcode_img"=>$qrcodeSavePath,
            "is_closed"=>0,
            "create_at"=>date('Y-m-d H:i:s'),
            "next_record_id"=>1,
            "records"=>[]
        ];
        safeWriteJson($eventFile,$initData);
    }
    header("Location: gift_book_main.php");
    exit;
}
$editEventId = 0;
$editEventData = null;
if($isLogin && isset($_GET['edit_event'])){
    $editEventId = intval($_GET['edit_event']);
    $tmpFile = $userDir . DIRECTORY_SEPARATOR . 'event_'.$editEventId.'.json';
    if(file_exists($tmpFile)){
        $editEventData = safeReadJson($tmpFile);
    }
}
if($isLogin && isset($_POST['saveEventEdit'])){
    $editEventId = intval($_POST['edit_event_id'] ?? 0);
    $newAccPerson = trim($_POST['account_person'] ?? '');
    $newEventName = trim($_POST['event_name'] ?? '');
    if($editEventId > 0){
        $tmpFile = $userDir . DIRECTORY_SEPARATOR . 'event_'.$editEventId.'.json';
        if(file_exists($tmpFile)){
            $editData = safeReadJson($tmpFile);
            if($newEventName !== ''){
                $editData['event_name'] = $newEventName;
            }
            $editData['account_person'] = $newAccPerson;
            if(isset($_FILES['qrcode_img']) && $_FILES['qrcode_img']['error'] === 0){
                $ext = pathinfo($_FILES['qrcode_img']['name'],PATHINFO_EXTENSION);
                $newName = date("YmdHis")."_".mt_rand(1000,9999).".".strtolower($ext);
                $destFile = $uploadQrDir . DIRECTORY_SEPARATOR . $newName;
                move_uploaded_file($_FILES['qrcode_img']['tmp_name'],$destFile);
                $editData['qrcode_img'] = "data/upload_qrcode/".$newName;
            }
            safeWriteJson($tmpFile,$editData);
        }
    }
    header("Location: gift_book_main.php?saved=1");
    exit;
}
if($isLogin && isset($_GET['del_event'])){
    $deid = intval($_GET['del_event']);
    $fpath = $userDir . DIRECTORY_SEPARATOR . 'event_'.$deid.'.json';
    if(file_exists($fpath)) unlink($fpath);
    if($currEventId == $deid){
        $_SESSION['curr_event_id'] = 0;
        $currEventId = 0;
    }
    header("Location: gift_book_main.php");
    exit;
}
if($isLogin && $currEventId>0 && isset($_POST['submit_password'])){
    $inputPwd = trim($_POST['submit_password'] ?? '');
    $currentUserInfo = null;
    foreach($userList as $u){
        if(intval($u['user_id']) === $userId){
            $currentUserInfo = $u;
            break;
        }
    }
    $pwdOk = false;
    if($currentUserInfo){
        if(md5($inputPwd) === $currentUserInfo['password']){
            $pwdOk = true;
        }elseif(password_verify($inputPwd,$currentUserInfo['password'])){
            $pwdOk = true;
        }
    }
    if(!$pwdOk){
        $msg = "❌密码输入错误，移交礼簿操作取消！";
        header("Location: gift_book_main.php?select_event=".$currEventId);
        exit;
    }
    $tmpFile = $userDir . DIRECTORY_SEPARATOR . 'event_'.$currEventId.'.json';
    if(file_exists($tmpFile)){
        $editData = safeReadJson($tmpFile);
        $editData['is_closed'] = 1;
        safeWriteJson($tmpFile,$editData);
    }
    header("Location: gift_book_main.php?select_event=".$currEventId);
    exit;
}
$currEvent = null;
$eventJsonPath = '';
$eventData = null;
$myRecords = [];
$allEditLogs = [];
$currAccountPerson = '';
$currQrcodeImg = '';
$currIsClosed = 0;
if($isLogin && $currEventId > 0){
    $eventJsonPath = $userDir . DIRECTORY_SEPARATOR . 'event_'.$currEventId.'.json';
    if(file_exists($eventJsonPath)){
        $eventData = safeReadJson($eventJsonPath);
        $currEvent = [
            'event_id'=>$eventData['event_id'],
            'event_name'=>$eventData['event_name'],
            'event_type'=>$eventData['event_type'],
            'create_at'=>$eventData['create_at']
        ];
        $currAccountPerson = $eventData['account_person'] ?? '';
        $currQrcodeImg = $eventData['qrcode_img'] ?? '';
        $currIsClosed = intval($eventData['is_closed']??0);
        $myRecords = $eventData['records'] ?? [];
        foreach($myRecords as $r){
            if(!empty($r['edit_log'])){
                foreach($r['edit_log'] as $logItem){
                    $logItem['record_id'] = $r['id'];
                    $logItem['record_name'] = $r['name'];
                    $allEditLogs[] = $logItem;
                }
            }
        }
        usort($allEditLogs,function($a,$b){
            return strtotime($b['edit_time']) - strtotime($a['edit_time']);
        });
    }else{
        $_SESSION['curr_event_id'] = 0;
        $currEventId = 0;
    }
}
$isFormSubmit = false;
if($isLogin && $currEventId > 0 && $eventData && isset($_POST['saveItem'])){
    $isFormSubmit = true;
    if( ($eventData['is_closed']??0) ===1 ){
        $msg = "礼簿已移交锁定，禁止新增/修改记录！";
        header("Location: gift_book_main.php?select_event=".$currEventId);
        exit;
    }
    $id = intval($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $moneyRaw = trim($_POST['money'] ?? '');
    $money = floatval($moneyRaw);
    if($money <= 0){
        $msg = "错误：礼金金额不允许为0或负数！";
    }else{
        $money = round($money,2);
    }
    $pay_way = trim($_POST['pay_way'] ?? '现金');
    $gift = trim($_POST['gift'] ?? '');
    $remark = trim($_POST['remark'] ?? '');
    $ctime = date("Y-m-d H:i:s");
    $oldInput['name'] = $name;
    $oldInput['money'] = $money;
    $oldInput['pay_way'] = $pay_way;
    $oldInput['gift'] = $gift;
    $oldInput['remark'] = $remark;
    if(empty($name)){
        $msg = "宾客姓名不能为空";
    }elseif($money <= 0){
    }else{
        $sameNameList = [];
        foreach($myRecords as $rowItem){
            if($rowItem['name'] === $name && intval($rowItem['id']) !== $id){
                $sameNameList[] = $rowItem;
            }
        }
        if(count($sameNameList) > 0 && empty($remark)){
            $msg = "⚠️出现同名宾客【".$name."】，必需添加备注信息，以区分同名人";
        }else{
            if($id > 0){
                $currEditRecord = null;
                foreach($eventData['records'] as &$row){
                    if($row['id'] === $id){$currEditRecord = $row;break;}
                }
                unset($row);
                if($currEditRecord === null){
                    $msg = "记录不存在";
                }elseif($currEditRecord['edit_count'] >= 3){
                    $msg = "❌该记录已经达到最大修改次数(3次)，禁止修改！";
                }else{
                    $oldData = ["name"=>$currEditRecord['name'],"money"=>$currEditRecord['money'],"pay_way"=>$currEditRecord['pay_way'],"gift"=>$currEditRecord['gift'],"remark"=>$currEditRecord['remark']];
                    $logItem = ["edit_time"=>$ctime,"operate_type"=>"edit","old"=>$oldData,"new"=>["name"=>$name,"money"=>$money,"pay_way"=>$pay_way,"gift"=>$gift,"remark"=>$remark]];
                    foreach($eventData['records'] as &$row){
                        if($row['id'] === $id){
                            $row['name'] = $name;
                            $row['money'] = $money;
                            $row['pay_way'] = $pay_way;
                            $row['gift'] = $gift;
                            $row['remark'] = $remark;
                            $row['update_time'] = $ctime;
                            $row['edit_count']++;
                            $row['edit_log'][] = $logItem;
                        }
                    }
                    unset($row);
                    safeWriteJson($eventJsonPath,$eventData);
                    //编辑保存清空预览
                    $_SESSION['preview_guest_name'] = '';
                    $remain = 3 - $currEditRecord['edit_count'] - 1;
                    $qsArr = ['select_event'=>$currEventId,'saved_remain'=>$remain];
                    $qs = http_build_query($qsArr);
                    header("Location: gift_book_main.php?".$qs);
                    exit;
                }
            }else{
                $newRecId = $eventData['next_record_id'];
                $addLog = [
                    "edit_time"=>$ctime,
                    "operate_type"=>"add",
                    "old"=>[],
                    "new"=>["name"=>$name,"money"=>$money,"pay_way"=>$pay_way,"gift"=>$gift,"remark"=>$remark]
                ];
                $newRecord = [
                    "id"=>$newRecId,"name"=>$name,"money"=>$money,"pay_way"=>$pay_way,
                    "gift"=>$gift,"remark"=>$remark,"create_time"=>$ctime,"update_time"=>$ctime,
                    "edit_count"=>0,"edit_log"=>[$addLog]
                ];
                $eventData['records'][] = $newRecord;
                $eventData['next_record_id'] = $newRecId + 1;
                safeWriteJson($eventJsonPath,$eventData);
                //新增保存清空预览
                $_SESSION['preview_guest_name'] = '';
                $_SESSION['temp_speech'] = $name."，礼金".$money."元";
                $qsArr = ['select_event'=>$currEventId];
                $qs = http_build_query($qsArr);
                header("Location: gift_book_main.php?".$qs);
                exit;
            }
        }
    }
}
$tempSpeech = '';
if(isset($_SESSION['temp_speech'])){
    $tempSpeech = $_SESSION['temp_speech'];
    unset($_SESSION['temp_speech']);
    session_write_close();
    session_start();
}
$kw = trim($_GET['kw'] ?? '');
$filterType = trim($_GET['filter_type'] ?? '');
$idQuery = trim($_GET['id_query'] ?? '');
$showList = $myRecords;
if($kw !== ''){
    $tmp = [];
    foreach($showList as $i){
        if(stripos($i['name'],$kw) !== false) $tmp[] = $i;
    }
    $showList = $tmp;
}
if ($idQuery !== '') {
    $tmp = [];
    $idSet = [];
    if (strpos($idQuery, '-') !== false) {
        [$startStr,$endStr] = explode('-',$idQuery,2);
        $start = intval(trim($startStr));
        $end = intval(trim($endStr));
        if($start > 0 && $end >= $start){
            for($i=$start;$i<=$end;$i++){
                $idSet[] = $i;
            }
        }
    }elseif(strpos($idQuery,',')!==false){
        $parts = explode(',',$idQuery);
        foreach($parts as $p){
            $n = intval(trim($p));
            if($n>0) $idSet[] = $n;
        }
    }else{
        $n = intval($idQuery);
        if($n>0) $idSet[] = $n;
    }
    $idSet = array_unique($idSet);
    foreach($showList as $row){
        if(in_array(intval($row['id']),$idSet)){
            $tmp[] = $row;
        }
    }
    $showList = $tmp;
}
if($filterType !== ''){
    $tmp = [];
    foreach($showList as $i){
        $giftVal = $i['gift'] ?? '';
        $remarkVal = $i['remark'] ?? '';
        $payVal = $i['pay_way'] ?? '';
        switch ($filterType){
            case '现金':
            case '微信':
            case '支付宝':
            case '其它':
                if($payVal === $filterType){
                    $tmp[] = $i;
                }
                break;
            case 'gift':
                if($giftVal !== ''){
                    $tmp[] = $i;
                }
                break;
            case 'remark':
                if($remarkVal !== ''){
                    $tmp[] = $i;
                }
                break;
            default:
                $tmp[] = $i;
                break;
        }
    }
    $showList = $tmp;
}
usort($showList,function($a,$b){
    return strtotime($b['create_time']) - strtotime($a['create_time']);
});
$totalCnt = count($showList);
$totalSum = 0;
$sumCash = 0;
$sumWechat = 0;
$sumAlipay = 0;
$sumOther = 0;
foreach($showList as $s){
    $totalSum += $s['money'];
    if($s['pay_way'] === '现金') $sumCash += $s['money'];
    if($s['pay_way'] === '微信') $sumWechat += $s['money'];
    if($s['pay_way'] === '支付宝') $sumAlipay += $s['money'];
    if($s['pay_way'] === '其它') $sumOther += $s['money'];
}
$editRow = null;
if($isLogin && $currEventId > 0 && isset($_GET['edit'])){
    $eid = intval($_GET['edit']);
    foreach($myRecords as $m){
        if($m['id'] === $eid) $editRow = $m;
    }
}
if($editRow !== null && !$isFormSubmit){
    $oldInput['name'] = $editRow['name'];
    $oldInput['money'] = $editRow['money'];
    $oldInput['pay_way'] = $editRow['pay_way'];
    $oldInput['gift'] = $editRow['gift'];
    $oldInput['remark'] = $editRow['remark'];
}
$hasSameName = false;
if(!empty($myRecords)){
    $curName = $oldInput['name'] ?? '';
    if($curName !== ''){
        foreach($myRecords as $r){
            if($r['name'] === $curName && (!$editRow || intval($r['id']) !== intval($editRow['id']))){
                $hasSameName = true;
                break;
            }
        }
    }
}
$jsonAllLogs = json_encode($allEditLogs,JSON_UNESCAPED_UNICODE);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>电子礼簿系统</title>
<style>
/* 大屏二维码切换按钮自定义样式 */
.btn-qrcode-off{
    background:#ffd09a;
    color:#444;
    border:1px solid #ffd09a;
}
.btn-qrcode-on{
    background:#c8102e;
    color:#ffffff;
    border:1px solid #a00;
}
:root{
--primary:#4f46e5;
--primary2:#6366f1;
--success:#16a34a;
--warning:#f59e0b;
--danger:#dc2626;
--info:#0891b2;
--gray-50:#f9fafb;
--gray-100:#f3f4f6;
--gray-200:#e5e7eb;
--gray-300:#d1d5db;
--gray-600:#4b5563;
--gray-800:#1f2937;
--shadow-sm:0 1px 2px rgba(0,0,0,0.05);
--shadow:0 4px 14px rgba(0,0,0,0.08);
--shadow-lg:0 10px 30px rgba(79,70,229,0.14);
--radius-md:14px;
--radius-lg:20px;
}
*,::after,::before{box-sizing:border-box}
body{
margin:0;
font-family:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
font-size:1rem;
line-height:1.55;
color:var(--gray-800);
background-color:var(--gray-100);
-webkit-text-size-adjust:100%;
}
.container-fluid{
width:100%;
padding-right:1.2rem;
padding-left:1.2rem;
margin-right:auto;
margin-left:auto;
}
.d-flex{display:flex!important;}
.justify-content-center{justify-content:center!important;}
.justify-content-between{justify-content:space-between!important;}
.align-items-center{align-items:center!important;}
.align-items-end{align-items:flex-end!important;}
.gap-2{gap:0.6rem!important;}
.gap-3{gap:1rem!important;}
.flex-wrap{flex-wrap:wrap!important;}
.flex-grow-1{flex-grow:1!important;}
.w-100{width:100%!important;}
.min-vh-100{min-height:100vh!important;}
.py-3{padding-top:1rem!important;padding-bottom:1rem!important;}
.py-4{padding-top:1.6rem!important;padding-bottom:1.6rem!important;}
.px-3{padding-left:1rem!important;padding-right:1rem!important;}
.mt-4{margin-top:1.6rem!important;}
.mb-0{margin-bottom:0!important;}
.mb-3{margin-bottom:1rem!important;}
.mb-4{margin-bottom:1.6rem!important;}
.ms-2{margin-left:0.6rem!important;}
.me-2{margin-right:0.6rem!important;}
.text-center{text-align:center!important;}
.text-end{text-align:right!important;}
.text-muted{color:var(--gray-600)!important;}
.text-danger{color:var(--danger)!important;}
.fw-semibold{font-weight:600!important;}
.fw-bold{font-weight:700!important;}
.h3{font-size:1.6rem;}
.h4{font-size:1.4rem;}
.h5{font-size:1.2rem;}
.card{
background-color:#fff;
border-radius:var(--radius-lg);
box-shadow:var(--shadow);
margin-bottom:1.4rem;
overflow:hidden;
border:none;
transition:box-shadow 0.22s ease;
}
.card:hover{
box-shadow:var(--shadow-lg);
}
.card-header{
padding:1.1rem 1.3rem;
background-color:#fff;
border-bottom:1px solid var(--gray-200);
}
.card-body{padding:1.2rem 1.3rem;}
.form-label{
margin-bottom:0.4rem;
font-size:0.86rem;
color:var(--gray-600);
font-weight:500;
}
.form-control,.form-select{
display:block;
padding:0.7rem 1rem;
font-size:0.96rem;
border:1px solid var(--gray-300);
border-radius:var(--radius-md);
background:#fff;
transition:all 0.2s ease;
}
.form-control:hover,.form-select:hover{
border-color:#a5b4fc;
}
.form-control:focus,.form-select:focus{
outline:none;
border-color:var(--primary);
box-shadow:0 0 0 3px rgba(79,90,229,0.16);
}
.btn{
padding:0.6rem 1.1rem;
border-radius:var(--radius-md);
border:none;
font-size:0.96rem;
cursor:pointer;
transition:all 0.2s ease;
}
.btn:hover{
transform:translateY(-2px);
box-shadow:var(--shadow);
}
.btn:active{
transform:translateY(0px);
}
.btn-sm{
padding:0.4rem 0.8rem;
font-size:0.86rem;
}
.btn-primary{background-color:var(--primary);color:#fff;}
.btn-secondary{background-color:var(--gray-600);color:#fff;}
.btn-success{background-color:var(--success);color:#fff;}
.btn-warning{background-color:var(--warning);color:#111;}
.btn-danger{background-color:var(--danger);color:#fff;}
.btn-info{background-color:var(--info);color:#fff;}
.btn-outline-secondary{background:transparent;color:var(--gray-600);border:1px solid var(--gray-300);}
.badge{
display:inline-block;
padding:0.32em 0.65em;
font-size:0.74rem;
font-weight:600;
border-radius:8px;
}
.alert{
padding:0.9rem 1.1rem;
border-radius:var(--radius-md);
margin-bottom:1rem;
border:none;
}
.alert-info{background-color:#e0f2fe;color:#0369a1;}
.alert-warning{background-color:#fffbeb;color:#92400e;}
.table{width:100%;margin-bottom:0;color:var(--gray-800);border-collapse:collapse;}
.table th,.table td{
padding:0.7rem 0.8rem;
border-bottom:1px solid var(--gray-200);
}
.table>thead th{
background-color:var(--gray-50);
font-weight:600;
text-align:left;
}
.table-striped>tbody tr:nth-child(odd){background-color:#f9fafb;}
.table-hover>tbody tr:hover{background-color:#eef2ff;}
.table-responsive{overflow-x:auto;}
.modal{
position:fixed;top:0;left:0;
width:100%;height:100%;
background:rgba(15,23,42,0.65);
overflow-y:auto;
display:none;
z-index:1050;
padding:1rem 0;
}
.modal-dialog{
margin:0 auto;
max-width:520px;
width:94%;
}
.modal-xl{max-width:96%;max-height:92vh;}
.modal-content{
background:#fff;
border-radius:var(--radius-lg);
box-shadow:var(--shadow-lg);
overflow:hidden;
}
.modal-header{
padding:1.1rem 1.3rem;
border-bottom:1px solid var(--gray-200);
display:flex;
justify-content:space-between;
align-items:center;
}
.modal-body{padding:1.2rem 1.3rem;}
.modal-footer{
padding:1rem 1.3rem;
border-top:1px solid var(--gray-200);
display:flex;gap:0.6rem;justify-content:flex-end;
}
.btn-close{
background:none;border:none;font-size:1.5rem;cursor:pointer;color:#666;
padding:0 6px;
}
.stat-card{
border-radius:var(--radius-md);
color:#fff;
padding:14px 10px;
text-align:center;
flex:1;
min-width:135px;
text-shadow:0 1px 3px rgba(0,0,0,0.15);
}
.stat-card .label-text{font-size:13px;opacity:0.92;}
.stat-card .num-text{font-size:21px;font-weight:bold;margin-top:5px;}
.img-fluid{max-width:100%;height:auto;}
.text-nowrap{white-space:nowrap;}
.login-wrap{
    min-height:100vh;
    display:flex;
    align-items:center;
    justify-content:center;
    background:
        radial-gradient(circle at 20% 20%, rgba(99,102,241,0.25), transparent 40%),
        radial-gradient(circle at 80% 30%, rgba(139,92,246,0.22), transparent 45%),
        linear-gradient(135deg,#eef2ff 0%,#f5f3ff 45%,#fdf4ff 100%);
    padding:24px;
    position:relative;
    overflow:hidden;
}
.login-wrap::before,
.login-wrap::after{
    content:"";
    position:absolute;
    border-radius:50%;
    filter:blur(60px);
    opacity:0.55;
    z-index:0;
}
.login-wrap::before{
    width:280px;height:280px;
    background:#c7d2fe;
    top:-80px;left:-60px;
}
.login-wrap::after{
    width:340px;height:340px;
    background:#e9d5ff;
    bottom:-120px;right:-80px;
}
.login-card{
    width:100%;
    max-width:480px;
    background:#ffffff;
    padding:48px 42px 36px;
    border-radius:24px;
    box-shadow:0 20px 50px rgba(79,70,229,0.18);
    position:relative;
    z-index:1;
    border:1px solid rgba(255,255,255,0.6);
}
.login-logo-bar{
    width:56px;height:56px;
    border-radius:18px;
    background:linear-gradient(135deg,#6366f1,#8b5cf6);
    display:flex;
    align-items:center;
    justify-content:center;
    margin:0 auto 18px;
    box-shadow:0 10px 24px rgba(99,102,241,0.35);
}
.login-logo-bar span{
    font-size:28px;
}
.login-card-title{
    text-align:center;
    font-size:26px;
    font-weight:700;
    color:#111827;
    margin-bottom:6px;
}
.login-card-subtitle{
    text-align:center;
    font-size:14px;
    color:#6b7280;
    margin-bottom:30px;
}
.login-card .form-control{
    height:54px;
    font-size:16px;
    border-radius:14px;
    padding:0 20px;
    border:1px solid #e5e7eb;
    background:#fafbff;
}
.login-card .form-control:focus{
    border-color:#6366f1;
    background:#fff;
    box-shadow:0 0 0 4px rgba(99,102,241,0.14);
    outline:none;
}
.login-card .btn{
    height:54px;
    font-size:17px;
    border-radius:14px;
    font-weight:600;
}
.login-card .btn-primary{
    background:linear-gradient(135deg,#4f46e5,#6366f1);
    box-shadow:0 10px 24px rgba(79,70,229,0.35);
}
.login-card .btn-primary:hover{
    background:linear-gradient(135deg,#4338ca,#4f46e5);
}
.login-card .btn-outline-secondary{
    background:#fff;
    border:1px solid #e5e7eb;
    color:#374151;
}
.login-card .btn-outline-secondary:hover{
    background:#f9fafb;
    border-color:#c7d2fe;
}
.login-tip{
    margin-top:18px;
    text-align:center;
    font-size:13px;
    color:#9ca3af;
}
@media (max-width:768px){
.btn{font-size:0.86rem;padding:0.5rem 0.8rem;}
.btn:hover{transform:none;}
.h3{font-size:1.3rem;}
.h4{font-size:1.15rem;}
.h5{font-size:1.05rem;}
.stat-card{min-width:115px;}
.login-card{padding:36px 22px 28px;}
.login-card-title{font-size:23px;}
.login-card .form-control{
    height:48px;
    font-size:15px;
    padding:0 16px;
}
.login-card .btn{
    height:48px;
    font-size:16px;
}
}
.login-copyright{
    margin-top:22px;
    width:100%;
    display:block;
    text-align:center;
    font-size:13px;
    color:#8892a0;
}
</style>
</head>
<body>
<?php if(!$isLogin): ?>
<div class="login-wrap">
    <div class="login-card">
        <div class="login-logo-bar">
            <span>📒</span>
        </div>
        <h4 class="login-card-title">老六队电子礼簿系统</h4>
        <div class="login-card-subtitle">多用户 · 多事务 · 礼金记录管理</div>
        <?php if($msg):?><div class="alert alert-info"><?=htmlspecialchars($msg)?></div><?php endif; ?>
        <form method="post">
            <div class="mb-3">
                <label class="form-label">账号</label>
                <input type="text" name="user" class="form-control" placeholder="请输入登录账号" required>
            </div>
            <div class="mb-3">
                <label class="form-label">密码</label>
                <input type="password" name="pwd" class="form-control" placeholder="请输入登录密码" required>
            </div>
            <div class="d-flex gap-2 flex-wrap mt-4">
                <button type="submit" name="login" class="btn btn-primary flex-grow-1 w-100">登录系统</button>
                <button type="button" id="openRegBtn" class="btn btn-outline-secondary flex-grow-1 w-100">新用户注册</button>
                       </div>
            </form>
            <div class="login-tip">请使用已注册账号进入系统管理</div>
<div class="login-copyright">
    &copy; <?php echo date("Y");?>  版权所有 喻永志 1898356009
</div>
    </div>
</div>
<div class="modal" id="regModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post">
      <div class="modal-header">
        <h5 class="modal-title">新用户注册</h5>
        <button type="button" class="btn-close" onclick="closeModal('regModal')">×</button>
      </div>
      <div class="modal-body">
          <div class="mb-3">
              <label class="form-label">登录账号 <span class="text-danger">*</span></label>
              <input type="text" name="reg_user" class="form-control" required>
          </div>
          <div class="mb-3">
              <label class="form-label">登录密码 <span class="text-danger">*</span></label>
              <input type="password" name="reg_pwd" class="form-control" required>
          </div>
          <div class="mb-3">
              <label class="form-label">注册人姓名 <span class="text-danger">*</span></label>
              <input type="text" name="reg_realname" class="form-control" required>
          </div>
          <div class="mb-3">
              <label class="form-label">手机号码 <span class="text-danger">*</span></label>
              <input type="tel" name="reg_phone" class="form-control" required>
          </div>
      </div>
      <div class="modal-footer flex-wrap">
        <button type="button" class="btn btn-secondary" onclick="closeModal('regModal')">取消</button>
        <button type="submit" name="register" class="btn btn-success">确认注册</button>
      </div>
      </form>
    </div>
  </div>
</div>
<?php else: ?>
<div class="container-fluid mt-4">
<?php if($currEventId <= 0): ?>
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <h3 class="fw-semibold">礼簿事务管理</h3>
        <div>
            <button id="btnVoiceSwitch" class="btn btn-sm btn-outline-secondary"></button>
            <a href="change_password.php" class="btn btn-sm btn-warning" style="text-decoration:none;">🔐修改登录密码</a>
<form method="post" style="display:inline-block;margin:0;">
<button type="submit" name="do_logout" class="btn btn-sm btn-danger" onclick="return confirm('确定要关闭系统退出登录吗？');">关闭系统</button>
</form>
        </div>
    </div>
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0 fw-semibold">新建礼簿事务</h5>
        </div>
        <div class="card-body">
            <?php if($msg):?><div class="alert alert-warning"><?=htmlspecialchars($msg)?></div><?php endif; ?>
            <form method="post" enctype="multipart/form-data" class="d-flex flex-wrap gap-2 align-items-end">
                <div class="">
                    <label class="form-label">事务名称 <span class="text-danger">*</span></label>
                    <input type="text" name="event_name" class="form-control" style="width:220px;" required>
                </div>
                <div class="">
                    <label class="form-label">礼簿类型</label>
                    <select name="event_type" class="form-select" style="width:110px;">
                        <option value="红事">红事</option>
                        <option value="白事">白事</option>
                    </select>
                </div>
                <div class="">
                    <label class="form-label">管礼人员</label>
                    <input type="text" name="account_person" class="form-control" style="width:160px;" placeholder="管账人员">
                </div>
                <div class="">
                    <label class="form-label">收款二维码</label>
                    <input type="file" name="qrcode_img" class="form-control" style="width:200px;" accept="image/*">
                </div>
                <div class="">
                    <label class="form-label">&nbsp;</label>
                    <button type="submit" name="saveEvent" class="btn btn-primary">创建事务</button>
                </div>
            </form>
        </div>
    </div>
<?php if($editEventData !== null): ?>
<div class="card">
    <div class="card-header">
        <h5 class="mb-0 fw-semibold"修改事务信息（管账人员、收款二维码）</h5>
    </div>
    <div class="card-body">
        <form method="post" enctype="multipart/form-data" class="d-flex flex-wrap gap-2 align-items-end">
            <input type="hidden" name="edit_event_id" value="<?=$editEventId?>">
            <div class="">
                <label class="form-label">事务名称</label>
                <input type="text" name="event_name" class="form-control" style="width:220px;" value="<?=htmlspecialchars($editEventData['event_name']??'')?>" required>
            </div>
            <div class="">
                <label class="form-label">管账人员</label>
                <input type="text" name="account_person" class="form-control" style="width:160px;" value="<?=htmlspecialchars($editEventData['account_person']??'')?>">
            </div>
            <div class="">
                <label class="form-label">更换收款二维码</label>
                <input type="file" name="qrcode_img" class="form-control" style="width:200px;" accept="image/*">
            </div>
            <div class="">
                <label class="form-label">&nbsp;</label>
                <button type="submit" name="saveEventEdit" class="btn btn-success">保存修改</button>
            </div>
        </form>
        <?php if(!empty($editEventData['qrcode_img']) && file_exists(__DIR__.'/'.$editEventData['qrcode_img'])):?>
            <div class="mt-3">当前二维码：<br>
            <img src="<?=htmlspecialchars($editEventData['qrcode_img'])?>" style="width:130px;max-width:100%;border:1px solid #999;padding:6px;border-radius:8px;">
            </div>
        <?php endif;?>
    </div>
</div>
<?php endif; ?>
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0 fw-semibold">我的全部礼簿事务</h5>
        </div>
        <div class="card-body" style="padding:0;">
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>事务ID</th>
                            <th>事务名称</th>
                            <th>类型</th>
                            <th>事务状态</th>
                            <th>管礼人员</th>
                            <th>收款码</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($myEvents)):?>
                            <tr><td colspan="8" class="text-center text-muted py-4">暂无事务，请上方新建礼簿事务</td></tr>
                        <?php else: foreach($myEvents as $ev): ?>
                            <tr>
                                <td><?=$ev['event_id']?></td>
                                <td><?=htmlspecialchars($ev['event_name'])?></td>
                                <td>
                                    <?php if($ev['event_type']==='红事'):?>
                                        <span class="badge" style="background:#fee2e2;color:#b91c1c;">红事</span>
                                    <?php else:?>
                                        <span class="badge" style="background:#e5e7eb;color:#374151;">白事</span>
                                    <?php endif;?>
                                </td>
                                <td>
                                    <?php $evIsClosed = intval($ev['is_closed'] ?? 0); ?>
                                    <?php if($evIsClosed ===1):?>
                                        <span class="badge" style="background:#fed7aa;color:#c2410c;">🔴已移交锁定</span>
                                    <?php else:?>
                                        <span class="badge" style="background:#dcfce7;color:#15803d;">🟢管礼中</span>
                                    <?php endif;?>
                                </td>
                                <td><?=htmlspecialchars($ev['account_person'] ?: '—')?></td>
                                <td>
                                    <?php if(!empty($ev['qrcode_img']) && file_exists(__DIR__.'/'.$ev['qrcode_img'])):?>
                                        <img src="<?=htmlspecialchars($ev['qrcode_img'])?>" style="width:60px;border-radius:6px;">
                                    <?php else:?>—<?php endif;?>
                                </td>
                                <td><?=htmlspecialchars($ev['create_at'])?></td>
                                <td class="text-nowrap">
                                    <a href="?select_event=<?=$ev['event_id']?>" class="btn btn-sm btn-primary">进入</a>
                                    <a href="?edit_event=<?=$ev['event_id']?>" class="btn btn-sm btn-warning">修改</a>
                                    <a href="?del_event=<?=$ev['event_id']?>" onclick="return confirm('确定删除该事务，所有记录将全部清除？')" class="btn btn-sm btn-danger">删除</a>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
<?php else: ?>
<div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
    <h3 class="fw-semibold"><?=htmlspecialchars($currEvent['event_name'])?>
        <?php if($currEvent['event_type']==='红事'):?>
        <span class="badge ms-2" style="background:#fee2e2;color:#b91c1c;">红事</span>
        <?php else:?>
        <span class="badge ms-2" style="background:#e5e7eb;color:#374151;">白事</span>
        <?php endif;?>
    </h3>
    <div class="d-flex gap-2 flex-wrap align-items-center">
        <button id="btnVoiceSwitch" class="btn btn-sm btn-outline-secondary"></button>
 <?php if( !$currIsClosed ): ?>
<form method="post" id="closeBookForm" style="display:inline-block;">
    <input type="hidden" name="submit_password" id="submit_password" value="">
    <button type="button" id="btnCloseBook" class="btn btn-sm btn-warning">📜移交礼簿</button>
</form>
<?php else: ?>
<span class="badge" style="background:#fed7aa;color:#c2410c;font-size:14px;">⚠️礼簿已锁定</span>
<?php endif; ?>
        <a target="_blank" href="gift_book_big_screen.php?select_event=<?=$currEventId?>" class="btn btn-sm btn-info">📺大屏展示</a>
        <button type="button" id="btnScreenPrev" class="btn btn-sm btn-secondary">⏮大屏上一页</button>
        <button type="button" id="btnScreenNext" class="btn btn-sm btn-secondary">⏭大屏下一页</button>
        <button id="btnBigQrToggle" class="btn btn-sm btn-outline-secondary"></button>
        <a target="_blank" href="gift_book_print.php?select_event=<?=$currEventId?>" class="btn btn-sm btn-success">🖨打印预览</a>
        <a href="?back_event" class="btn btn-sm btn-secondary">事务列表</a>
        <a href="change_password.php" class="btn btn-sm btn-warning" style="text-decoration:none;">🔐修改密码</a>
        <a href="?logout" class="btn btn-sm btn-danger">退出礼簿</a>
    </div>
</div>
<?php if($msg):?><div class="alert alert-info"><?=htmlspecialchars($msg)?></div><?php endif; ?>
<?php if(count($myRecords)>800):?>
<div class="alert alert-warning">⚠️当前事务记录数量较多，JSON文件存储性能会下降，建议分新建事务拆分记录</div>
<?php endif;?>
<div class="d-flex flex-wrap gap-2 mb-4">
    <div class="stat-card" style="background:linear-gradient(135deg,#f97316,#ea580c);">
        <div class="label-text">总礼金</div>
        <div class="num-text">¥<?=number_format($totalSum,2) ?></div>
    </div>
    <div class="stat-card" style="background:linear-gradient(135deg,#3b82f6,#2563eb);">
        <div class="label-text">现金合计</div>
        <div class="num-text">¥<?=number_format($sumCash, 2) ?></div>
    </div>
    <div class="stat-card" style="background:linear-gradient(135deg,#22c55e,#16a34a);">
        <div class="label-text">微信合计</div>
        <div class="num-text">¥<?=number_format($sumWechat, 2) ?></div>
    </div>
    <div class="stat-card" style="background:linear-gradient(135deg,#8b5cf6,#7c3aed);">
        <div class="label-text">支付宝合计</div>
        <div class="num-text">¥<?=number_format($sumAlipay, 2) ?></div>
    </div>
    <div class="stat-card" style="background:linear-gradient(135deg,#ec4899,#db2777);">
        <div class="label-text">其它合计</div>
        <div class="num-text">¥<?=number_format($sumOther, 2) ?></div>
    </div>
    <div class="stat-card" style="background:linear-gradient(135deg,#eab308,#ca8a04);">
        <div class="label-text">总人数</div>
        <div class="num-text"><?=$totalCnt?> 人</div>
    </div>
</div>
<?php if(!$currIsClosed):?>
<div class="card">
    <div class="card-header">
        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
            <h5 class="mb-0 fw-semibold">录入宾客礼金记录</h5>
            <?php if($hasSameName):?><span class="badge" style="background:#fee2e2;color:#b91c1c;">检测同名宾客，备注必填 *</span><?php endif;?>
        </div>
    </div>
    <div class="card-body">
        <form method="post" id="itemSaveForm" class="d-flex flex-wrap gap-2 align-items-end">
            <input type="hidden" name="id" value="<?=intval($editRow['id']??0)?>">
            <div class="">
                <label class="form-label">姓名 <span class="text-danger">*</span></label>
                <input id="input_guest_name" type="text" name="name" class="form-control" style="width:130px;" value="<?=htmlspecialchars($oldInput['name'])?>" required
oninput="sendPreviewName(this.value)">
            </div>
            <div class="">
                <label class="form-label">礼金 <span class="text-danger">*</span></label>
                <input type="number" min="0.01" step="0.01" name="money" class="form-control" style="width:110px;" value="<?=htmlspecialchars($oldInput['money'])?>" required>
            </div>
            <div class="">
                <label class="form-label">支付方式</label>
                <select name="pay_way" class="form-select" style="width:120px;">
                    <option value="现金" <?= $oldInput['pay_way']==='现金'?'selected':'' ?>>现金</option>
                    <option value="微信" <?= $oldInput['pay_way']==='微信'?'selected':'' ?>>微信</option>
                    <option value="支付宝" <?= $oldInput['pay_way']==='支付宝'?'selected':'' ?>>支付宝</option>
                    <option value="其它" <?= $oldInput['pay_way']==='其它'?'selected':'' ?>>其它</option>
                </select>
            </div>
            <div class="">
                <label class="form-label">礼品</label>
                <input type="text" name="gift" class="form-control" style="width:130px;" value="<?=htmlspecialchars($oldInput['gift'])?>">
            </div>
            <div class="">
                <label class="form-label">备注 <?php if($hasSameName):?><span class="text-danger">*</span><?php endif;?></label>
                <input type="text" name="remark" class="form-control" style="width:160px;" value="<?=htmlspecialchars($oldInput['remark'])?>">
            </div>
            <div class="d-flex gap-2">
                <label class="form-label">&nbsp;</label>
                <button type="submit" name="saveItem" class="btn btn-primary"><?=$editRow?'保存修改':'新增记录'?></button>
                <?php if($editRow):?>
                <a href="?select_event=<?=$currEventId?>" class="btn btn-outline-secondary">取消修改</a>
                <?php endif;?>
            </div>
        </form>
    </div>
</div>
<?php else:?>
<div class="alert alert-warning text-center" style="font-size:18px;">
    📜本礼簿已经移交锁定，不能新增、修改记录，仅支持查看筛选与打印导出PDF
</div>
<?php endif;?>
<div class="card">
    <div class="card-header">
        <h5 class="mb-0 fw-semibold">筛选查询</h5>
    </div>
    <div class="card-body">
       <form class="d-flex flex-wrap gap-2 align-items-end" method="get">
    <input type="hidden" name="select_event" value="<?=$currEventId?>">
    <div class="">
        <label class="form-label">宾客姓名搜索</label>
        <input type="text" name="kw" class="form-control" style="width:200px;" value="<?=htmlspecialchars($kw)?>">
    </div>
    <div class="">
        <label class="form-label">记录ID查询(单ID/3‑15/2,5,9)</label>
        <input type="text" name="id_query" class="form-control" style="width:220px;" value="<?=htmlspecialchars($idQuery)?>" placeholder="例：5  或 3‑15  或 2,7,12">
    </div>
    <div class="">
        <label class="form-label">筛选类型</label>
        <select name="filter_type" class="form-select" style="width:200px;">
            <option value="">全部</option>
            <option value="现金" <?=$filterType==='现金'?'selected':''?>>现金</option>
            <option value="微信" <?=$filterType==='微信'?'selected':''?>>微信</option>
            <option value="支付宝" <?=$filterType==='支付宝'?'selected':''?>>支付宝</option>
            <option value="其它" <?=$filterType==='其它'?'selected':''?>>其它</option>
            <option value="gift" <?=$filterType==='gift'?'selected':''?>>礼品（显示有礼品记录）</option>
            <option value="remark" <?=$filterType==='remark'?'selected':''?>>备注（显示有备注记录）</option>
        </select>
    </div>
    <div class="d-flex gap-2">
        <label class="form-label">&nbsp;</label>
        <button class="btn btn-primary">查询</button>
        <a href="?select_event=<?=$currEventId?>" class="btn btn-outline-secondary">重置</a>
        <button type="button" id="btnShowAllLog" class="btn btn-warning">📋查看全部操作记录</button>
    </div>
</form>
    </div>
</div>
<div class="card">
    <div class="card-header">
        <h5 class="mb-0 fw-semibold">宾客记录列表（新记录在最上方）</h5>
    </div>
    <div class="card-body" style="padding:0;">
        <div class="table-responsive">
            <table class="table">
                <thead>
                  <tr>
                     <th>ID</th>
                     <th>姓名</th>
                     <th>礼金</th>
                     <th>支付方式</th>
                     <th>礼品</th>
                     <th>备注</th>
                     <th>录入时间</th>
                     <th>修改次数</th>
                     <th>操作</th>
                         </tr>
                </thead>
                <tbody>
                    <?php if(empty($showList)):?>
                        <tr><td colspan="9" class="text-center text-muted py-4">暂无宾客记录</td></tr>
                    <?php else: foreach($showList as $rec): ?>
                        <tr>
                            <td><?=$rec['id']?></td>
                            <td><?=htmlspecialchars($rec['name'])?></td>
                            <td>¥<?=number_format($rec['money'],2)?></td>
                            <td><?=htmlspecialchars($rec['pay_way'])?></td>
                            <td><?=htmlspecialchars($rec['gift']??'—')?></td>
                            <td><?=htmlspecialchars($rec['remark']??'—')?></td>
                            <td><?=htmlspecialchars($rec['create_time'])?></td>
                            <td><?=intval($rec['edit_count'])?>/3</td>
                            <td class="text-nowrap">
                                <?php if(!$currIsClosed):?>
                                <a href="?select_event=<?=$currEventId?>&edit=<?=$rec['id']?>" class="btn btn-sm btn-warning">修改</a>
                                <?php endif;?>
                                <button class="btn btn-sm btn-info btn-log-modal"
                                        data-record-id="<?=$rec['id']?>"
                                        data-record-name="<?=htmlspecialchars($rec['name'])?>"
                                        data-log="<?=htmlspecialchars(json_encode($rec['edit_log'],JSON_UNESCAPED_UNICODE))?>">
                                     查看修改记录
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<div class="modal" id="recordLogModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="recordLogModalLabel">记录修改历史</h5>
        <button type="button" class="btn-close" onclick="closeModal('recordLogModal')">×</button>
      </div>
      <div class="modal-body" id="modalLogBody"></div>
     <div class="modal-footer">
        <button type="button" class="btn btn-secondary" onclick="closeModal('recordLogModal')" style="padding:8px 22px;">关闭</button>
    </div>
    </div>
  </div>
</div>
<div class="modal" id="allLogModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl">
     <div class="modal-content">
      <div class="modal-header" style="display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid #e5e7eb;background:#fff;">
  <h5 class="modal-title" style="margin:0;font-size:26px;font-weight:700;color:#111827;">📋 全部操作记录</h5>
  <div style="display:flex;align-items:center;gap:12px;">
    <button type="button" onclick="closeModal('allLogModal')" style="padding:7px 18px;font-size:15px;border:1px solid #d1d5db;border-radius:6px;background:#f9fafb;cursor:pointer;">关闭</button>
    <button type="button" onclick="closeModal('allLogModal')" style="font-size:24px;line-height:1;padding:0 8px;border:none;background:transparent;cursor:pointer;">×</button>
  </div>
</div>
<div class="modal-body" id="allLogModalBody" style="padding:0;">
   <!-- 查询操作记录筛选栏 -->
  <div style="
    position:sticky;
    top:0;
    z-index:3;
    background:#f9fafb;
    padding:14px 20px;
    border-bottom:1px solid #e5e7eb;
  ">
    <!-- 第一行：筛选下拉 + 统计条数（统计移到下拉右侧，同一行） -->
    <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
        <label style="font-size:14px;font-weight:600;color:#374151;">筛选类型：</label>
        <select id="logTypeSelect" class="form-select" style="width:180px;height:40px;">
          <option value="">全部操作</option>
          <option value="add">新增记录</option>
          <option value="edit">修改记录</option>
        </select>
        <!-- 这里删掉 margin‑left:auto，直接紧跟在下拉后面 -->
        <div style="font-size:14px;font-weight:600;color:#111827;">
            <span id="logStatInfo">共 0 条记录</span>
        </div>
    </div>
    <!-- 第二行：图例，单独一行 -->
    <div style="display:flex;gap:24px;align-items:center;margin-top:8px;">
      <span style="font-size:13px;color:#6b7280;display:flex;align-items:center;gap:6px;">
        <span style="width:8px;height:8px;border-radius:50%;background:#10b981;flex-shrink:0;"></span>
        新增
      </span>
      <span style="font-size:13px;color:#6b7280;display:flex;align-items:center;gap:6px;">
        <span style="width:8px;height:8px;border-radius:50%;background:#ef4444;flex-shrink:0;"></span>
        修改
      </span>
    </div>
  </div>

  <!-- 表格区 -->
  <div id="logTableWrap" style="
    padding:0;
    max-height:65vh;
    overflow-y:auto;
    background:#fff;
    scrollbar-width:thin;
    scrollbar-color:#cbd5e1 #f1f5f9;
  "></div>
</div>
     </div>
  </div>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<script>
//实时上报输入的宾客预览姓名给session，大屏读取
async function sendPreviewName(nameVal){
    const fd = new FormData();
    fd.append('preview_guest_name', nameVal);
    await fetch('',{
        method:'POST',
        body:fd,
        credentials:"same-origin"
    });
}
function openModal(id){
    const el = document.getElementById(id);
    if(el) el.style.display = 'block';
}
function closeModal(id){
    const el = document.getElementById(id);
    if(el) el.style.display = 'none';
}
const rawAllLogs = <?php echo $jsonAllLogs; ?>;
const openRegBtn = document.getElementById('openRegBtn');
if(openRegBtn){
    openRegBtn.addEventListener('click',function(){
        openModal('regModal');
    });
}
const btnCloseBook = document.getElementById("btnCloseBook");
if(btnCloseBook){
    btnCloseBook.addEventListener("click",function(){
        const confirmTip = confirm("⚠️确认移交礼簿？确认之后本礼簿所有记录将永久禁止新增和修改，仅允许查看、查询、打印，此操作不可撤销！");
        if(!confirmTip){
            return;
        }
        const inputPwd = prompt("请输入您当前登录账号的密码，确认执行移交礼簿操作：","");
        if(inputPwd === null || inputPwd.trim() === ""){
            alert("操作已取消，未执行移交！");
            return;
        }
        document.getElementById("submit_password").value = inputPwd.trim();
        document.getElementById("closeBookForm").submit();
    });
}
//语音开关转换
let voiceSwitch = <?=json_encode($_SESSION['voice_switch'])?>;
const btnVoice = document.getElementById('btnVoiceSwitch');
function setVoiceBtn(){
    if(!btnVoice) return;
    if(voiceSwitch){
        btnVoice.innerText = "🔊开启语音";
        btnVoice.classList.remove('btn-outline-secondary');
        btnVoice.classList.add('btn-success');
    }else{
        btnVoice.innerText = "🔇语音关闭";
        btnVoice.classList.remove('btn-success');
        btnVoice.classList.add('btn-outline-secondary');
    }
}
if(btnVoice){
    setVoiceBtn();
    btnVoice.onclick = async function(){
        voiceSwitch = !voiceSwitch;
        setVoiceBtn();
        const fd = new FormData();
        fd.append('action','voice_switch');
        fd.append('val', voiceSwitch ? 1 : 0);
        await fetch('',{method:'POST',body:fd,credentials:"same-origin"});
    }
}
//=====二维码切换按钮,默认为隐藏状态=====
let qrVisibleSwitch = <?=json_encode(!empty($_SESSION['big_screen_qrcode_visible']) ? true : false)?>;
const btnBigQrToggle = document.getElementById('btnBigQrToggle');
function setBigQrToggleBtn(){
    if(!btnBigQrToggle) return;
    if(qrVisibleSwitch){
        btnBigQrToggle.innerText = "📱隐藏大屏二维码";
        btnBigQrToggle.className = "btn btn-sm btn-qrcode-on";
    }else{
        btnBigQrToggle.innerText = "📱显示大屏二维码";
        btnBigQrToggle.className = "btn btn-sm btn-qrcode-off";
    }
}
if(btnBigQrToggle){
    setBigQrToggleBtn();
    btnBigQrToggle.onclick = async function(){
        qrVisibleSwitch = !qrVisibleSwitch;
        setBigQrToggleBtn();
        const fd = new FormData();
        fd.append('ctrl_big_qrcode', qrVisibleSwitch ? 1 : 0);
        await fetch('',{method:'POST',body:fd,credentials:"same-origin"});
    }
}
<?php if(!empty($tempSpeech)):?>
const speakText = <?=json_encode($tempSpeech)?>;
if(voiceSwitch && window.speechSynthesis){
    speechSynthesis.cancel();
    const utter = new SpeechSynthesisUtterance(speakText);
    utter.lang = 'zh-CN';
    speechSynthesis.speak(utter);
}
<?php endif; ?>
const modalLogBody = document.getElementById('modalLogBody');
document.querySelectorAll('.btn-log-modal').forEach(btn=>{
    btn.addEventListener('click',function(){
        const recordId = this.dataset.recordId;
        const recordName = this.dataset.recordName;
        const logRaw = this.dataset.log;
        let logList = [];
        try{
            logList = JSON.parse(logRaw);
        }catch(e){
            logList = [];
        }
        let html = `<h6>ID：${recordId}｜宾客姓名：${escapeHtml(recordName)}</h6><hr>`;
        if(logList.length === 0){
            html += '<div class="text-muted">暂无操作记录</div>';
        }else{
            logList.forEach(item=>{
                const opType = item.operate_type === 'add' ? '🟢新增记录' : '🔴修改记录';
                html += `<div class="border rounded p-3 mb-3" style="border:1px solid var(--gray-200);border-radius:var(--radius-md);">
                    <div><strong>操作时间：</strong>${item.edit_time} &nbsp; <strong>操作类型：</strong>${opType}</div>
                    <div class="row mt-2" style="display:flex;flex-wrap:wrap;gap:1rem;">
                        <div style="flex:1;min-width:240px;">
                            <div class="text-muted">修改前：</div>
                            ${ Object.keys(item.old).length > 0 ?
                                `姓名：${escapeHtml(item.old.name||'')}<br>
                                 礼金：¥${item.old.money||0}<br>
                                 支付：${escapeHtml(item.old.pay_way||'')}<br>
                                 礼品：${escapeHtml(item.old.gift||'—')}<br>
                                 备注：${escapeHtml(item.old.remark||'—')}`
                                : '<span class="text-secondary">（新增无旧数据）</span>'
                            }
                        </div>
                        <div style="flex:1;min-width:240px;">
                            <div class="text-muted">修改后：</div>
                             姓名：${escapeHtml(item.new.name||'')}<br>
                             礼金：¥${item.new.money||0}<br>
                             支付：${escapeHtml(item.new.pay_way||'')}<br>
                             礼品：${escapeHtml(item.new.gift||'—')}<br>
                             备注：${escapeHtml(item.new.remark||'—')}
                        </div>
                    </div>
                </div>`;
            });
        }
        modalLogBody.innerHTML = html;
        openModal('recordLogModal');
    });
});
const allLogModalBody = document.getElementById('allLogModalBody');
const btnShowAllLog = document.getElementById('btnShowAllLog');
if(btnShowAllLog){
    btnShowAllLog.addEventListener('click',function(){
        renderLogTable("");
        openModal('allLogModal');
        //下拉切换事件
        setTimeout(()=>{
            const sel = document.getElementById('logTypeSelect');
            sel.onchange = function(){
                renderLogTable(this.value);
            }
        },100);
    });
}
//渲染日志表格函数，接收筛选类型：''全部 / add新增 / edit修改
function renderLogTable(filterType){
    const wrapDom = document.getElementById('logTableWrap');
    let html = '';
    //根据下拉值过滤日志数组
    let filterLogs = rawAllLogs;
    if(filterType !== ""){
        filterLogs = rawAllLogs.filter(item=>item.operate_type === filterType);
    }
    if(!filterLogs || filterLogs.length === 0){
        html = '<div class="text-center text-muted py-4">暂无任何操作记录</div>';
    }else{
        html += `<div class="table-responsive">
<table class="table" style="margin-bottom:0;">
<thead style="position:sticky;top:0;z-index:1;background:#f3f4f6;">
<tr>
<th style="width:90px;font-weight:700;color:#111827;">记录ID</th>
<th style="width:110px;font-weight:700;color:#111827;">宾客姓名</th>
<th style="width:160px;font-weight:700;color:#111827;">操作时间</th>
<th style="width:100px;font-weight:700;color:#111827;">操作类型</th>
<th style="width:32%;font-weight:700;color:#111827;">修改前</th>
<th style="width:32%;font-weight:700;color:#111827;">修改后</th>
</tr>
</thead><tbody>`;

        filterLogs.forEach(log=>{
            const opText = log.operate_type === 'add' ? '🟢新增' : '🔴修改';
            let oldHtml = '';
            if(Object.keys(log.old||{}).length > 0){
                oldHtml = `姓名：${escapeHtml(log.old.name||'')}<br>礼金：¥${log.old.money||0}<br>支付：${escapeHtml(log.old.pay_way||'')}<br>礼品：${escapeHtml(log.old.gift||'—')}<br>备注：${escapeHtml(log.old.remark||'—')}`;
            }else{
                oldHtml = '<span class="text-secondary">新增无旧数据</span>';
            }
            const newHtml = `姓名：${escapeHtml(log.new.name||'')}<br>礼金：¥${log.new.money||0}<br>支付：${escapeHtml(log.new.pay_way||'')}<br>礼品：${escapeHtml(log.new.gift||'—')}<br>备注：${escapeHtml(log.new.remark||'—')}`;

            html += `<tr style="border-bottom:1px solid #f1f5f9;">
        <td style="font-weight:600;color:#111827;">${log.record_id}</td>
        <td style="font-weight:600;color:#111827;">${escapeHtml(log.record_name)}</td>
        <td style="color:#4b5563;font-size:14px;">${log.edit_time}</td>
        <td>
          <span style="
            display:inline-flex;
            align-items:center;
            gap:6px;
            padding:4px 10px;
            border-radius:999px;
            font-size:13px;
            font-weight:600;
            background:${log.operate_type === 'add' ? '#d1fae5' : '#fee2e2'};
            color:${log.operate_type === 'add' ? '#065f46' : '#991b1b'};
          ">
                  ${opText}
          </span>
        </td>
        <td style="background:#fafafa;color:#374151;font-size:14px;line-height:1.7;">${oldHtml}</td>
        <td style="background:#fff;color:#111827;font-size:14px;line-height:1.7;font-weight:500;">${newHtml}</td>
        </tr>`;
        });
        html += `</tbody></table></div>`;
    }
    wrapDom.innerHTML = html;

    const statDom = document.getElementById('logStatInfo');
    if(statDom){
      const total = filterLogs && filterLogs.length ? filterLogs.length : 0;
      statDom.textContent = '共 ' + total + ' 条记录';
    }
}
function escapeHtml(s){
    if(!s) return '';
    return String(s).replace(/[&<>"']/g,m=>{
        const map={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'};
        return map[m];
    });
}
document.addEventListener('DOMContentLoaded', function(){
    const nameInput = document.getElementById('input_guest_name');
    if(nameInput){
        setTimeout(()=>{
            nameInput.focus();
            nameInput.select();
        }, 80);
    }
const formEl = document.getElementById("itemSaveForm");
formEl.addEventListener("submit",function(e){
    const moneyInput = document.querySelector('input[name="money"]');
    const moneyVal = moneyInput.value.trim();
 //对金额进行校验，只允许最多 2 位小数，防止输入 100.123 这种无效金额
if(/\.\d{3,}/.test(moneyVal)){
    e.preventDefault();
    alert("⚠️金额最多只能输入两位小数（角、分）！");
    moneyInput.focus();
    return;
}
    const nameVal = (document.getElementById("input_guest_name").value||'').trim();
    const remarkVal = (document.querySelector('input[name="remark"]').value||'').trim();
    const recordList = <?=json_encode($myRecords,JSON_UNESCAPED_UNICODE)?>;
    const editId = parseInt(document.querySelector('input[name="id"]').value||"0");
    let hasDup = false;
    for(let r of recordList){
        if(r.name === nameVal && parseInt(r.id)!== editId){
            hasDup = true;
            break;
        }
    }
    // 规则：有同名并且备注为空  弹窗，禁止提交；同名且备注有内容 → 无弹窗直接提交
    if(hasDup && remarkVal === ''){
        e.preventDefault();
        alert("⚠️检测到系统中已经存在同名宾客【"+nameVal+"】！\n该姓名必须填写备注区分，请填写备注信息，否则无法保存。");
        return;
    }
});
});
//远程控制大屏翻页
document.getElementById('btnScreenPrev').addEventListener('click',async function(){
    const fd=new FormData();
    fd.append('screen_page_cmd','prev');
    await fetch('',{method:'POST',body:fd,credentials:"same-origin"});
});
document.getElementById('btnScreenNext').addEventListener('click',async function(){
    const fd=new FormData();
    fd.append('screen_page_cmd','next');
    await fetch('',{method:'POST',body:fd,credentials:"same-origin"});
});
</script>
</body>
</html>
<?php ob_end_flush(); ?>

