<?php
/**
 * 简易管理后台
 * 登录后可查看/处理预约记录，修改管理密码
 * 部署时建议将 admin 目录改名成随机路径
 */
session_name('XYWEDSESS');
session_start();

$conf = require dirname(__DIR__) . '/config.php';
$passFile = $conf['DATA_DIR'] . '/admin_pass.php';
$hash = null;
if (is_file($passFile)) {
    $hash = trim(substr(file_get_contents($passFile), strlen('<?php exit; ?>')));
}

function logout() {
    $_SESSION = array();
    session_destroy();
    header('Location: index.php');
    exit;
}

if (isset($_GET['action']) && $_GET['action'] === 'logout') logout();

$msg = '';
$logged = isset($_SESSION['xy_admin']) && $_SESSION['xy_admin'] === true;

// 登录
if (!$logged && isset($_POST['pass'])) {
    if ($hash === null) {
        // 首次登录：明文校验并转哈希
        if (hash_equals($conf['ADMIN_PASS'], $_POST['pass'])) {
            if (!is_dir($conf['DATA_DIR'])) @mkdir($conf['DATA_DIR'], 0755, true);
            @file_put_contents($passFile, '<?php exit; ?>' . password_hash($_POST['pass'], PASSWORD_DEFAULT));
            $_SESSION['xy_admin'] = true;
            $logged = true;
        } else {
            $msg = '密码错误';
        }
    } else if (password_verify($_POST['pass'], $hash)) {
        $_SESSION['xy_admin'] = true;
        $logged = true;
    } else {
        $msg = '密码错误';
    }
}

// 修改密码
if ($logged && isset($_POST['newpass']) && $_POST['newpass'] !== '') {
    $np = trim($_POST['newpass']);
    if (strlen($np) >= 8) {
        if (!is_dir($conf['DATA_DIR'])) @mkdir($conf['DATA_DIR'], 0755, true);
        @file_put_contents($passFile, '<?php exit; ?>' . password_hash($np, PASSWORD_DEFAULT));
        $msg = '密码已修改';
    } else {
        $msg = '新密码至少8位';
    }
}

// 处理预约（标记/删除）
$bookFile = $conf['DATA_DIR'] . '/bookings.json';
$bookings = is_file($bookFile) ? json_decode(file_get_contents($bookFile), true) : array();
if (!is_array($bookings)) $bookings = array();

if ($logged && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['act'])) {
    $i = isset($_POST['i']) ? intval($_POST['i']) : -1;
    if (isset($bookings[$i])) {
        if ($_POST['act'] === 'done')  $bookings[$i]['status'] = 1;
        if ($_POST['act'] === 'undone') $bookings[$i]['status'] = 0;
        if ($_POST['act'] === 'del')   array_splice($bookings, $i, 1);
        @file_put_contents($bookFile, json_encode($bookings, JSON_UNESCAPED_UNICODE), LOCK_EX);
    }
}

// 领券记录
$couponFile = $conf['DATA_DIR'] . '/coupons.json';
$coupons = is_file($couponFile) ? json_decode(file_get_contents($couponFile), true) : array();
if (!is_array($coupons)) $coupons = array();

if ($logged && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cact'])) {
    $i = isset($_POST['i']) ? intval($_POST['i']) : -1;
    if (isset($coupons[$i])) {
        if ($_POST['cact'] === 'done')  $coupons[$i]['status'] = 1;
        if ($_POST['cact'] === 'del')   array_splice($coupons, $i, 1);
        @file_put_contents($couponFile, json_encode($coupons, JSON_UNESCAPED_UNICODE), LOCK_EX);
    }
}

