<?php
/**
 * 국민자료실 - 문의하기
 */
require_once __DIR__ . '/bootstrap.php';
require_once BASE_DIR . '/includes/functions.php';
require_once BASE_DIR . '/includes/security.php';

$currentPage = 'contact';
logPageView('contact');
$pageTitle = '문의하기';
$pageDescription = '국민자료실에 대한 의견, 오류 신고, 정책 정보 정정 요청 등을 보내주세요.';

$submitted = false;
$error = '';

// 문의 폼 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Rate Limiting (IP당 분당 5회)
    $clientIp = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    if (!checkRateLimit('contact_' . $clientIp, 5, 60)) {
        $error = '요청이 너무 많습니다. 1분 후 다시 시도해 주세요.';
    }

    // CSRF 검증
    if (!$error && !validateCsrf($_POST['_csrf'] ?? '')) {
        $error = '보안 토큰이 유효하지 않습니다. 페이지를 새로고침 후 다시 시도해 주세요.';
    }

    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $message = trim($_POST['message'] ?? '');

    if (!$error && (empty($name) || empty($email) || empty($message))) {
        $error = '이름, 이메일, 문의 내용은 필수 항목입니다.';
    } elseif (!$error && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = '올바른 이메일 주소를 입력해 주세요.';
    } elseif (!$error) {
        // DB 저장
        try {
            $db = getDB();

            // 테이블 존재 확인 및 생성
            $db->exec("CREATE TABLE IF NOT EXISTS gs_contacts (
                id INT AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(100) NOT NULL,
                email VARCHAR(200) NOT NULL,
                category VARCHAR(50) DEFAULT '',
                message TEXT NOT NULL,
                ip_hash VARCHAR(64) DEFAULT '',
                is_read TINYINT(1) DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

            $stmt = $db->prepare(
                "INSERT INTO gs_contacts (name, email, category, message, ip_hash) VALUES (?, ?, ?, ?, ?)"
            );
            $stmt->execute([$name, $email, $category, $message, hash('sha256', $_SERVER['REMOTE_ADDR'] ?? '')]);
            $submitted = true;
        } catch (PDOException $e) {
            $error = '전송 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.';
            error_log("[Contact] DB Error: " . $e->getMessage());
        }
    }
}

require_once BASE_DIR . '/templates/header.php';
?>

<section class="section" style="padding-top: 3rem;">
<div class="container" style="max-width: 640px;">

<h1 style="font-size: 1.8rem; margin-bottom: 0.5rem;">문의하기</h1>
<p style="color: var(--text-muted); margin-bottom: 2rem;">정책 정보 오류 신고, 서비스 개선 의견, 기타 문의사항을 보내주세요.</p>

<?php if ($submitted): ?>
<div class="info-card" style="background: var(--success-bg, #f0fdf4); border-color: var(--success-border, #86efac); text-align: center; padding: 2rem;">
    <p style="font-size: 1.1rem; font-weight: 600; margin-bottom: 0.5rem;">문의가 접수되었습니다.</p>
    <p style="color: var(--text-secondary);">빠른 시일 내에 확인 후 답변드리겠습니다.</p>
    <a href="/" class="btn" style="margin-top: 1rem; display: inline-block;">홈으로 돌아가기</a>
</div>

<?php else: ?>

<?php if ($error): ?>
<div class="info-card" style="background: #fef2f2; border-color: #fca5a5; margin-bottom: 1.5rem;">
    <p style="color: #dc2626;"><?= e($error) ?></p>
</div>
<?php endif; ?>

<form method="POST" action="/contact" style="display: flex; flex-direction: column; gap: 1.2rem;">
    <input type="hidden" name="_csrf" value="<?= e(getCsrfToken()) ?>">
    <div>
        <label style="display: block; font-weight: 500; margin-bottom: 0.3rem; font-size: 0.9rem;">이름 <span style="color: #dc2626;">*</span></label>
        <input type="text" name="name" value="<?= e($_POST['name'] ?? '') ?>" required
               style="width: 100%; padding: 0.7rem; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.95rem;">
    </div>

    <div>
        <label style="display: block; font-weight: 500; margin-bottom: 0.3rem; font-size: 0.9rem;">이메일 <span style="color: #dc2626;">*</span></label>
        <input type="email" name="email" value="<?= e($_POST['email'] ?? '') ?>" required
               style="width: 100%; padding: 0.7rem; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.95rem;">
    </div>

    <div>
        <label style="display: block; font-weight: 500; margin-bottom: 0.3rem; font-size: 0.9rem;">문의 유형</label>
        <select name="category" style="width: 100%; padding: 0.7rem; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.95rem; background: white;">
            <option value="general">일반 문의</option>
            <option value="error">정책 정보 오류 신고</option>
            <option value="suggestion">서비스 개선 제안</option>
            <option value="privacy">개인정보 관련</option>
            <option value="other">기타</option>
        </select>
    </div>

    <div>
        <label style="display: block; font-weight: 500; margin-bottom: 0.3rem; font-size: 0.9rem;">문의 내용 <span style="color: #dc2626;">*</span></label>
        <textarea name="message" rows="6" required
                  style="width: 100%; padding: 0.7rem; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.95rem; resize: vertical;"><?= e($_POST['message'] ?? '') ?></textarea>
    </div>

    <button type="submit" class="btn" style="padding: 0.8rem; font-size: 1rem; cursor: pointer;">문의 보내기</button>
</form>

<?php endif; ?>

</div>
</section>

<?php require_once BASE_DIR . '/templates/footer.php'; ?>
