<?php
/**
 * /www/auth.php  —  로그인 / 회원가입  (실연동)
 * ------------------------------------------------------------------
 *  이메일/비밀번호 회원가입·로그인 동작. 소셜(카카오/네이버/구글)은 데모(OAuth 추후).
 *  users 테이블이 아직 없으면 친절 안내로 폴백(사이트는 안 깨짐).
 *  ?tab=login(기본) | join
 * ------------------------------------------------------------------
 */

require_once __DIR__ . '/includes/config.php';   // $pdo, 세션, won(), e()

/** 로그인 후 돌아갈 '내부 경로'만 허용 (open-redirect 방지) */
function auth_safe_next(?string $u): string {
    $u = trim((string)$u);
    if ($u === '' || $u[0] !== '/' || str_starts_with($u, '//') || preg_match('~[\r\n]~', $u)) return '/mypage.php';
    return $u;
}
$next = auth_safe_next($_POST['next'] ?? $_GET['next'] ?? '');

// 이미 로그인 상태면 돌아갈 곳(없으면 마이페이지)으로
if (is_logged_in()) { header('Location: ' . $next); exit; }

$tab = ($_GET['tab'] ?? 'login') === 'join' ? 'join' : 'login';
$err = '';
$old_email = '';
if (!empty($_SESSION['auth_error'])) {
    $err = (string)$_SESSION['auth_error'];
    unset($_SESSION['auth_error']);
}

