<?php
$pageTitle = '电子请柬';
require_once 'header.php';
require_once 'config.php';

$themes = [
    'pink'    => ['name' => '浪漫粉', 'primary' => '#e891a0', 'secondary' => '#fce4ec', 'bg' => '#fff5f7'],
    'red'     => ['name' => '中国红', 'primary' => '#c41e3a', 'secondary' => '#fde8ec', 'bg' => '#fff8f8'],
    'gold'    => ['name' => '典雅金', 'primary' => '#b8860b', 'secondary' => '#fef9e7', 'bg' => '#fffdf5'],
    'purple'  => ['name' => '梦幻紫', 'primary' => '#7b2d8e', 'secondary' => '#f3e5f5', 'bg' => '#fdfbff'],
    'blue'    => ['name' => '星空蓝', 'primary' => '#1a5276', 'secondary' => '#eaf2f8', 'bg' => '#f7fbfd'],
    'green'   => ['name' => '清新绿', 'primary' => '#1e8449', 'secondary' => '#eafaf1', 'bg' => '#f8fdf9'],
];

$invitation = null;
$editing = false;

// 检查是否是编辑已有请柬
if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = $pdo->prepare("SELECT * FROM invitations WHERE id = ?");
    $stmt->execute([$id]);
    $invitation = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($invitation) {
        $editing = true;
    }
}

// 获取请柬寄语模板
$templates = [];
$categories = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM invitation_templates ORDER BY sort_order ASC");
    $stmt->execute();
    $templates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 获取所有分类
    $categorySet = [];
    foreach ($templates as $template) {
        $categorySet[$template['category']] = true;
    }
    $categories = array_keys($categorySet);
} catch (Exception $e) {
    // 如果表不存在，使用默认模板
    $templates = [];
}

// 处理表单提交
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $brideName    = trim($_POST['bride_name'] ?? '');
    $groomName    = trim($_POST['groom_name'] ?? '');
    $weddingDate  = trim($_POST['wedding_date'] ?? '');
    $weddingTime  = trim($_POST['wedding_time'] ?? '');
    $venue        = trim($_POST['venue'] ?? '');
    $venueAddress = trim($_POST['venue_address'] ?? '');
    $msg          = trim($_POST['message'] ?? '');
    $theme        = trim($_POST['theme'] ?? 'pink');

    // 图片处理
    $coverImage = $invitation['cover_image'] ?? '';
    if (isset($_FILES['cover_image']) && $_FILES['cover_image']['error'] === UPLOAD_ERR_OK) {
        // 文件大小限制：10MB
        $maxSize = 10 * 1024 * 1024;
        if ($_FILES['cover_image']['size'] > $maxSize) {
            $message = '封面图片大小不能超过10MB。';
            $messageType = 'error';
        } else {
            $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            
            $ext = strtolower(pathinfo($_FILES['cover_image']['name'], PATHINFO_EXTENSION));
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $_FILES['cover_image']['tmp_name']);
            finfo_close($finfo);
            
            if (!in_array($ext, $allowedExtensions) || !in_array($mime, $allowedMimeTypes)) {
                $message = '只支持 JPG、PNG、GIF、WebP 格式的图片。';
                $messageType = 'error';
            } else {
                $uploadDir = 'uploads/invitations/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                $filename = time() . '_' . uniqid() . '.' . $ext;
                $dest = $uploadDir . $filename;
                if (move_uploaded_file($_FILES['cover_image']['tmp_name'], $dest)) {
                    $coverImage = $dest;
                }
            }
        }
    }

    if (empty($brideName) || empty($groomName)) {
        $message = '请至少填写新郎和新娘姓名。';
        $messageType = 'error';
    } else {
        try {
            if ($editing && $invitation) {
                $stmt = $pdo->prepare(
                    "UPDATE invitations SET bride_name=?, groom_name=?, wedding_date=?, wedding_time=?, venue=?, venue_address=?, message=?, theme=?, cover_image=? WHERE id=?"
                );
                $stmt->execute([$brideName, $groomName, $weddingDate, $weddingTime, $venue, $venueAddress, $msg, $theme, $coverImage, $invitation['id']]);
                $message = '请柬更新成功！';
                $messageType = 'success';
                // 刷新数据
                $stmt = $pdo->prepare("SELECT * FROM invitations WHERE id = ?");
                $stmt->execute([$invitation['id']]);
                $invitation = $stmt->fetch(PDO::FETCH_ASSOC);
            } else {
                $shareCode = bin2hex(random_bytes(16));
                $stmt = $pdo->prepare(
                    "INSERT INTO invitations (user_id, bride_name, groom_name, wedding_date, wedding_time, venue, venue_address, message, theme, cover_image, share_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
                );
                $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
                $stmt->execute([$userId, $brideName, $groomName, $weddingDate, $weddingTime, $venue, $venueAddress, $msg, $theme, $coverImage, $shareCode]);
                $newId = $pdo->lastInsertId();
                $message = '请柬创建成功！';
                $messageType = 'success';
                $editing = true;
                // 获取新创建的记录
                $stmt = $pdo->prepare("SELECT * FROM invitations WHERE id = ?");
                $stmt->execute([$newId]);
                $invitation = $stmt->fetch(PDO::FETCH_ASSOC);
            }
        } catch (PDOException $e) {
            $message = '保存失败：' . $e->getMessage();
            $messageType = 'error';
        }
    }
}
?>

