<?php
// api/admin_gifts_action.php - 天啟者專屬商品管理引擎 (支援專屬運費)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

// 🛡️ 屠龍刀防呆裝甲：確保資料表與 shipping_fee 欄位絕對存在
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS gifts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        type VARCHAR(20) NOT NULL DEFAULT 'virtual',
        cost INT NOT NULL DEFAULT 0,
        shipping_fee INT NOT NULL DEFAULT 0,
        icon VARCHAR(50) DEFAULT '🎁',
        is_active TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    // 試圖補上運費欄位 (若已存在會自動忽略報錯)
    $pdo->exec("ALTER TABLE gifts ADD COLUMN shipping_fee INT NOT NULL DEFAULT 0");
} catch (Exception $e) {
    // 忽略欄位已存在的錯誤
}

$method = $_SERVER['REQUEST_METHOD'];

// 🟢 GET: 撈取所有商品名單 (供前台與後台顯示)
if ($method === 'GET') {
    try {
        $stmt = $pdo->query("SELECT * FROM gifts ORDER BY is_active DESC, id DESC");
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(["status" => "success", "data" => $data]);
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => "讀取失敗: " . $e->getMessage()]);
    }
    exit;
}

// 🔴 POST: 天啟者新增/修改商品
if ($method === 'POST') {
    $input = json_decode(file_get_contents("php://input"), true);
    $admin_id = $input['admin_id'] ?? 0;
    
    try {
        // 1. 驗證天啟者身分
        $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
        $stmt->execute([$admin_id]);
        if ($stmt->fetchColumn() < 99) throw new Exception("天啟禁區，權限不足！");

        $action = $input['action'] ?? '';
        
        if ($action === 'save') {
            $id = $input['id'] ?? '';
            $name = $input['name'];
            $type = $input['type'];
            $cost = (int)$input['cost'];
            $shipping_fee = (int)($input['shipping_fee'] ?? 0);
            $icon = $input['icon'] ?? '🎁';
            $is_active = (int)$input['is_active'];

            if ($id) {
                // 修改現有商品
                $stmt = $pdo->prepare("UPDATE gifts SET name=?, type=?, cost=?, shipping_fee=?, icon=?, is_active=? WHERE id=?");
                $stmt->execute([$name, $type, $cost, $shipping_fee, $icon, $is_active, $id]);
            } else {
                // 新增商品
                $stmt = $pdo->prepare("INSERT INTO gifts (name, type, cost, shipping_fee, icon, is_active) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name, $type, $cost, $shipping_fee, $icon, $is_active]);
            }
            echo json_encode(["status" => "success", "message" => "商品儲存成功！"]);
        }
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
}
?>