<?php
// pages/my_profile.php — 내 정보 변경
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/header.php';

$db = (new Database())->getConnection();
$user = currentUser();
$msg = '';
$err = '';
$isSysadmin = in_array(($_SESSION['user_role'] ?? ''), ['sysadmin']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // 프로필 이미지 업로드
    if ($action === 'upload_profile' && isset($_FILES['profile_photo']) && $_FILES['profile_photo']['size'] > 0) {
        $pf = $_FILES['profile_photo'];
        $ext = strtolower(pathinfo($pf['name'], PATHINFO_EXTENSION));
        if ($pf['size'] > 3*1024*1024) {
            $err = '프로필 이미지는 3MB 이하만 가능합니다.';
        } elseif (!in_array($ext, ['jpg','jpeg','png','gif'])) {
            $err = 'JPG, PNG, GIF 형식만 지원합니다.';
        } else {
            $dir = __DIR__ . '/../assets/theme/' . $user['user_id'] . '/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            foreach (glob($dir . 'profile.*') as $old) @unlink($old);
            $dest = $dir . 'profile.' . $ext;
            if (move_uploaded_file($pf['tmp_name'], $dest)) {
                $msg = '프로필 이미지가 변경되었습니다.';
            } else { $err = '업로드 실패'; }
        }
    }

    // 비밀번호 변경
    if ($action === 'change_pw') {
        $cur  = $_POST['current_pw'] ?? '';
        $new  = $_POST['new_pw'] ?? '';
        $new2 = $_POST['new_pw2'] ?? '';

        $s = $db->prepare("SELECT password_hash FROM user_account WHERE user_id = ?");
        $s->execute([$user['user_id']]);
        $hash = $s->fetchColumn();

        if (!password_verify($cur, $hash)) {
            $err = '현재 비밀번호가 일치하지 않습니다.';
        } elseif (strlen($new) < 6) {
            $err = '새 비밀번호는 6자 이상이어야 합니다.';
        } elseif ($new !== $new2) {
            $err = '새 비밀번호가 일치하지 않습니다.';
        } elseif ($cur === $new) {
            $err = '현재와 동일한 비밀번호로 변경할 수 없습니다.';
        } else {
            $newHash = password_hash($new, PASSWORD_DEFAULT);
            $db->prepare("UPDATE user_account SET password_hash = ?, must_change_pw = 0, pw_changed_at = NOW() WHERE user_id = ?")
               ->execute([$newHash, $user['user_id']]);
            $_SESSION['must_change_pw'] = 0;
            writeAudit($db, 'user_account', $user['user_id'], 'UPDATE', ['action' => '비밀번호 변경']);
            $msg = '비밀번호가 변경되었습니다.';
        }
    }

    // 연락처/기본정보 수정
    if ($action === 'update_info') {
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');

        if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $err = '올바른 이메일 형식이 아닙니다.';
        } else {
            $updates = ['email' => $email ?: '미기재', 'phone' => $phone];

            // 시스템관리자: 이름, 아이디도 수정 가능
            if ($isSysadmin) {
                $newName = trim($_POST['name'] ?? '');
                $newLoginId = trim($_POST['login_id'] ?? '');
                if ($newName) {
                    $db->prepare("UPDATE staff SET name=? WHERE staff_id=?")->execute([$newName, $user['staff_id']]);
                    $updates['name'] = $newName;
                }
                if ($newLoginId) {
                    // 중복 체크
                    $dup = $db->prepare("SELECT COUNT(*) FROM user_account WHERE login_id=? AND user_id!=?");
                    $dup->execute([$newLoginId, $user['user_id']]);
                    if ($dup->fetchColumn() > 0) {
                        $err = '이미 사용 중인 아이디입니다.';
                    } else {
                        $db->prepare("UPDATE user_account SET login_id=? WHERE user_id=?")->execute([$newLoginId, $user['user_id']]);
                        $updates['login_id'] = $newLoginId;
                    }
                }
            }

            if (!$err) {
                $db->prepare("UPDATE staff SET email = ?, phone = ? WHERE staff_id = ?")
                   ->execute([$email ?: '미기재', $phone, $user['staff_id']]);
                writeAudit($db, 'staff', $user['staff_id'], 'UPDATE', $updates);
                $msg = '정보가 저장되었습니다.';
            }
        }
    }

    // 계정 상세 수정 (시스템관리자 전용)
    if ($action === 'update_account_detail' && $isSysadmin) {
        $grade = trim($_POST['grade'] ?? '');
        $role = trim($_POST['role'] ?? '');
        $team = trim($_POST['team'] ?? '');
        $hireDate = trim($_POST['hire_date'] ?? '');

        if ($grade && $team) {
            $db->prepare("UPDATE staff SET grade=?, team=?, role=?, hire_date=? WHERE staff_id=?")
               ->execute([$grade, $team, $role ?: '시스템관리자', $hireDate ?: null, $user['staff_id']]);
            $newUserRole = trim($_POST['user_role'] ?? '');
            if ($newUserRole) {
                $db->prepare("UPDATE user_account SET user_role=? WHERE user_id=?")->execute([$newUserRole, $user['user_id']]);
                $_SESSION['user_role'] = $newUserRole;
            }
            writeAudit($db, 'staff', $user['staff_id'], 'UPDATE', ['grade'=>$grade,'team'=>$team,'role'=>$role,'user_role'=>$newUserRole,'hire_date'=>$hireDate]);
            $msg = '계정 상세 정보가 저장되었습니다.';
        } else {
            $err = '직급과 소속 팀은 필수 항목입니다.';
        }
    }
}