<main class="site-main">

    <section class="page-banner">
        <div class="container">
            <h1>💌 电子请柬制作</h1>
            <p>定制专属于你们的浪漫婚礼请柬，一键分享给亲朋好友</p>
        </div>
    </section>

    <section class="invitation-create">
        <div class="container">
            <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?>">
                <?php echo htmlspecialchars($message); ?>
                <?php if ($messageType === 'success' && $invitation): ?>
                    <a href="invitation_view.php?code=<?php echo $invitation['share_code']; ?>" class="btn btn-primary" style="margin-left:15px;">查看请柬</a>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <div class="invitation-create-grid">
                <!-- 左侧表单 -->
                <div class="invitation-form-panel">
                    <h2><?php echo $editing ? '编辑请柬' : '创建新请柬'; ?></h2>
                    <form method="POST" enctype="multipart/form-data" class="invitation-form">
                        <div class="form-row">
                            <div class="form-group">
                                <label>新郎姓名 <span class="required">*</span></label>
                                <input type="text" name="groom_name" value="<?php echo htmlspecialchars($invitation['groom_name'] ?? ''); ?>" placeholder="请输入新郎姓名" required>
                            </div>
                            <div class="form-group">
                                <label>新娘姓名 <span class="required">*</span></label>
                                <input type="text" name="bride_name" value="<?php echo htmlspecialchars($invitation['bride_name'] ?? ''); ?>" placeholder="请输入新娘姓名" required>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label>婚礼日期</label>
                                <input type="date" name="wedding_date" value="<?php echo htmlspecialchars($invitation['wedding_date'] ?? ''); ?>">
                            </div>
                            <div class="form-group">
                                <label>婚礼时间</label>
                                <input type="text" name="wedding_time" value="<?php echo htmlspecialchars($invitation['wedding_time'] ?? ''); ?>" placeholder="如：上午10:00">
                            </div>
                        </div>

                        <div class="form-group">
                            <label>婚礼场地</label>
                            <input type="text" name="venue" value="<?php echo htmlspecialchars($invitation['venue'] ?? ''); ?>" placeholder="如：XX大酒店 百合厅">
                        </div>

                        <div class="form-group">
                            <label>场地地址</label>
                            <input type="text" name="venue_address" value="<?php echo htmlspecialchars($invitation['venue_address'] ?? ''); ?>" placeholder="详细地址">
                        </div>

                        <div class="form-group">
                            <label>请柬寄语 <button type="button" class="btn btn-secondary btn-sm" style="margin-left:10px;" onclick="openTemplateModal()">选择模板</button></label>
                            <textarea name="message" id="messageInput" rows="4" placeholder="写下你们想对亲朋好友说的话..."><?php echo htmlspecialchars($invitation['message'] ?? ''); ?></textarea>
                        </div>

                        <div class="form-group">
                            <label>请柬主题</label>
                            <div class="theme-selector">
                                <?php foreach ($themes as $key => $t): ?>
                                <label class="theme-option <?php echo ($invitation['theme'] ?? 'pink') === $key ? 'active' : ''; ?>">
                                    <input type="radio" name="theme" value="<?php echo $key; ?>" <?php echo ($invitation['theme'] ?? 'pink') === $key ? 'checked' : ''; ?>>
                                    <span class="theme-swatch" style="background:<?php echo $t['primary']; ?>"></span>
                                    <span class="theme-name"><?php echo $t['name']; ?></span>
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>封面图片（可选）</label>
                            <input type="file" name="cover_image" accept="image/*">
                            <?php if (!empty($invitation['cover_image'])): ?>
                                <p class="current-image">当前封面：<?php echo htmlspecialchars($invitation['cover_image']); ?></p>
                            <?php endif; ?>
                        </div>

                        <button type="submit" class="btn btn-primary btn-block">
                            <?php echo $editing ? '更新请柬' : '创建请柬'; ?>
                        </button>
                    </form>
                </div>

                <!-- 右侧实时预览 -->
                <div class="invitation-preview-panel">
                    <h2>实时预览</h2>
                    <div class="preview-wrapper">
                        <?php
                        $previewTheme = $invitation['theme'] ?? 'pink';
                        $t = $themes[$previewTheme];
                        ?>
                        <div class="preview-card" style="background:<?php echo $t['bg']; ?>; border-color:<?php echo $t['primary']; ?>;">
                            <?php if (!empty($invitation['cover_image'])): ?>
                            <div class="preview-cover">
                                <img src="<?php echo (strpos($invitation['cover_image'], 'http') === 0 ? '' : './') . htmlspecialchars($invitation['cover_image']); ?>" alt="封面">
                            </div>
                            <?php else: ?>
                            <div class="preview-card-top" style="background: linear-gradient(135deg, <?php echo $t['primary']; ?>, <?php echo $t['secondary']; ?>);">
                                <div class="preview-icon">💒</div>
                                <p class="preview-subtitle">诚挚邀请您参加</p>
                            </div>
                            <?php endif; ?>
                            <div class="preview-card-body">
                                <h3 class="preview-couple">
                                    <span><?php echo htmlspecialchars($invitation['groom_name'] ?? '新郎'); ?></span>
                                    <span class="preview-and">&</span>
                                    <span><?php echo htmlspecialchars($invitation['bride_name'] ?? '新娘'); ?></span>
                                </h3>
                                <p class="preview-title">的婚礼</p>
                                <?php if (!empty($invitation['wedding_date'])): ?>
                                <div class="preview-info">
                                    <span>📅 <?php echo htmlspecialchars($invitation['wedding_date']); ?></span>
                                    <?php if (!empty($invitation['wedding_time'])): ?>
                                    <span>🕐 <?php echo htmlspecialchars($invitation['wedding_time']); ?></span>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                                <?php if (!empty($invitation['venue'])): ?>
                                <p class="preview-venue">📍 <?php echo htmlspecialchars($invitation['venue']); ?></p>
                                <?php endif; ?>
                                <?php if (!empty($invitation['venue_address'])): ?>
                                <p class="preview-address"><?php echo htmlspecialchars($invitation['venue_address']); ?></p>
                                <?php endif; ?>
                                <?php if (!empty($invitation['message'])): ?>
                                <p class="preview-message">"<?php echo htmlspecialchars($invitation['message']); ?>"</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <?php if ($editing && $invitation): ?>
                    <div class="share-section">
                        <h3>分享请柬</h3>
                        <p>复制链接发送给亲朋好友：</p>
                        <div class="share-link-box">
                            <?php
                            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
                            $host = $_SERVER['HTTP_HOST'];
                            $scriptName = $_SERVER['SCRIPT_NAME'];
                            $basePath = dirname($scriptName);
                            if ($basePath === '/') {
                                $basePath = '';
                            }
                            $shareUrl = $protocol . '://' . $host . $basePath . '/invitation_view.php?code=' . $invitation['share_code'];
                            ?>
                            <input type="text" id="shareUrl" value="<?php echo htmlspecialchars($shareUrl); ?>" readonly>
                            <button type="button" class="btn btn-primary" onclick="copyShareUrl()">复制链接</button>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- 我的请柬列表 -->
            <?php if (isset($_SESSION['user_id'])): ?>
            <div class="my-invitations">
                <h2>我的请柬</h2>
                <?php
                $stmt = $pdo->prepare("SELECT * FROM invitations WHERE user_id = ? ORDER BY created_at DESC");
                $stmt->execute([$_SESSION['user_id']]);
                $myInvitations = $stmt->fetchAll(PDO::FETCH_ASSOC);
                ?>
                <?php if (empty($myInvitations)): ?>
                    <p class="empty-state">您还没有创建请柬，快来制作第一个吧！</p>
                <?php else: ?>
                <div class="my-invitation-grid">
                    <?php foreach ($myInvitations as $inv): ?>
                    <div class="my-invitation-card">
                        <div class="my-invitation-preview">
                            <div class="mini-invite">
                                <span class="mini-icon">💒</span>
                                <strong><?php echo htmlspecialchars($inv['groom_name']); ?> & <?php echo htmlspecialchars($inv['bride_name']); ?></strong>
                                <?php if ($inv['wedding_date']): ?>
                                <span><?php echo htmlspecialchars($inv['wedding_date']); ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="my-invitation-actions">
                            <a href="invitation_view.php?code=<?php echo $inv['share_code']; ?>" class="btn btn-primary btn-sm" target="_blank">查看</a>
                            <a href="invitation_create.php?id=<?php echo $inv['id']; ?>" class="btn btn-sm btn-edit">编辑</a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
    </section>