/* ---------------- POST: 로그인 / 회원가입 ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action    = $_POST['action'] ?? '';
    $old_email = trim($_POST['email'] ?? '');
    try {
        if ($action === 'login') {
            $tab   = 'login';
            $email = trim($_POST['email'] ?? '');
            $pw    = (string)($_POST['password'] ?? '');
            $st = $pdo->prepare("SELECT id, password_hash, is_active FROM users WHERE email = ?");
            $st->execute([$email]);
            $row = $st->fetch();
            if (!$row || !password_verify($pw, (string)$row['password_hash'])) {
                $err = '이메일 또는 비밀번호가 올바르지 않아요.';
            } elseif ((int)$row['is_active'] !== 1) {
                $err = '이용이 정지된 계정이에요. 고객센터로 문의해 주세요.';
            } else {
                session_regenerate_id(true);
                $_SESSION['user_id'] = (int)$row['id'];
                cart_merge();   // 비회원으로 담은 장바구니 → 회원 carts 병합
                header('Location: ' . $next); exit;
            }
        } elseif ($action === 'join') {
            $tab   = 'join';
            $email = trim($_POST['email'] ?? '');
            $pw    = (string)($_POST['password'] ?? '');
            $pw2   = (string)($_POST['password2'] ?? '');
            $name  = trim($_POST['name'] ?? '');
            $phone = trim($_POST['phone'] ?? '');
            $agree = isset($_POST['agree']);
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $err = '올바른 이메일을 입력해 주세요.'; }
            elseif (mb_strlen($pw) < 8)                     { $err = '비밀번호는 8자 이상으로 정해 주세요.'; }
            elseif ($pw !== $pw2)                           { $err = '비밀번호 확인이 일치하지 않아요.'; }
            elseif ($name === '')                           { $err = '이름을 입력해 주세요.'; }
            elseif (!$agree)                                { $err = '약관에 동의해 주세요.'; }
            else {
                $dup = $pdo->prepare("SELECT id FROM users WHERE email = ?");
                $dup->execute([$email]);
                if ($dup->fetch()) {
                    $err = '이미 가입된 이메일이에요. 로그인해 주세요.';
                } else {
                    $ins = $pdo->prepare("INSERT INTO users (email, password_hash, name, phone, created_at) VALUES (?, ?, ?, ?, NOW())");
                    $ins->execute([$email, password_hash($pw, PASSWORD_DEFAULT), $name, $phone]);
                    $newUid = (int)$pdo->lastInsertId();
                    kp_grant_signup_points($pdo, $newUid);   // 신규가입 적립금 지급
                    session_regenerate_id(true);
                    $_SESSION['user_id'] = $newUid;
                    cart_merge();   // 가입 전 담은 장바구니 → 회원 carts 병합
                    header('Location: ' . $next); exit;
                }
            }
        }
    } catch (Throwable $ex) {
        $err = '회원 기능이 아직 준비 중이에요. (users 테이블 생성이 필요합니다)';
    }
}

$word = $tab === 'join' ? '가입' : '로그인';

$page_title  = ($tab === 'join' ? '회원가입' : '로그인') . ' | KPOPPOCA';
$active_nav  = '';
include __DIR__ . '/includes/header.php';
?>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Unbounded:wght@600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.css">

<style>
.au-wrap{ max-width:430px; margin:0 auto; padding:42px 18px 90px; font-family:'Pretendard',sans-serif; color:#141414; word-break:keep-all; }
.au-logo{ text-align:center; font-family:'Unbounded',sans-serif; font-weight:800; font-size:24px; margin-bottom:22px; }
.au-logo b{ color:#FF1488; } .au-logo .star{ color:#FF1488; font-size:13px; vertical-align:super; }

.au-card{ background:#fff; border:1.5px solid #f0eef2; border-radius:20px; padding:30px 26px; box-shadow:0 18px 50px rgba(20,20,20,.06); }

/* 탭 */
.au-tabs{ display:flex; background:#f6f6f8; border-radius:12px; padding:5px; margin-bottom:24px; }
.au-tabs a{ flex:1; text-align:center; text-decoration:none; font-family:'Unbounded',sans-serif; font-weight:700; font-size:14px; color:#999; padding:11px 0; border-radius:9px; transition:.14s; }
.au-tabs a.on{ background:#FF1488; color:#fff; box-shadow:0 6px 16px rgba(255,20,136,.26); }

.au-field{ margin-bottom:14px; }
.au-field label{ display:block; font-size:12.5px; font-weight:700; color:#555; margin-bottom:6px; }
.au-input{ width:100%; box-sizing:border-box; height:48px; padding:0 14px; font-size:14px; font-family:'Pretendard'; border:1.5px solid #e6e6ea; border-radius:11px; outline:none; transition:.14s; }
.au-input:focus{ border-color:#FF1488; box-shadow:0 0 0 3px #FFE3F0; }

.au-row{ display:flex; align-items:center; justify-content:space-between; font-size:13px; margin:4px 2px 18px; }
.au-row label{ display:flex; align-items:center; gap:6px; color:#555; cursor:pointer; }
.au-row a{ color:#888; text-decoration:none; } .au-row a:hover{ color:#FF1488; }

.au-submit{ width:100%; padding:15px; border:none; border-radius:12px; background:#FF1488; color:#fff; font-weight:800; font-size:15px; cursor:pointer; box-shadow:0 10px 24px rgba(255,20,136,.28); transition:.16s; }
.au-submit:hover{ transform:translateY(-2px); }

.au-err{ background:#fdecec; color:#d33; font-size:13px; font-weight:700; border-radius:11px; padding:12px 14px; margin-bottom:16px; line-height:1.5; }

.au-agree{ display:flex; align-items:center; justify-content:space-between; font-size:13px; color:#444; background:#fafafa; border-radius:10px; padding:12px 14px; margin:4px 0 18px; }
.au-agree label{ display:flex; align-items:center; gap:8px; font-weight:700; cursor:pointer; }
.au-agree a{ color:#aaa; font-size:12px; text-decoration:underline; }

.au-switch{ text-align:center; font-size:13px; color:#999; margin-top:18px; }
.au-switch a{ color:#FF1488; font-weight:800; text-decoration:none; margin-left:5px; }

/* 소셜 */
.au-or{ display:flex; align-items:center; gap:12px; color:#bbb; font-size:12px; margin:24px 0 16px; }
.au-or::before,.au-or::after{ content:''; flex:1; height:1px; background:#eee; }
.au-socials{ display:flex; flex-direction:column; gap:9px; }
.au-social{ display:flex; align-items:center; justify-content:center; gap:9px; height:48px; border-radius:11px; font-weight:700; font-size:14px; text-decoration:none; border:1.5px solid transparent; cursor:pointer; }
.au-kakao{ background:#FEE500; color:#191600; }
.au-naver{ background:#03C75A; color:#fff; }
.au-google{ background:#fff; color:#333; border-color:#e3e3e6; }
.au-social .ic{ width:18px; height:18px; display:grid; place-items:center; font-weight:800; }

.au-demo{ text-align:center; font-size:12px; color:#bbb; margin-top:18px; }
</style>

<div class="au-wrap">
  <div class="au-logo">KPOP<b>POCA</b><span class="star">✦</span></div>

  <div class="au-card">
    <div class="au-tabs">
      <a href="/auth.php?tab=login" class="<?= $tab==='login'?'on':'' ?>">로그인</a>
      <a href="/auth.php?tab=join"  class="<?= $tab==='join'?'on':'' ?>">회원가입</a>
    </div>

    <?php if ($err !== ''): ?><div class="au-err"><?= e($err) ?></div><?php endif; ?>

    <?php if ($tab === 'login'): ?>
      <form method="post" action="/auth.php?tab=login">
        <input type="hidden" name="action" value="login">
        <input type="hidden" name="next" value="<?= e($next) ?>">
        <div class="au-field"><label>이메일</label><input class="au-input" type="email" name="email" value="<?= e($old_email) ?>" placeholder="example@kpoppoca.kr" required></div>
        <div class="au-field"><label>비밀번호</label><input class="au-input" type="password" name="password" placeholder="비밀번호를 입력하세요" required></div>
        <div class="au-row">
          <label><input type="checkbox" name="remember"> 로그인 상태 유지</label>
          <a href="#">비밀번호 찾기</a>
        </div>
        <button type="submit" class="au-submit">로그인</button>
        <div class="au-switch">아직 회원이 아니세요?<a href="/auth.php?tab=join">회원가입</a></div>
      </form>

    <?php else: ?>
      <form method="post" action="/auth.php?tab=join">
        <input type="hidden" name="action" value="join">
        <input type="hidden" name="next" value="<?= e($next) ?>">
        <div class="au-field"><label>이메일</label><input class="au-input" type="email" name="email" value="<?= e($old_email) ?>" placeholder="example@kpoppoca.kr" required></div>
        <div class="au-field"><label>비밀번호</label><input class="au-input" type="password" name="password" placeholder="8자 이상, 영문·숫자 조합" required></div>
        <div class="au-field"><label>비밀번호 확인</label><input class="au-input" type="password" name="password2" placeholder="비밀번호를 다시 입력하세요" required></div>
        <div class="au-field"><label>이름</label><input class="au-input" type="text" name="name" placeholder="홍길동" required></div>
        <div class="au-field"><label>휴대폰</label><input class="au-input" type="tel" name="phone" placeholder="010-1234-5678"></div>
        <div class="au-agree">
          <label><input type="checkbox" name="agree"> 전체 동의 <span style="color:#aaa;font-weight:500">(선택 정보 포함)</span></label>
          <a href="/support.php?tab=terms">보기</a>
        </div>
        <button type="submit" class="au-submit">회원가입</button>
        <div class="au-switch">이미 계정이 있으세요?<a href="/auth.php?tab=login">로그인</a></div>
      </form>
    <?php endif; ?>

    <div class="au-or">또는 간편 <?= $word ?></div>
    <div class="au-socials">
      <a class="au-social au-kakao" href="/oauth/start.php?provider=kakao&tab=<?= e($tab) ?>&return_to=<?= e(rawurlencode($next)) ?>"><span class="ic">💬</span> 카카오로 <?= $word ?></a>
      <a class="au-social au-naver" href="/oauth/start.php?provider=naver&tab=<?= e($tab) ?>&return_to=<?= e(rawurlencode($next)) ?>"><span class="ic">N</span> 네이버로 <?= $word ?></a>
      <a class="au-social au-google" href="/oauth/start.php?provider=google&tab=<?= e($tab) ?>&return_to=<?= e(rawurlencode($next)) ?>"><span class="ic">G</span> 구글로 <?= $word ?></a>
    </div>

    <div class="au-demo">처음 이용하는 소셜 계정은 자동으로 회원가입 처리돼요.</div>
  </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
