<?php
// api/admin_gifts_action.php - 禮品管理後台 API
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(0);
require_once 'db.php';

$method = $_SERVER['REQUEST_METHOD'];

// 驗證天啟者權限
function checkAdmin($pdo, $admin_id) {
    $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
    $stmt->execute([$admin_id]);
    if ($stmt->fetchColumn() < 99) { echo json_encode(["status" => "error", "message" => "權限不足"]); exit; }
}

// 🟢 GET: 取得所有禮品清單 (包含下架的)
if ($method === 'GET') {
    $stmt = $pdo->query("SELECT * FROM gifts ORDER BY is_active DESC, id DESC");
    echo json_encode(["status" => "success", "data" => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

// 🔴 POST: 新增、切換狀態、刪除
if ($method === 'POST') {
    $input = json_decode(file_get_contents("php://input"), true);
    $admin_id = $input['admin_id'] ?? 0;
    $action = $input['action'] ?? '';

    checkAdmin($pdo, $admin_id);

    try {
        if ($action === 'add') {
            // 新增商品
            $name = trim($input['name']);
            $type = trim($input['type']);
            $cost = intval($input['cost']);
            $icon = trim($input['icon']) ?: '🎁';
            $desc = trim($input['description']);
            
            if (!$name || !$type || $cost <= 0) throw new Exception("資料填寫不完整");

            $stmt = $pdo->prepare("INSERT INTO gifts (name, type, cost, icon, description) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$name, $type, $cost, $icon, $desc]);
            $msg = "✅ 商品上架成功！";

        } else if ($action === 'toggle') {
            // 切換上下架狀態
            $gift_id = intval($input['gift_id']);
            $stmt = $pdo->prepare("UPDATE gifts SET is_active = NOT is_active WHERE id = ?");
            $stmt->execute([$gift_id]);
            $msg = "🔄 商品狀態已更新！";

        } else if ($action === 'delete') {
            // 永久刪除
            $gift_id = intval($input['gift_id']);
            $stmt = $pdo->prepare("DELETE FROM gifts WHERE id = ?");
            $stmt->execute([$gift_id]);
            $msg = "🗑️ 商品已從倉庫永久刪除！";
        }

        echo json_encode(["status" => "success", "message" => $msg]);
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
    exit;
}
?>