<?php
require_once 'db.php';
require_once 'notifications.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $vendorEmail = $_GET['vendorEmail'] ?? '';
    if (!$vendorEmail) {
        http_response_code(400);
        echo json_encode(['error' => 'vendorEmail required']);
        exit;
    }

    try {
        $stmtV = $pdo->prepare("SELECT loyalty_coins FROM vendors WHERE contactEmail = ?");
        $stmtV->execute([$vendorEmail]);
        $coins = $stmtV->fetchColumn();
        if ($coins === false) $coins = 0;

        $stmtT = $pdo->prepare("SELECT * FROM loyalty_transactions WHERE vendor_email = ? ORDER BY createdAt DESC");
        $stmtT->execute([$vendorEmail]);
        $transactions = $stmtT->fetchAll(PDO::FETCH_ASSOC);

        foreach ($transactions as &$t) {
            $t['amount'] = (int)$t['amount'];
            $t['createdAt'] = (int)$t['createdAt'];
        }

        echo json_encode([
            'loyalty_coins' => (int)$coins,
            'transactions' => $transactions
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
} else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
    $action = $_GET['action'] ?? '';

    if ($action === 'feature_product') {
        $vendorEmail = $data['vendorEmail'] ?? '';
        $productId = $data['productId'] ?? '';

        if (!$vendorEmail || !$productId) {
            http_response_code(400);
            echo json_encode(['error' => 'vendorEmail and productId required']);
            exit;
        }

        $pdo->beginTransaction();
        try {
            // Check vendor balance
            $stmtV = $pdo->prepare("SELECT loyalty_coins FROM vendors WHERE contactEmail = ? FOR UPDATE");
            $stmtV->execute([$vendorEmail]);
            $coins = (int)($stmtV->fetchColumn() ?? 0);

            if ($coins < 100) {
                $pdo->rollBack();
                echo json_encode(['success' => false, 'error' => 'Insufficient loyalty coins. You need 100 coins to feature an item.']);
                exit;
            }

            // Check product
            $stmtP = $pdo->prepare("SELECT name FROM products WHERE id = ?");
            $stmtP->execute([$productId]);
            $productName = $stmtP->fetchColumn() ?: 'Product';

            // Deduct 100 coins
            $newBalance = $coins - 100;
            $pdo->prepare("UPDATE vendors SET loyalty_coins = ? WHERE contactEmail = ?")->execute([$newBalance, $vendorEmail]);

            // Set product as featured and top
            $pdo->prepare("UPDATE products SET is_featured = 1, is_top = 1 WHERE id = ?")->execute([$productId]);

            // Log loyalty transaction
            $stmtT = $pdo->prepare("INSERT INTO loyalty_transactions (vendor_email, amount, type, description, product_id, createdAt) VALUES (?, ?, ?, ?, ?, ?)");
            $stmtT->execute([
                $vendorEmail,
                -100,
                'spent_feature',
                "Spent 100 Loyalty Coins to feature '$productName'",
                $productId,
                time()
            ]);

            // Send notification
            createNotification(
                $pdo,
                $vendorEmail,
                'vendor',
                '✨ Product Featured!',
                "You spent 100 Loyalty Coins to feature '$productName' across SulejaMarket.",
                'product_featured',
                '/vendor'
            );

            $pdo->commit();
            echo json_encode(['success' => true, 'loyalty_coins' => $newBalance]);
        } catch (Exception $e) {
            $pdo->rollBack();
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    }
}
?>
