<?php include "includes/init.php"; ?>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $userid = trim($_POST['userid']);
    $email = trim($_POST['email']);
    
    // 입력 유효성 검사
    if (empty($userid)) {
        $error[] = "사용자 ID를 입력해주세요.";
    }
    
    if (empty($email)) {
        $error[] = "이메일 주소를 입력해주세요.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error[] = "올바른 이메일 주소를 입력해주세요.";
    }
    
    if (!isset($error)) {
        // 사용자 ID와 이메일이 일치하는지 확인
        try {
            $sql = "SELECT * FROM users WHERE userid = :userid AND email = :email";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':userid' => $userid, ':email' => $email]);
            $row = $stmt->fetch();
            
            if ($row) {
                // 새로운 검증 코드 생성
                $validation_code = bin2hex(random_bytes(32));
                
                // 검증 코드를 데이터베이스에 업데이트
                $update_sql = "UPDATE users SET validationcode = :validationcode WHERE id = :id";
                $update_stmt = $pdo->prepare($update_sql);
                $update_stmt->execute([
                    ':validationcode' => $validation_code,
                    ':id' => $row['id']
                ]);
                
                // 이메일 본문 생성
                $resetLink = "https://{$_SERVER['HTTP_HOST']}/GIS/reset_2.php?user=" . urlencode($userid) . "&code=" . urlencode($validation_code);
                $body = <<<EOD
                <html>
                <head>
                    <title>비밀번호 재설정</title>
                    <style>
                        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                        .header { background-color: #4CAF50; color: white; text-align: center; padding: 20px; border-radius: 5px 5px 0 0; }
                        .content { background-color: #f9f9f9; padding: 30px; border-radius: 0 0 5px 5px; }
                        .button { background-color: #4CAF50; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 20px 0; }
                        .footer { text-align: center; margin-top: 30px; color: #666; }
                        .warning { background-color: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin: 20px 0; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <div class="header">
                            <h1>WKY_GIS 비밀번호 재설정</h1>
                        </div>
                        <div class="content">
                            <p>안녕하세요, <strong>{$row['username']}</strong>님!</p>
                            <p>WKY_GIS 계정의 비밀번호 재설정을 요청하셨습니다.</p>
                            <p>아래 버튼을 클릭하여 새 비밀번호를 설정하세요:</p>
                            
                            <div style="text-align: center;">
                                <a href="{$resetLink}" class="button">비밀번호 재설정</a>
                            </div>
                            
                            <div class="warning">
                                <strong>보안 안내:</strong><br>
                                • 이 링크는 24시간 후 만료됩니다.<br>
                                • 본인이 요청하지 않은 경우 이 이메일을 무시하세요.<br>
                                • 링크를 다른 사람과 공유하지 마세요.
                            </div>
                            
                            <p>버튼이 작동하지 않는 경우, 아래 링크를 복사하여 웹 브라우저에 붙여넣으세요:</p>
                            <p style="word-break: break-all; background-color: #f0f0f0; padding: 10px; border-radius: 3px;">
                                <a href="{$resetLink}">{$resetLink}</a>
                            </p>
                        </div>
                        <div class="footer">
                            <p>감사합니다.<br>WKY_GIS 운영팀</p>
                        </div>
                    </div>
                </body>
                </html>
                EOD;
                
                // 기존 프로젝트의 send_mail 함수 사용
                $mail_subject = '[WKY_GIS] 비밀번호 재설정 요청';
                $mail_result = send_mail($row['email'], $mail_subject, $body, $from_email, $reply_email);
                
                if ($mail_result) {
                    set_msg("비밀번호 재설정 링크가 '{$row['email']}'로 발송되었습니다. 이메일을 확인해주세요.", 'success');
                    $success = true;
                } else {
                    $error[] = '이메일 발송에 실패했습니다. 잠시 후 다시 시도해주세요.';
                }
            } else {
                $error[] = "입력하신 사용자 ID와 이메일이 일치하지 않습니다.";
            }
        } catch (PDOException $e) {
            $error[] = "데이터베이스 오류가 발생했습니다. 관리자에게 문의하세요.";
            error_log("Reset password database error: " . $e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ko">
<?php include "includes/header.php" ?>
<head>
    <style>
        .reset-container {
            max-width: 500px;
            margin: 50px auto;
            padding: 0 15px;
        }
        
        .reset-panel {
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .reset-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .reset-header h2 {
            margin: 0;
            font-size: 24px;
            font-weight: 300;
        }
        
        .reset-header .icon {
            font-size: 48px;
            margin-bottom: 15px;
        }
        
        .reset-body {
            padding: 40px;
        }
        
        .form-group {
            margin-bottom: 25px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }
        
        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e1e1;
            border-radius: 6px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .btn-reset {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s ease;
        }
        
        .btn-reset:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .btn-reset:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .alert {
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
        }
        
        .alert-danger {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .alert-success {
            background-color: #d1f2dd;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        
        .back-link {
            text-align: center;
            margin-top: 30px;
        }
        
        .back-link a {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
        }
        
        .back-link a:hover {
            text-decoration: underline;
        }
        
        .info-box {
            background-color: #e7f3ff;
            border: 1px solid #b3d9ff;
            color: #004085;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 25px;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .system-info {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            color: #495057;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 20px;
            font-size: 12px;
        }
    </style>
</head>

<body>
    <?php include "includes/nav.php" ?>
    
    <div class="reset-container">
        <div class="reset-panel">
            <div class="reset-header">
                <div class="icon">🔒</div>
                <h2>비밀번호 재설정</h2>
                <p style="margin: 10px 0 0 0; opacity: 0.9;">계정 정보를 입력하시면 재설정 링크를 이메일로 보내드립니다</p>
            </div>
            
            <div class="reset-body">
                <?php
                // 에러 메시지 표시
                if (isset($error) && is_array($error)) {
                    foreach ($error as $msg) {
                        echo "<div class='alert alert-danger'><strong>오류:</strong> {$msg}</div>";
                    }
                }
                
                // 성공 메시지 표시
                show_msg();
                
                if (!isset($success)):
                ?>
                
                <div class="info-box">
                    <strong>안내사항:</strong><br>
                    • 가입 시 등록한 사용자 ID와 이메일 주소를 정확히 입력해주세요.<br>
                    • 재설정 링크는 24시간 동안 유효합니다.<br>
                    • 스팸 폴더도 확인해보세요.
                </div>
                
                <?php if ($_SERVER['SERVER_NAME'] == "localhost"): ?>
                <div class="system-info">
                    <strong>개발 환경 안내:</strong> localhost 환경에서는 실제 이메일이 발송되지 않고 화면에 내용이 표시됩니다.
                </div>
                <?php endif; ?>
                
                <form id="reset-form" method="post" role="form">
                    <div class="form-group">
                        <label for="userid">사용자 ID</label>
                        <input type="text" name="userid" id="userid" class="form-control" 
                               placeholder="가입 시 사용한 사용자 ID를 입력하세요" 
                               value="<?php echo isset($_POST['userid']) ? htmlspecialchars($_POST['userid']) : ''; ?>" 
                               required autocomplete="username">
                    </div>
                    
                    <div class="form-group">
                        <label for="email">이메일 주소</label>
                        <input type="email" name="email" id="email" class="form-control" 
                               placeholder="가입 시 등록한 이메일 주소를 입력하세요" 
                               value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" 
                               required autocomplete="email">
                    </div>
                    
                    <div class="form-group">
                        <button type="submit" id="submit-btn" class="btn-reset">
                            재설정 링크 발송
                        </button>
                    </div>
                </form>
                
                <div class="loading" id="loading">
                    <div class="spinner"></div>
                    <p>이메일을 발송하고 있습니다. 잠시만 기다려주세요...</p>
                </div>
                
                <?php else: ?>
                
                <div class="alert alert-success">
                    <strong>✅ 발송 완료!</strong><br>
                    이메일을 확인하시고 재설정 링크를 클릭해주세요.<br>
                    이메일이 도착하지 않은 경우 스팸 폴더를 확인해보세요.
                </div>
                
                <?php endif; ?>
                
                <div class="back-link">
                    <a href="index.php">← 로그인 페이지로 돌아가기</a>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('reset-form');
            const submitBtn = document.getElementById('submit-btn');
            const loading = document.getElementById('loading');
            
            if (form) {
                form.addEventListener('submit', function(e) {
                    // 기본 유효성 검사
                    const userid = document.getElementById('userid').value.trim();
                    const email = document.getElementById('email').value.trim();
                    
                    if (!userid) {
                        alert('사용자 ID를 입력해주세요.');
                        e.preventDefault();
                        return false;
                    }
                    
                    if (!email) {
                        alert('이메일 주소를 입력해주세요.');
                        e.preventDefault();
                        return false;
                    }
                    
                    // 이메일 형식 검증
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(email)) {
                        alert('올바른 이메일 주소를 입력해주세요.');
                        e.preventDefault();
                        return false;
                    }
                    
                    // 로딩 UI 표시
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '발송 중...';
                    loading.style.display = 'block';
                });
            }
            
            // 입력 필드 실시간 유효성 검사
            const useridInput = document.getElementById('userid');
            const emailInput = document.getElementById('email');
            
            if (useridInput) {
                useridInput.addEventListener('input', function() {
                    this.value = this.value.trim();
                });
            }
            
            if (emailInput) {
                emailInput.addEventListener('input', function() {
                    this.value = this.value.trim().toLowerCase();
                });
            }
        });
    </script>
    
    <?php include "includes/footer.php" ?>
</body>
</html>
