<?php
// register.php — 회원가입 (시스템관리자 승인 필요)
$_base = '/' . trim(str_replace(str_replace('\\','/',$_SERVER['DOCUMENT_ROOT']??''), '', str_replace('\\','/',__DIR__)), '/') . '/';
if (!defined('BASE_URL')) define('BASE_URL', $_base);
if (!file_exists(__DIR__ . '/config/database.php')) { header('Location: '.$_base.'setup.php'); exit; }
require_once __DIR__ . '/config/database.php';
if (session_status() === PHP_SESSION_NONE) session_start();

$db = (new Database())->getConnection();
$error = '';

// 팀/직급 마스터 테이블 연동
$db->exec("CREATE TABLE IF NOT EXISTS team_master (team_id INT AUTO_INCREMENT PRIMARY KEY, team_name VARCHAR(50) NOT NULL UNIQUE, description VARCHAR(200) DEFAULT '', leader_staff_id INT DEFAULT NULL, is_active TINYINT(1) DEFAULT 1, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)");
$db->exec("CREATE TABLE IF NOT EXISTS grade_master (grade_id INT AUTO_INCREMENT PRIMARY KEY, grade_name VARCHAR(30) NOT NULL UNIQUE, sort_order INT DEFAULT 0, is_active TINYINT(1) DEFAULT 1, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)");
$teams = $db->query("SELECT team_name FROM team_master WHERE is_active=1 ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);
$grades = $db->query("SELECT grade_name FROM grade_master WHERE is_active=1 ORDER BY sort_order")->fetchAll(PDO::FETCH_COLUMN);
// 팀/직급이 없으면 team_master/grade_master에서 직접 등록 필요 (하드코딩 폴백 제거)
if (!$grades) $grades = ['사원','선임','책임','수석'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name     = trim($_POST['name'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $phone    = trim($_POST['phone'] ?? '');
    $grade    = $_POST['grade'] ?? '사원';
    $team     = $_POST['team'] ?? '';
    $hire_date = $_POST['hire_date'] ?? null;
    $login_id = trim($_POST['login_id'] ?? '');
    $password = $_POST['password'] ?? '';
    $password2 = $_POST['password2'] ?? '';

    // 유효성 검사
    if (!$name || !$email || !$login_id || !$password || !$team) {
        $error = '필수 항목을 모두 입력해주세요.';
    } elseif (strlen($login_id) < 3) {
        $error = '아이디는 3자 이상이어야 합니다.';
    } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $login_id)) {
        $error = '아이디는 영문, 숫자, 밑줄(_)만 사용 가능합니다.';
    } elseif (strlen($password) < 6) {
        $error = '비밀번호는 6자 이상이어야 합니다.';
    } elseif ($password !== $password2) {
        $error = '비밀번호가 일치하지 않습니다.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = '올바른 이메일 형식이 아닙니다.';
    } else {
        // 중복 체크
        $chk = $db->prepare("SELECT COUNT(*) FROM user_account WHERE login_id = ?");
        $chk->execute([$login_id]);
        if ($chk->fetchColumn() > 0) {
            $error = '이미 사용 중인 아이디입니다.';
        }
        // 로그인 아이디 중복 체크 (이름 중복은 허용)
        if (!$error) {
            $chk = $db->prepare("SELECT COUNT(*) FROM user_account WHERE login_id = ?");
            $chk->execute([$login_id]);
            if ($chk->fetchColumn() > 0) {
                $error = '이미 사용 중인 아이디입니다. 다른 아이디를 입력하세요.';
            }
        }
    }

    if (!$error) {
        try {
            $db->beginTransaction();

            // staff 레코드 생성 (is_active=0, 승인 대기) — 이름 중복 허용
            $stmt = $db->prepare("INSERT INTO staff (name, email, phone, grade, team, role, hire_date, is_active, memo)
                VALUES (?,?,?,?,?, '직원', ?, 0, '가입 승인 대기')");
            $stmt->execute([$name, $email, $phone, $grade, $team, $hire_date]);
            $staffId = $db->lastInsertId();

            // user_account 생성 (approval_status=대기, is_active=0)
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $db->prepare("INSERT INTO user_account (staff_id, login_id, password_hash, user_role, is_active, approval_status)
                VALUES (?,?,?, 'staff', 0, '대기')");
            $stmt->execute([$staffId, $login_id, $hash]);

            $db->commit();

            // 시스템관리자/대표에게 가입 승인 알림 전송
            try {
                $db2 = (new Database())->getConnection();
                $db2->exec("CREATE TABLE IF NOT EXISTS notifications (
                    noti_id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL,
                    message VARCHAR(300), link VARCHAR(200) DEFAULT '', is_read TINYINT(1) DEFAULT 0,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP, INDEX idx_user_read(user_id, is_read)
                )");
                $admins = $db2->query("SELECT user_id FROM user_account WHERE user_role IN ('sysadmin','ceo') AND is_active=1")->fetchAll(PDO::FETCH_COLUMN);
                $notiMsg = '📋 새 가입 승인 요청: ' . $name . ' (' . $grade . ' / ' . $team . ')';
                $notiLink = BASE_URL . 'pages/admin_accounts.php';
                foreach ($admins as $adminUid) {
                    $db2->prepare("INSERT INTO notifications (user_id, message, link) VALUES(?,?,?)")
                        ->execute([$adminUid, $notiMsg, $notiLink]);
                }
            } catch(Exception $e2) {}

            header('Location: '.BASE_URL.'index.php?msg=registered');
            exit;
        } catch (PDOException $e) {
            $db->rollBack();
            $error = '등록 중 오류가 발생했습니다.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>회원가입 — AP MEDIA ONE</title>
    <?php
    $faviconFiles = glob(__DIR__ . '/assets/favicon.*');
    foreach ($faviconFiles as $ff) {
        $fext = strtolower(pathinfo($ff, PATHINFO_EXTENSION));
        if (in_array($fext, ['png','ico'])) {
            $ftype = $fext === 'ico' ? 'image/x-icon' : 'image/png';
            echo '<link rel="icon" type="'.$ftype.'" href="'.BASE_URL.'assets/'.basename($ff).'?v='.filemtime($ff).'">';
            break;
        }
    }
    ?>
    <link rel="stylesheet" href="<?=BASE_URL?>assets/css/style.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;600;700;800&display=swap" rel="stylesheet">
</head>
<body>
<div class="login-page">
    <div class="login-card" style="max-width:520px;">
        <h1>📝 회원가입 신청</h1>
        <p class="subtitle">시스템 관리자 승인 후 로그인이 가능합니다</p>

        <?php if ($error): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <form method="POST">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                <div class="form-group">
                    <label>이름 <span class="required">*</span></label>
                    <input type="text" name="name" required value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" placeholder="홍길동">
                </div>
                <div class="form-group">
                    <label>이메일 <span class="required">*</span></label>
                    <input type="email" name="email" required value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" placeholder="email@company.com">
                </div>
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                <div class="form-group">
                    <label>연락처</label>
                    <input type="text" name="phone" value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>" placeholder="010-0000-0000">
                </div>
                <div class="form-group">
                    <label>입사일</label>
                    <input type="date" name="hire_date" value="<?= htmlspecialchars($_POST['hire_date'] ?? '') ?>" style="color-scheme:dark;">
                </div>
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                <div class="form-group">
                    <label>직급 <span class="required">*</span></label>
                    <select name="grade" required>
                        <?php foreach ($grades as $g): ?>
                            <option value="<?= $g ?>" <?= ($_POST['grade'] ?? '') === $g ? 'selected' : '' ?>><?= $g ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>소속팀 <span class="required">*</span></label>
                    <select name="team" required>
                        <option value="">선택</option>
                        <?php if ($teams): ?>
                        <?php foreach ($teams as $t): ?>
                            <option value="<?= htmlspecialchars($t) ?>" <?= ($_POST['team'] ?? '') === $t ? 'selected' : '' ?>><?= htmlspecialchars($t) ?></option>
                        <?php endforeach; ?>
                        <?php else: ?>
                            <option value="" disabled>등록된 팀이 없습니다 (관리자에게 문의)</option>
                        <?php endif; ?>
                    </select>
                </div>
            </div>

            <hr style="margin:16px 0;border-color:rgba(255,255,255,0.08);">

            <div class="form-group">
                <label>아이디 <span class="required">*</span></label>
                <input type="text" name="login_id" required minlength="3" pattern="[a-zA-Z0-9_]+"
                       value="<?= htmlspecialchars($_POST['login_id'] ?? '') ?>" placeholder="영문/숫자/밑줄, 3자 이상">
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                <div class="form-group">
                    <label>비밀번호 <span class="required">*</span></label>
                    <input type="password" name="password" required minlength="6" placeholder="6자 이상">
                </div>
                <div class="form-group">
                    <label>비밀번호 확인 <span class="required">*</span></label>
                    <input type="password" name="password2" required minlength="6" placeholder="비밀번호 재입력">
                </div>
            </div>

            <div class="alert alert-info" style="margin-top:8px;">
                ℹ 비밀번호는 암호화되어 저장되며, 시스템 관리자도 확인할 수 없습니다.
            </div>

            <button type="submit" class="btn btn-primary" style="width:100%;margin-top:8px;">회원가입 신청</button>
        </form>

        <div style="text-align:center;margin-top:16px;">
            <a href="<?=BASE_URL?>index.php" style="font-size:13px;color:var(--text-tertiary);">← 로그인으로 돌아가기</a>
        </div>
    </div>
</div>
</body>
</html>