$tab = isset($_GET['tab']) && $_GET['tab'] === 'coupon' ? 'coupon' : 'booking';
?>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>囍缘婚礼 · 管理</title>
<style>
* { box-sizing: border-box; }
body { font: 14px/1.6 "Microsoft YaHei", sans-serif; background: #f4f1ec; color: #333; margin: 0; }
.wrap { max-width: 960px; margin: 30px auto; padding: 0 16px; }
h1 { font-size: 20px; color: #8a6a3f; }
.card { background: #fff; border-radius: 8px; padding: 22px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,.05); }
input[type=password], input[type=text] { padding: 8px 10px; border: 1px solid #ddd; border-radius: 4px; width: 240px; }
button { padding: 8px 18px; background: #b4885c; color: #fff; border: none; border-radius: 4px; cursor: pointer; }
button.gray { background: #999; }
table { width: 100%; border-collapse: collapse; }
th, td { border-bottom: 1px solid #eee; padding: 10px 8px; text-align: left; font-size: 13px; }
th { color: #8a6a3f; }
.tag { display: inline-block; padding: 1px 8px; border-radius: 3px; font-size: 12px; }
.tag0 { background: #fdeaea; color: #c0392b; }
.tag1 { background: #e8f6e8; color: #27ae60; }
form.inline { display: inline; }
.msg { color: #c0392b; margin-top: 10px; }
.logout { float: right; font-size: 13px; color: #999; }
.tabs { margin-bottom: 16px; }
.tablink { display: inline-block; padding: 7px 22px; border-radius: 4px 4px 0 0; background: #e8e2d8; color: #666; margin-right: 6px; font-size: 14px; }
.tablink.on { background: #b4885c; color: #fff; }
</style>
</head>
<body>
<div class="wrap">
<?php if (!$logged): ?>
  <div class="card" style="max-width:360px;margin:80px auto;">
    <h1>囍缘婚礼 · 管理登录</h1>
    <form method="post">
      <input type="password" name="pass" placeholder="管理密码" autofocus>
      <button type="submit">登录</button>
    </form>
    <?php if ($msg) echo '<div class="msg">' . htmlspecialchars($msg) . '</div>'; ?>
  </div>
<?php else: ?>
  <h1>预约管理 <a class="logout" href="?action=logout">退出</a></h1>

  <div class="tabs">
    <a class="tablink <?php echo $tab === 'booking' ? 'on' : ''; ?>" href="?tab=booking">预约记录</a>
    <a class="tablink <?php echo $tab === 'coupon' ? 'on' : ''; ?>" href="?tab=coupon">领券记录</a>
  </div>

  <div class="card">
    <strong>修改管理密码</strong>
    <form method="post" style="margin-top:10px;">
      <input type="password" name="newpass" placeholder="新密码（至少8位）">
      <button type="submit" class="gray">保存</button>
    </form>
    <?php if ($msg) echo '<div class="msg">' . htmlspecialchars($msg) . '</div>'; ?>
  </div>

<?php if ($tab === 'booking'): ?>
  <div class="card">
    <table>
      <tr><th>时间</th><th>称呼</th><th>手机号</th><th>婚期</th><th>意向</th><th>备注</th><th>状态</th><th>操作</th></tr>
      <?php if (!$bookings): ?>
      <tr><td colspan="8" style="color:#999;">暂无预约记录</td></tr>
      <?php endif; ?>
      <?php foreach ($bookings as $i => $b): ?>
      <tr>
        <td><?php echo htmlspecialchars($b['time']); ?></td>
        <td><?php echo htmlspecialchars($b['name']); ?></td>
        <td><?php echo htmlspecialchars($b['phone']); ?></td>
        <td><?php echo htmlspecialchars($b['date']); ?></td>
        <td><?php echo htmlspecialchars($b['service']); ?></td>
        <td style="max-width:220px;"><?php echo htmlspecialchars($b['note']); ?></td>
        <td><span class="tag tag<?php echo intval($b['status']); ?>"><?php echo intval($b['status']) ? '已处理' : '待跟进'; ?></span></td>
        <td>
          <form class="inline" method="post"><input type="hidden" name="i" value="<?php echo $i; ?>">
            <?php if (intval($b['status'])): ?>
            <button class="gray" name="act" value="undone">待跟进</button>
            <?php else: ?>
            <button name="act" value="done">已处理</button>
            <?php endif; ?>
          </form>
          <form class="inline" method="post"><input type="hidden" name="i" value="<?php echo $i; ?>">
            <button class="gray" name="act" value="del" onclick="return confirm('确认删除?')">删除</button>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
<?php else: ?>
  <div class="card">
    <table>
      <tr><th>时间</th><th>手机号</th><th>券名</th><th>状态</th><th>操作</th></tr>
      <?php if (!$coupons): ?>
      <tr><td colspan="5" style="color:#999;">暂无领券记录</td></tr>
      <?php endif; ?>
      <?php foreach ($coupons as $i => $c): ?>
      <tr>
        <td><?php echo htmlspecialchars($c['time']); ?></td>
        <td><?php echo htmlspecialchars($c['phone']); ?></td>
        <td><?php echo htmlspecialchars($c['coupon']); ?></td>
        <td><span class="tag tag<?php echo intval($c['status']); ?>"><?php echo intval($c['status']) ? '已核销' : '未核销'; ?></span></td>
        <td>
          <form class="inline" method="post"><input type="hidden" name="i" value="<?php echo $i; ?>">
            <?php if (intval($c['status'])): ?>
            <button class="gray" name="cact" value="del">删除</button>
            <?php else: ?>
            <button name="cact" value="done">核销</button>
            <?php endif; ?>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
<?php endif; ?>
<?php endif; ?>
</div>
</body>
</html>