</main>

<!-- 模板选择弹窗 -->
<div id="templateModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>选择请柬寄语模板</h3>
            <button type="button" class="close-btn" onclick="closeTemplateModal()">&times;</button>
        </div>
        <div class="modal-body">
            <!-- 分类标签 -->
            <div class="category-tabs">
                <button type="button" class="category-tab active" data-category="all" onclick="filterTemplates('all')">全部</button>
                <?php foreach ($categories as $category): ?>
                <button type="button" class="category-tab" data-category="<?php echo htmlspecialchars($category); ?>" onclick="filterTemplates('<?php echo htmlspecialchars($category); ?>')">
                    <?php echo htmlspecialchars($category); ?>
                </button>
                <?php endforeach; ?>
            </div>
            
            <!-- 模板列表 -->
            <div class="template-list">
                <?php if (empty($templates)): ?>
                    <p style="text-align:center; color:#999;">暂无模板数据</p>
                <?php else: ?>
                    <?php foreach ($templates as $template): ?>
                    <div class="template-item" data-category="<?php echo htmlspecialchars($template['category']); ?>">
                        <div class="template-title"><?php echo htmlspecialchars($template['title']); ?></div>
                        <div class="template-content"><?php echo htmlspecialchars($template['content']); ?></div>
                        <button type="button" class="btn btn-primary btn-sm" onclick="selectTemplate('<?php echo htmlspecialchars($template['content']); ?>')">
                            使用此模板
                        </button>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
function copyShareUrl() {
    var input = document.getElementById('shareUrl');
    input.select();
    input.setSelectionRange(0, 99999);
    document.execCommand('copy');
    alert('链接已复制到剪贴板！');
}

function openTemplateModal() {
    document.getElementById('templateModal').style.display = 'block';
    filterTemplates('all');
}

function closeTemplateModal() {
    document.getElementById('templateModal').style.display = 'none';
}

function filterTemplates(category) {
    var tabs = document.querySelectorAll('.category-tab');
    tabs.forEach(function(tab) {
        tab.classList.remove('active');
    });
    event.target.classList.add('active');
    
    var items = document.querySelectorAll('.template-item');
    items.forEach(function(item) {
        if (category === 'all' || item.dataset.category === category) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
}

function selectTemplate(content) {
    document.getElementById('messageInput').value = content;
    closeTemplateModal();
}

// 点击弹窗外部关闭
window.onclick = function(event) {
    var modal = document.getElementById('templateModal');
    if (event.target === modal) {
        closeTemplateModal();
    }
}
</script>

<?php require_once 'footer.php'; ?>