<?php
require_once dirname(__DIR__, 2) . '/config.php';

$user_id = $_SESSION['user_id'];
$user = currentUser();

// 检查是否为代理商
if ($user['is_agent'] != 1) {
    redirect('?page=dashboard');
}

$error = '';
$success = '';

// 处理产品上传
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upload') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $duration_days = intval($_POST['duration_days'] ?? 0);
    $commission_rate = floatval($_POST['commission_rate'] ?? 0);
    
    if (empty($name)) {
        $error = '产品名称不能为空';
    } elseif ($price <= 0) {
        $error = '价格必须大于0';
    } elseif ($commission_rate < 0 || $commission_rate > 100) {
        $error = '佣金比例应在0-100之间';
    } else {
        // 处理图片上传
        $images = [];
        if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
            $upload_dir = UPLOAD_DIR . 'agent_products/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
                if ($_FILES['images']['error'][$key] == 0) {
                    $ext = pathinfo($_FILES['images']['name'][$key], PATHINFO_EXTENSION);
                    $filename = 'product_' . time() . '_' . uniqid() . '.' . $ext;
                    $target = $upload_dir . $filename;
                    if (move_uploaded_file($tmp_name, $target)) {
                        $images[] = UPLOAD_URL . 'agent_products/' . $filename;
                    }
                }
            }
        }
        
        $name = $db->escape($name);
        $description = $db->escape($description);
        $images_json = json_encode($images);
        
        $db->query("INSERT INTO agent_products (agent_id, name, description, price, duration_days, commission_rate, images, status) 
                    VALUES ($user_id, '$name', '$description', $price, $duration_days, $commission_rate, '$images_json', 'pending')");
        $success = '产品已提交，等待管理员审核';
    }
}

// 获取代理商已上传的产品
$products = $db->fetchAll("
    SELECT * FROM agent_products 
    WHERE agent_id = $user_id 
    ORDER BY id DESC
");
?>

<div class="agent-products-container">
    <div class="page-header">
        <h2>我的产品</h2>
        <button class="btn btn-primary" id="showUploadModalBtn">+ 上传新产品</button>
    </div>
    
    <!-- 产品列表 -->
    <div class="products-grid">
        <?php if (empty($products)): ?>
            <div class="empty-state">
                <div class="empty-icon">📦</div>
                <p>暂无产品</p>
                <button class="btn btn-primary" onclick="document.getElementById('showUploadModalBtn').click()">上传第一个产品</button>
            </div>
        <?php else: ?>
            <?php foreach ($products as $product): ?>
                <div class="product-card">
                    <div class="product-status status-<?php echo $product['status']; ?>">
                        <?php 
                        $status_map = ['pending' => '待审核', 'approved' => '已上架', 'rejected' => '已拒绝'];
                        echo $status_map[$product['status']];
                        ?>
                    </div>
                    <h3><?php echo htmlspecialchars($product['name']); ?></h3>
                    <p class="product-desc"><?php echo htmlspecialchars(mb_substr($product['description'], 0, 100)); ?></p>
                    <div class="product-meta">
                        <span>💰 价格：¥<?php echo number_format($product['price'], 2); ?></span>
                        <span>📅 授权期限：<?php echo $product['duration_days'] ? $product['duration_days'] . '天' : '永久'; ?></span>
                        <span>🎁 佣金：<?php echo $product['commission_rate']; ?>%</span>
                    </div>
                    <?php if ($product['status'] == 'rejected' && $product['admin_remark']): ?>
                        <div class="reject-reason">拒绝原因：<?php echo htmlspecialchars($product['admin_remark']); ?></div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- 上传产品弹窗 -->
<div id="uploadModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 600px;">
        <div class="modal-header">
            <h3>上传产品</h3>
            <span class="close">&times;</span>
        </div>
        <form id="uploadForm" enctype="multipart/form-data">
            <input type="hidden" name="action" value="upload">
            <div class="modal-body">
                <div class="form-group">
                    <label>产品名称 *</label>
                    <input type="text" name="name" required placeholder="例如：高级主题授权">
                </div>
                <div class="form-group">
                    <label>产品描述</label>
                    <textarea name="description" rows="4" placeholder="详细描述产品功能、特点..."></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group" style="flex:1">
                        <label>价格 (元) *</label>
                        <input type="number" name="price" step="0.01" required>
                    </div>
                    <div class="form-group" style="flex:1">
                        <label>授权期限 (天)</label>
                        <input type="number" name="duration_days" value="0" placeholder="0表示永久">
                    </div>
                </div>
                <div class="form-group">
                    <label>佣金比例 (%) *</label>
                    <input type="number" name="commission_rate" step="0.01" required placeholder="例如：20">
                    <small>销售后您将获得此比例的佣金</small>
                </div>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="discount_enabled" value="1" checked>
                        启用折扣优惠
                    </label>
                </div>
                <div class="discount-settings" id="discountSettings">
                    <div class="form-row">
                        <div class="form-group" style="flex:1">
                            <label>折扣类型</label>
                            <select name="discount_type" id="discount_type">
                                <option value="percent">百分比折扣</option>
                                <option value="fixed">固定金额折扣</option>
                            </select>
                        </div>
                        <div class="form-group" style="flex:1">
                            <label>折扣值</label>
                            <input type="number" name="discount_value" id="discount_value" step="0.01" value="0" placeholder="百分比如：10 或 固定金额如：5">
                            <small id="discount_tip">例如：10 表示 9折</small>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" name="stack_discount" value="1">
                            与平台用户组折扣叠加
                        </label>
                        <small>开启后，用户可同时享受会员折扣和您的专属折扣</small>
                    </div>
                </div>
                <div class="form-group">
                    <label>产品图片</label>
                    <input type="file" name="images[]" accept="image/*" multiple>
                    <small>支持多选，最多5张图片</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancel-btn">取消</button>
                <button type="submit" class="btn btn-primary">提交审核</button>
            </div>
        </form>
    </div>
</div>

<style>
.agent-products-container {
    max-width: 100%;
}
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}
.products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
}
.product-card {
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    padding: 20px;
    position: relative;
    transition: all 0.3s;
}
.product-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow-md);
}
.product-status {
    position: absolute;
    top: 16px;
    right: 16px;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}
