<?php

// STEP 1 - fetch the featured merchants JSON
$featured_merchants_url = 'https://www.wildlink.me/data/3/featured-merchant/1';

$context = stream_context_create([ "http" => [ "header"  => "User-agent: Myagent" ]]); // we need to declare a user agent to comply with Wildfire policy

$data = file_get_contents($featured_merchants_url, false, $context);
$featured_merchants = json_decode($data);

// let's prepare the merchant data so we can append metadata to it in the next step
foreach ($featured_merchants[0]->MerchantIDs as $merchant_id){
    $output_merchants[$merchant_id] = (object)["ID" => $merchant_id];
}

// STEP 2 - fetch the merchants JSON (for metadata)
$merchant_metadata_url = 'https://www.wildlink.me/data/3/merchant/1';

$context = stream_context_create([ "http" => [ "header"  => "User-agent: Myagent" ]]);
$data = file_get_contents($merchant_metadata_url, false, $context);
$merchant_metadata = json_decode($data);

// loop through the merchant metadata and find the matching merchant IDs
foreach ($merchant_metadata as $key => $merchant){
    if (in_array($merchant->ID, $featured_merchants[0]->MerchantIDs)){
        $output_merchants[$merchant->ID]->metadata = $merchant;
        
        // find the logo image from the available images for the merchant
        foreach ($merchant->Images as $image){
            if ($image->Kind == 'LOGO'){
                $output_merchants[$merchant->ID]->logo_url = $image->URL;
            }
        }
    }
}

?>

<style>
#merchants {width:700px}

.merchant {
    border: 1px solid #999;
    width: 200px;
    padding: 5px;
    float: left;
    margin-right: 10px;
    margin-bottom: 10px;
}
</style>

<h1>Merchants</h1>
<div id="merchants">
<?php foreach ($output_merchants as $merchant){ ?>
    <?php if (isset($merchant->metadata)){ ?>
    <div class="merchant">
        <div><?php if (isset($merchant->logo_url)){ ?><img src="<?=$merchant->logo_url?>"/><?php } ?></div>
        <div><?=$merchant->ID?> : <?=$merchant->metadata->Name?></div>
    </div>
    <?php } ?>
<?php } ?>
</div>