// 내 정보 조회
$stmt = $db->prepare("
    SELECT s.*, u.login_id, u.user_role, u.last_login, u.pw_changed_at, u.created_at AS account_created
    FROM staff s
    JOIN user_account u ON s.staff_id = u.staff_id
    WHERE u.user_id = ?
");
$stmt->execute([$user['user_id']]);
$myInfo = $stmt->fetch();
?>

<div class="page-header"><h2>👤 내 정보 변경</h2></div>

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

<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">

<!-- 프로필 이미지 -->
<div class="card" style="grid-column:1/3;">
    <div class="card-header"><h3>📷 프로필 이미지</h3></div>
    <div style="display:flex;align-items:center;gap:1.5rem;padding:0.5rem 0;">
        <?php
        $profileDir = __DIR__ . '/../assets/theme/' . $user['user_id'] . '/';
        $profileFiles = glob($profileDir . 'profile.*');
        $profileUrl = $profileFiles ? BASE_URL.'assets/theme/' . $user['user_id'] . '/' . basename($profileFiles[0]) : BASE_URL.'assets/empty.png';
        ?>
        <img src="<?= $profileUrl ?>?t=<?= time() ?>" alt="프로필" style="width:6rem;height:6rem;border-radius:50%;object-fit:cover;border:3px solid var(--border);">
        <div>
            <form method="POST" enctype="multipart/form-data" style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
                <input type="hidden" name="action" value="upload_profile">
                <label class="btn btn-outline" style="cursor:pointer;font-size:var(--fs-xs);padding:0.375rem 1rem;">
                    📷 이미지 선택
                    <input type="file" name="profile_photo" accept="image/jpeg,image/png,image/gif" style="display:none;" onchange="document.getElementById('pfName').textContent=this.files[0]?.name||''">
                </label>
                <span id="pfName" style="font-size:var(--fs-xs);color:var(--text-tertiary);"></span>
                <button type="submit" class="btn btn-primary" style="font-size:var(--fs-xs);padding:0.375rem 1rem;">업로드</button>
            </form>
            <p style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-top:0.5rem;">JPG, PNG, GIF · 3MB 이하 · GIF는 움직이는 이미지 지원</p>
        </div>
    </div>
</div>

<!-- 비밀번호 변경 -->
<div class="card">
    <div class="card-header"><h3>🔒 비밀번호 변경</h3></div>
    <form method="POST">
        <input type="hidden" name="action" value="change_pw">
        <div class="form-group">
            <label>현재 비밀번호 <span class="required">*</span></label>
            <input type="password" name="current_pw" required>
        </div>
        <div class="form-group">
            <label>새 비밀번호 <span class="required">*</span></label>
            <input type="password" name="new_pw" required minlength="6" placeholder="6자 이상">
        </div>
        <div class="form-group">
            <label>새 비밀번호 확인 <span class="required">*</span></label>
            <input type="password" name="new_pw2" required>
        </div>
        <button type="submit" class="btn btn-primary">비밀번호 변경</button>
    </form>
    <div class="alert alert-info" style="margin-top:12px;font-size:var(--fs-xs);">
        비밀번호는 암호화(bcrypt) 저장되어 시스템 관리자도 확인할 수 없습니다.
        분실 시 시스템 관리자에게 임시 비밀번호 발급을 요청하세요.
    </div>
</div>

<!-- 기본 정보 수정 -->
<div class="card">
    <div class="card-header"><h3>📞 기본 정보 수정</h3></div>
    <form method="POST">
        <input type="hidden" name="action" value="update_info">
        <div class="form-group">
            <label>아이디<?php if($isSysadmin): ?> <span class="required">*</span><?php endif; ?></label>
            <?php if ($isSysadmin): ?>
            <input type="text" name="login_id" value="<?= htmlspecialchars($myInfo['login_id']) ?>" required>
            <?php else: ?>
            <input type="text" value="<?= htmlspecialchars($myInfo['login_id']) ?>" disabled>
            <?php endif; ?>
        </div>
        <div class="form-group">
            <label>이름<?php if($isSysadmin): ?> <span class="required">*</span><?php endif; ?></label>
            <?php if ($isSysadmin): ?>
            <input type="text" name="name" value="<?= htmlspecialchars($myInfo['name']) ?>" required>
            <?php else: ?>
            <input type="text" value="<?= htmlspecialchars($myInfo['name']) ?>" disabled>
            <small style="color:var(--text-tertiary);">이름 변경은 시스템 관리자에게 요청하세요.</small>
            <?php endif; ?>
        </div>
        <div class="form-group">
            <label>이메일</label>
            <input type="email" name="email" value="<?= htmlspecialchars($myInfo['email'] !== '미기재' ? $myInfo['email'] : '') ?>" placeholder="email@company.com">
        </div>
        <div class="form-group">
            <label>연락처</label>
            <input type="tel" name="phone" value="<?= htmlspecialchars($myInfo['phone'] ?? '') ?>" placeholder="010-0000-0000">
        </div>
        <button type="submit" class="btn btn-primary">정보 저장</button>
    </form>
</div>

</div>

<!-- 계정 상세 정보 -->
<div class="card" style="margin-top:20px;">
    <div class="card-header"><h3>📌 계정 상세</h3></div>
    <?php
    // 팀/직급 마스터
    $teamList = $db->query("SELECT team_name FROM team_master WHERE is_active=1 ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);
    $gradeList = $db->query("SELECT grade_name FROM grade_master WHERE is_active=1 ORDER BY sort_order")->fetchAll(PDO::FETCH_COLUMN);
    if (!$teamList) $teamList = [];
    if (!$gradeList) $gradeList = [];
    $roleOptions = ['직원','팀장','관리자','대표','시스템관리자'];
    $userRoleMap = ['staff'=>'직원','team_leader'=>'팀장','manager'=>'관리자','ceo'=>'대표','sysadmin'=>'시스템관리자'];
    $userRoleKeys = ['staff','team_leader','manager','ceo','sysadmin'];
    ?>
    <?php if ($isSysadmin): ?>
    <form method="POST">
        <input type="hidden" name="action" value="update_account_detail">
        <div class="table-wrap">
            <table>
                <tr>
                    <td style="width:120px;font-weight:600;">직급</td>
                    <td>
                        <select name="grade" style="padding:0.35rem 0.5rem;border:1px solid var(--form-line-color);background:var(--card-bg-color);color:var(--text-primary);border-radius:var(--radius-sm);font-size:var(--fs-sm);">
                            <?php foreach ($gradeList as $g): ?>
                            <option value="<?= htmlspecialchars($g) ?>" <?= $g===$myInfo['grade']?'selected':'' ?>><?= htmlspecialchars($g) ?></option>
                            <?php endforeach; ?>
                            <?php if (!in_array($myInfo['grade'], $gradeList)): ?>
                            <option value="<?= htmlspecialchars($myInfo['grade']) ?>" selected><?= htmlspecialchars($myInfo['grade']) ?></option>
                            <?php endif; ?>
                        </select>
                    </td>
                    <td style="width:120px;font-weight:600;">역할 (시스템)</td>
                    <td>
                        <select name="user_role" style="padding:0.35rem 0.5rem;border:1px solid var(--form-line-color);background:var(--card-bg-color);color:var(--text-primary);border-radius:var(--radius-sm);font-size:var(--fs-sm);">
                            <?php foreach ($userRoleKeys as $rk): ?>
                            <option value="<?= $rk ?>" <?= $rk===$myInfo['user_role']?'selected':'' ?>><?= $userRoleMap[$rk] ?? $rk ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td style="font-weight:600;">역할 (직책)</td>
                    <td>
                        <select name="role" style="padding:0.35rem 0.5rem;border:1px solid var(--form-line-color);background:var(--card-bg-color);color:var(--text-primary);border-radius:var(--radius-sm);font-size:var(--fs-sm);">
                            <?php foreach ($roleOptions as $ro): ?>
                            <option value="<?= $ro ?>" <?= $ro===$myInfo['role']?'selected':'' ?>><?= $ro ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td style="font-weight:600;">소속 팀</td>
                    <td>
                        <select name="team" style="padding:0.35rem 0.5rem;border:1px solid var(--form-line-color);background:var(--card-bg-color);color:var(--text-primary);border-radius:var(--radius-sm);font-size:var(--fs-sm);">
                            <?php foreach ($teamList as $t): ?>
                            <option value="<?= htmlspecialchars($t) ?>" <?= $t===$myInfo['team']?'selected':'' ?>><?= htmlspecialchars($t) ?></option>
                            <?php endforeach; ?>
                            <?php if (!in_array($myInfo['team'], $teamList)): ?>
                            <option value="<?= htmlspecialchars($myInfo['team']) ?>" selected><?= htmlspecialchars($myInfo['team']) ?></option>
                            <?php endif; ?>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td style="font-weight:600;">입사일</td>
                    <td>
                        <input type="date" name="hire_date" value="<?= $myInfo['hire_date'] ?? '' ?>" style="padding:0.35rem 0.5rem;border:1px solid var(--form-line-color);background:var(--card-bg-color);color:var(--text-primary);border-radius:var(--radius-sm);font-size:var(--fs-sm);">
                    </td>
                    <td style="font-weight:600;">PW 변경일</td>
                    <td><?= $myInfo['pw_changed_at'] ? date('Y-m-d H:i', strtotime($myInfo['pw_changed_at'])) : '변경 이력 없음' ?></td>
                </tr>
                <tr>
                    <td style="font-weight:600;">계정 생성일</td>
                    <td><?= $myInfo['account_created'] ? date('Y-m-d H:i', strtotime($myInfo['account_created'])) : '-' ?></td>
                    <td style="font-weight:600;">최종 로그인</td>
                    <td><?= $myInfo['last_login'] ? date('Y-m-d H:i', strtotime($myInfo['last_login'])) : '-' ?></td>
                </tr>
            </table>
        </div>
        <div style="margin-top:0.75rem;">
            <button type="submit" class="btn btn-primary" style="font-size:var(--fs-sm);">계정 상세 저장</button>
        </div>
    </form>
    <?php else: ?>
    <div class="table-wrap">
        <table>
            <tr>
                <td style="width:120px;font-weight:600;">직급</td>
                <td><span class="badge badge-info"><?= $myInfo['grade'] ?></span></td>
                <td style="width:120px;font-weight:600;">역할</td>
                <td><span class="badge <?= getRoleBadgeClass($myInfo['user_role']) ?>"><?= getRoleLabel($myInfo['user_role']) ?></span></td>
            </tr>
            <tr>
                <td style="font-weight:600;">소속 팀</td>
                <td><?= htmlspecialchars($myInfo['team']) ?></td>
                <td style="font-weight:600;">입사일</td>
                <td><?= $myInfo['hire_date'] ?></td>
            </tr>
            <tr>
                <td style="font-weight:600;">최종 로그인</td>
                <td><?= $myInfo['last_login'] ? date('Y-m-d H:i', strtotime($myInfo['last_login'])) : '-' ?></td>
                <td style="font-weight:600;">PW 변경일</td>
                <td><?= $myInfo['pw_changed_at'] ? date('Y-m-d H:i', strtotime($myInfo['pw_changed_at'])) : '변경 이력 없음' ?></td>
            </tr>
        </table>
    </div>
    <div class="alert alert-info" style="margin-top:12px;font-size:var(--fs-xs);">
        직급, 역할, 소속 팀 변경은 시스템 관리자에게 문의하세요.
    </div>
    <?php endif; ?>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
