<?php
require_once '../config.php';

// 權限檢查：必須登入且為 admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

$family_id = $_SESSION['family_id'];
$success_msg = '';
$error_msg = '';

// ==========================================
// 1. 處理 POST 動作
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'save_item') {
        $id = !empty($_POST['item_id']) ? (int)$_POST['item_id'] : null;
        $name = trim($_POST['item_name']);
        $price = (int)$_POST['price_minutes'];
        $desc = trim($_POST['description']);
        $active = isset($_POST['is_active']) ? 1 : 0;

        if (empty($name) || $price <= 0) {
            $error_msg = "商品名稱與售價為必填，且售價必須大於 0！";
        } else {
            try {
                if ($id) {
                    $sql = "UPDATE items_shop SET item_name=:n, price_minutes=:p, description=:d, is_active=:a WHERE id=:id AND family_id=:fid";
                    $stmt = $mysql_db->prepare($sql);
                    $stmt->execute([':n'=>$name, ':p'=>$price, ':d'=>$desc, ':a'=>$active, ':id'=>$id, ':fid'=>$family_id]);
                    $success_msg = "獎勵「{$name}」已更新！";
                } else {
                    $sql = "INSERT INTO items_shop (family_id, item_name, price_minutes, description, is_active) VALUES (:fid, :n, :p, :d, :a)";
                    $stmt = $mysql_db->prepare($sql);
                    $stmt->execute([':fid'=>$family_id, ':n'=>$name, ':p'=>$price, ':d'=>$desc, ':a'=>$active]);
                    $success_msg = "新獎勵「{$name}」已上架家庭柑仔店！";
                }
            } catch (PDOException $e) {
                $error_msg = "儲存失敗：" . $e->getMessage();
            }
        }
    } elseif ($action === 'delete_item' && !empty($_POST['item_id'])) {
        try {
            $stmt = $mysql_db->prepare("DELETE FROM items_shop WHERE id = :id AND family_id = :fid");
            $stmt->execute([':id' => $_POST['item_id'], ':fid' => $family_id]);
            $success_msg = "商品已從柑仔店永久移除。";
        } catch (PDOException $e) {
            $error_msg = "刪除失敗：" . $e->getMessage();
        }
    }
}

// ==========================================
// 2. 取得要編輯的資料
// ==========================================
$edit_item = null;
if (isset($_GET['edit_id'])) {
    $stmt = $mysql_db->prepare("SELECT * FROM items_shop WHERE id = :id AND family_id = :fid");
    $stmt->execute([':id' => $_GET['edit_id'], ':fid' => $family_id]);
    $edit_item = $stmt->fetch();
}