.status-pending {
    background: #fef3c7;
    color: #92400e;
}
.status-approved {
    background: #d1fae5;
    color: #065f46;
}
.status-rejected {
    background: #fee2e2;
    color: #991b1b;
}
.product-card h3 {
    font-size: 18px;
    margin-bottom: 8px;
    padding-right: 70px;
}
.product-desc {
    color: var(--text-secondary);
    font-size: 13px;
    line-height: 1.5;
    margin-bottom: 12px;
}
.product-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    font-size: 12px;
    color: var(--text-muted);
    margin-bottom: 12px;
}
.reject-reason {
    background: #fee2e2;
    padding: 8px 12px;
    border-radius: 8px;
    font-size: 12px;
    color: #991b1b;
    margin-top: 12px;
}
.empty-state {
    text-align: center;
    padding: 80px 20px;
    background: var(--bg-primary);
    border-radius: 20px;
}
.empty-icon {
    font-size: 64px;
    margin-bottom: 16px;
    opacity: 0.5;
}
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: 20px;
    width: 90%;
    max-width: 600px;
    max-height: 90vh;
    overflow-y: auto;
}
.modal-header {
    padding: 18px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
}
.modal-body {
    padding: 24px;
}
.modal-footer {
    padding: 16px 24px;
    border-top: 1px solid var(--border-color);
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}
.form-row {
    display: flex;
    gap: 16px;
}
.discount-settings {
    background: var(--bg-secondary);
    padding: 16px;
    border-radius: 12px;
    margin-bottom: 16px;
}
.loading-spinner {
    display: inline-block;
    width: 14px;
    height: 14px;
    border: 2px solid #fff;
    border-radius: 50%;
    border-top-color: transparent;
    animation: spin 0.6s linear infinite;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}
</style>

<script>
const modal = document.getElementById('uploadModal');
const form = document.getElementById('uploadForm');

// 折扣开关控制
const discountCheckbox = document.querySelector('input[name="discount_enabled"]');
const discountSettings = document.getElementById('discountSettings');
const discountType = document.getElementById('discount_type');
const discountValue = document.getElementById('discount_value');
const discountTip = document.getElementById('discount_tip');

if (discountCheckbox) {
    discountCheckbox.addEventListener('change', function() {
        discountSettings.style.display = this.checked ? 'block' : 'none';
    });
}

if (discountType) {
    discountType.addEventListener('change', function() {
        if (this.value === 'percent') {
            discountTip.innerHTML = '例如：10 表示 9折';
            discountValue.placeholder = '百分比（1-99）';
        } else {
            discountTip.innerHTML = '例如：5 表示减5元';
            discountValue.placeholder = '固定金额（元）';
        }
    });
}

document.getElementById('showUploadModalBtn')?.addEventListener('click', () => {
    modal.style.display = 'flex';
});

document.querySelectorAll('.close, .cancel-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        modal.style.display = 'none';
    });
});

form?.addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<span class="loading-spinner"></span> 提交中...';
    submitBtn.disabled = true;
    
    fetch('/api/agent_upload_product.php?action=upload', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            window.showToast(data.message || '提交成功，等待审核', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            window.showToast(data.message || '提交失败', 'error');
        }
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
        modal.style.display = 'none';
    })
    .catch(err => {
        console.error(err);
        window.showToast('网络错误', 'error');
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});
</script>