<?php
require_once '../config/database.php';
require_once '../includes/functions.php';

check_admin_auth();

$action = $_GET['action'] ?? 'list';
$message = '';
$upload_error = '';

// 处理图片上传
function handle_image_upload($file) {
    // 如果是编辑模式且没有上传新图片，直接返回
    if ($file['error'] === UPLOAD_ERR_NO_FILE) {
        return ['success' => true];
    }

    $target_dir = "../uploads/products/";
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    
    $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
    
    if (!in_array($file_extension, $allowed_types)) {
        return ['error' => '只允许上传 JPG, JPEG, PNG 或 GIF 格式的图片'];
    }
    
    if ($file['size'] > 5000000) { // 5MB limit
        return ['error' => '图片大小不能超过5MB'];
    }
    
    $new_filename = uniqid() . '.' . $file_extension;
    $target_file = $target_dir . $new_filename;
    
    if (move_uploaded_file($file['tmp_name'], $target_file)) {
        return ['success' => true, 'filename' => $new_filename];
    }
    
    return ['error' => '图片上传失败，请重试'];
}

// 处理添加/编辑/删除商品
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !verify_csrf_token($_POST['csrf_token'])) {
        die('CSRF token verification failed');
    }

    if (isset($_POST['action']) && $_POST['action'] === 'delete' && isset($_POST['id'])) {
        $id = intval($_POST['id']);
        $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
        $stmt->execute([$id]);
        $message = '商品删除成功！';
        header("Location: products.php?action=list");
        exit;
    }

    $name = sanitize_input($_POST['name'] ?? '');
    $description = sanitize_input($_POST['description'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $stock = intval($_POST['stock'] ?? 0);
    $status = isset($_POST['status']) ? 1 : 0;

    // 处理图片上传
    $image = null;
    if (isset($_FILES['image'])) {
        $upload_result = handle_image_upload($_FILES['image']);
        if (isset($upload_result['error'])) {
            $upload_error = $upload_result['error'];
        } elseif (isset($upload_result['filename'])) {
            $image = $upload_result['filename'];
        }
    }

    if ($action === 'add') {
        if (empty($upload_error)) {
            $stmt = $pdo->prepare("INSERT INTO products (name, description, price, stock, status, image) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $description, $price, $stock, $status, $image]);
            $message = '商品添加成功！';
            header("Location: products.php?action=list");
            exit;
        }
    } elseif ($action === 'edit' && isset($_POST['id'])) {
        $id = intval($_POST['id']);
        if (!empty($image)) {
            // 如果上传了新图片
            $stmt = $pdo->prepare("UPDATE products SET name = ?, description = ?, price = ?, stock = ?, status = ?, image = ? WHERE id = ?");
            $stmt->execute([$name, $description, $price, $stock, $status, $image, $id]);
        } else {
            // 如果没有上传新图片
            $stmt = $pdo->prepare("UPDATE products SET name = ?, description = ?, price = ?, stock = ?, status = ? WHERE id = ?");
            $stmt->execute([$name, $description, $price, $stock, $status, $id]);
        }
        $message = '商品更新成功！';
        if (empty($upload_error)) {
            header("Location: products.php?action=list");
            exit;
        }
    }
}

// 获取商品列表或单个商品信息
if ($action === 'list') {
    // 分页设置
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $items_per_page = 10;
    $offset = ($page - 1) * $items_per_page;

    // 获取总记录数
    $total_stmt = $pdo->query("SELECT COUNT(*) FROM products");
    $total_items = $total_stmt->fetchColumn();
    $total_pages = ceil($total_items / $items_per_page);

    // 获取当前页的商品
    $stmt = $pdo->prepare("SELECT * FROM products ORDER BY id DESC LIMIT ? OFFSET ?");
    $stmt->execute([$items_per_page, $offset]);
    $products = $stmt->fetchAll();
} elseif ($action === 'edit' && isset($_GET['id'])) {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([intval($_GET['id'])]);
    $product = $stmt->fetch();
    if (!$product) {
        header("Location: products.php?action=list");
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品管理 - 发卡系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.0/css/all.min.css">
</head>
<body>
    <div class="columns is-gapless" style="min-height: 100vh;">
        <!-- 侧边栏 -->
        <div class="column is-2 has-background-light" style="padding: 1rem;">
            <aside class="menu">
                <p class="menu-label">管理菜单</p>
                <ul class="menu-list">
                    <li><a href="index.php">
                        <span class="icon"><i class="fas fa-chart-bar"></i></span>
                        <span>统计概览</span>
                    </a></li>
                    <li><a href="products.php" class="is-active">
                        <span class="icon"><i class="fas fa-box"></i></span>
                        <span>商品管理</span>
                    </a></li>
                    <li><a href="payment.php">
                        <span class="icon"><i class="fas fa-qrcode"></i></span>
                        <span>支付设置</span>
                    </a></li>
                    <li><a href="settings.php">
                        <span class="icon"><i class="fas fa-cog"></i></span>
                        <span>网站设置</span>
                    </a></li>
                    <li><a href="password.php">
                        <span class="icon"><i class="fas fa-key"></i></span>
                        <span>修改密码</span>
                    </a></li>
                    <li><a href="logout.php">
                        <span class="icon"><i class="fas fa-sign-out-alt"></i></span>
                        <span>退出登录</span>
                    </a></li>
                </ul>
            </aside>
        </div>

        <!-- 主要内容区 -->
        <div class="column">
            <section class="section">
                <div class="container">
                    <?php if ($message): ?>
                    <div class="notification <?php echo strpos($message, '成功') !== false ? 'is-success' : 'is-danger'; ?>">
                        <?php echo htmlspecialchars($message); ?>
                    </div>
                    <?php endif; ?>
                    <?php if ($upload_error): ?>
                    <div class="notification is-danger">
                        <?php echo htmlspecialchars($upload_error); ?>
                    </div>
                    <?php endif; ?>

                    <?php if ($action === 'list'): ?>
                    <div class="level">
                        <div class="level-left">
                            <div class="level-item">
                                <h1 class="title">商品管理</h1>
                            </div>
                        </div>
                        <div class="level-right">
                            <div class="level-item">
                                <a href="?action=add" class="button is-primary">
                                    <span class="icon">
                                        <i class="fas fa-plus"></i>
                                    </span>
                                    <span>添加商品</span>
                                </a>
                            </div>
                        </div>
                    </div>

                    <div class="table-container">
                        <table class="table is-fullwidth">
                            <thead>
                                <tr>
                                    <th>商品名称</th>
                                    <th>价格</th>
                                    <th>库存</th>
                                    <th>状态</th>
                                    <th>图片</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($products as $product): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($product['name']); ?></td>
                                    <td>¥<?php echo number_format($product['price'], 2); ?></td>
                                    <td><?php echo $product['stock']; ?></td>
                                    <td>
                                        <span class="tag <?php echo $product['status'] ? 'is-success' : 'is-danger'; ?>">
                                            <?php echo $product['status'] ? '上架' : '下架'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if (!empty($product['image'])): ?>
                                        <img src="../uploads/products/<?php echo htmlspecialchars($product['image']); ?>" alt="商品图片" style="max-width: 50px;">
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="buttons are-small">
                                            <a href="?action=edit&id=<?php echo $product['id']; ?>" class="button is-info">
                                                <span class="icon">
                                                    <i class="fas fa-edit"></i>
                                                </span>
                                            </a>
                                            <form method="post" style="display: inline;" onsubmit="return confirm('确定要删除这个商品吗？');">
                                                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="id" value="<?php echo $product['id']; ?>">
                                                <button type="submit" class="button is-danger">
                                                    <span class="icon">
                                                        <i class="fas fa-trash"></i>
                                                    </span>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页 -->
                    <?php if ($total_pages > 1): ?>
                    <nav class="pagination is-centered" role="navigation" aria-label="pagination">
                        <?php if ($page > 1): ?>
                        <a href="?page=<?php echo ($page - 1); ?>" class="pagination-previous">上一页</a>
                        <?php endif; ?>
                        <?php if ($page < $total_pages): ?>
                        <a href="?page=<?php echo ($page + 1); ?>" class="pagination-next">下一页</a>
                        <?php endif; ?>
                        <ul class="pagination-list">
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <li>
                                <a href="?page=<?php echo $i; ?>" class="pagination-link <?php echo $i === $page ? 'is-current' : ''; ?>" aria-label="第 <?php echo $i; ?> 页">
                                    <?php echo $i; ?>
                                </a>
                            </li>
                            <?php endfor; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>
                    <?php endif; ?>

                    <?php if ($action === 'add' || $action === 'edit'): ?>
                    <h1 class="title"><?php echo $action === 'add' ? '添加商品' : '编辑商品'; ?></h1>
                    
                    <form method="POST" action="" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                        <?php if ($action === 'edit'): ?>
                        <input type="hidden" name="id" value="<?php echo $product['id']; ?>">
                        <?php endif; ?>

                        <div class="field">
                            <label class="label">商品名称</label>
                            <div class="control">
                                <input class="input" type="text" name="name" required
                                    value="<?php echo $action === 'edit' ? htmlspecialchars($product['name']) : ''; ?>">
                            </div>
                        </div>

                        <div class="field">
                            <label class="label">商品描述</label>
                            <div class="control">
                                <textarea class="textarea" name="description"><?php echo $action === 'edit' ? htmlspecialchars($product['description']) : ''; ?></textarea>
                            </div>
                        </div>

                        <div class="field">
                            <label class="label">价格</label>
                            <div class="control">
                                <input class="input" type="number" step="0.01" name="price" required
                                    value="<?php echo $action === 'edit' ? $product['price'] : ''; ?>">
                            </div>
                        </div>

                        <div class="field">
                            <label class="label">库存</label>
                            <div class="control">
                                <input class="input" type="number" name="stock" required
                                    value="<?php echo $action === 'edit' ? $product['stock'] : '0'; ?>">
                            </div>
                        </div>

                        <div class="field">
                            <label class="checkbox">
                                <input type="checkbox" name="status" <?php echo ($action === 'edit' && $product['status']) ? 'checked' : ''; ?>>
                                商品上架
                            </label>
                        </div>

                        <div class="field">
                            <label class="label">商品图片</label>
                            <div class="control">
                                <?php if ($action === 'edit' && !empty($product['image'])): ?>
                                <div class="mb-3">
                                    <img src="../uploads/products/<?php echo htmlspecialchars($product['image']); ?>" alt="当前商品图片" style="max-width: 200px;">
                                    <p class="help">当前图片</p>
                                </div>
                                <?php endif; ?>
                                <input type="file" name="image" accept="image/*" <?php echo $action === 'add' ? 'required' : ''; ?>>
                                <p class="help">支持 JPG, JPEG, PNG, GIF 格式，大小不超过5MB<?php echo $action === 'edit' ? '。不上传则保持原图不变' : ''; ?></p>
                            </div>
                        </div>

                        <div class="field is-grouped">
                            <div class="control">
                                <button type="submit" class="button is-primary">保存</button>
                            </div>
                            <div class="control">
                                <a href="?action=list" class="button is-light">返回</a>
                            </div>
                        </div>
                    </form>
                    <?php endif; ?>
                </div>
            </section>
        </div>
    </div>
</body>
</html>