// ==========================================
// 3. 讀取本家庭的商品清單
// ==========================================
$stmt_items = $mysql_db->prepare("SELECT * FROM items_shop WHERE family_id = :fid ORDER BY is_active DESC, created_at DESC");
$stmt_items->execute([':fid' => $family_id]);
$items = $stmt_items->fetchAll();
?>

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>家庭柑仔店管理 | 時間大富翁</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f7f6; color: #333; margin: 0; padding: 0; }
        
        .container { max-width: 1000px; margin: 20px auto; padding: 0 20px; display: grid; grid-template-columns: 350px 1fr; gap: 20px; }
        @media (max-width: 768px) { .container { grid-template-columns: 1fr; } }
        
        .card { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .card-header { border-bottom: 2px solid #f39c12; padding-bottom: 10px; margin-bottom: 15px; color: #d35400; font-size: 1.2rem; font-weight: bold; }
        
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; color: #34495e; font-size: 0.95rem; }
        input[type="text"], input[type="number"], textarea { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
        
        .btn-save { background-color: #f39c12; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; font-size: 1rem; font-weight: bold; width: 100%; transition: 0.2s;}
        .btn-save:hover { background-color: #e67e22; }
        .btn-cancel { display: block; text-align: center; margin-top: 10px; color: #7f8c8d; text-decoration: none; font-size: 0.9rem; }
        .btn-del { background-color: #e74c3c; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; font-size: 0.85rem; }
        
        .alert { padding: 10px; border-radius: 4px; margin-bottom: 15px; }
        .alert-error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .alert-success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
        th { background-color: #f8f9fa; color: #2c3e50; }
        .status-on { background: #d4edda; color: #155724; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem; font-weight: bold; }
        .status-off { background: #e2e3e5; color: #383d41; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem; }
    </style>
</head>
<body>

<?php include 'navbar.php'; ?>

<div class="container">
    <div class="card">
        <div class="card-header"><?php echo $edit_item ? '✏️ 修改商品設定' : '🎁 上架新獎勵'; ?></div>
        
        <?php if ($error_msg): ?><div class="alert alert-error"><?php echo $error_msg; ?></div><?php endif; ?>
        <?php if ($success_msg): ?><div class="alert alert-success"><?php echo $success_msg; ?></div><?php endif; ?>

        <form method="POST" action="shop.php">
            <input type="hidden" name="action" value="save_item">
            <input type="hidden" name="item_id" value="<?php echo $edit_item['id'] ?? ''; ?>">
            
            <div class="form-group">
                <label>商品名稱 (實體獎勵)</label>
                <input type="text" name="item_name" value="<?php echo htmlspecialchars($edit_item['item_name'] ?? ''); ?>" placeholder="例：看卡通 30 分鐘" required>
            </div>

            <div class="form-group">
                <label>兌換價格 (需花費的分鐘數)</label>
                <input type="number" name="price_minutes" value="<?php echo $edit_item['price_minutes'] ?? ''; ?>" min="1" required>
            </div>

            <div class="form-group">
                <label>兌換規則與說明 (選填)</label>
                <textarea name="description" rows="3" placeholder="例：僅限假日兌換，需提前一天告知。"><?php echo htmlspecialchars($edit_item['description'] ?? ''); ?></textarea>
            </div>

            <div class="form-group">
                <label style="display: flex; align-items: center; cursor: pointer; font-weight: normal;">
                    <input type="checkbox" name="is_active" style="width: auto; margin-right: 10px;" <?php echo (!isset($edit_item) || $edit_item['is_active']) ? 'checked' : ''; ?>> 
                    目前有貨 (打勾上架)
                </label>
            </div>

            <button type="submit" class="btn-save"><?php echo $edit_item ? '儲存修改' : '新增至柑仔店'; ?></button>
            <?php if ($edit_item): ?>
                <a href="shop.php" class="btn-cancel">取消修改</a>
            <?php endif; ?>
        </form>
    </div>

    <div class="card">
        <div class="card-header">🏪 柑仔店架上商品</div>
        <?php if (count($items) > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>獎勵名稱</th>
                        <th>價格</th>
                        <th>狀態</th>
                        <th width="120">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $item): ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($item['item_name']); ?></strong><br>
                                <small style="color: #7f8c8d;"><?php echo htmlspecialchars($item['description']); ?></small>
                            </td>
                            <td style="color: #e67e22; font-weight: bold;"><?php echo $item['price_minutes']; ?> 分</td>
                            <td>
                                <span class="<?php echo $item['is_active'] ? 'status-on' : 'status-off'; ?>">
                                    <?php echo $item['is_active'] ? '販售中' : '缺貨中'; ?>
                                </span>
                            </td>
                            <td>
                                <a href="shop.php?edit_id=<?php echo $item['id']; ?>" style="color: #3498db; text-decoration: none; margin-right: 10px; font-size: 0.9rem;">修改</a>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('確定要刪除「<?php echo htmlspecialchars($item['item_name']); ?>」嗎？');">
                                    <input type="hidden" name="action" value="delete_item">
                                    <input type="hidden" name="item_id" value="<?php echo $item['id']; ?>">
                                    <button type="submit" class="btn-del">刪除</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p style="text-align: center; color: #7f8c8d; padding: 20px;">柑仔店目前空空如也，趕快新增一些獎勵來激勵孩子吧！</p>
        <?php endif; ?>
    </div>
</div>

</body>
</html>