<?php
use Orchard\Service\Ows\Account as OwsAccountServiceClient;
use Orchard\FeatureFlags\Context\AccountContext;
use Orchard\FeatureFlags\FeatureService;
use Orchard\Service\Ows\Carveouts;

$logger = Zend_Registry::get('applicationLoggerOA');

$owsFeaturesClient = new FeatureService($logger);
$deprecateVendorDefaultSelectionTable = $owsFeaturesClient->isVariant(
    'deprecate_use_of_vendor_physical_supplychain_default_selection_table',
    'enabled',
    AccountContext::fromLegacy((string)$_SESSION['S_USERID'], 'oa')
);

$owsCarveoutsClient = new Carveouts($logger);

if (!$deprecateVendorDefaultSelectionTable) {
    $owsAccount = new OwsAccountServiceClient(logger: $logger);
    $stores = $owsCarveoutsClient->getPhysicalStores();
    if ($stores) {
        asort($stores);
    } else {
        $stores = array();
    }
    $suppliers = array();
    try {
        $items = json_decode($owsAccount->getSupplyChainInfo($this->vendorId, $_SESSION['S_USERID']));
        foreach ($items as $item) {
            $suppliers[$item->store_id] = $item->store_id;
        }
    } catch (\Exception $e) {
        // do nothing
    }
} else {
    $stores = $owsCarveoutsClient->getPhysicalStores();
    if (!$stores) {
        throw new Exception('Unable to retrieve physical suppliers');
    }

    $vendorCarveouts = $owsCarveoutsClient->getVendorCarveoutsByVendorId($this->vendorId);
    $carveoutResultsForVendor = $vendorCarveouts['message'] ?? [];
    $suppliers = [];

    if (!empty($carveoutResultsForVendor['store'])) {
        $suppliers = array_diff(array_keys($stores), array_keys($carveoutResultsForVendor['store']));
    }
}
?>
<div class="panelHeader" id="grasregistration_header">
    <h3>Physical Supply Chain</h3>
    <ul><li><a href="/cont_mgmt/edit_vendor.php?vendor_id=<?=$this->vendorId?>">Edit</a></li>
    </ul>
</div>
<div class="panelContent" id="grasregistration_content">
    <table class="form">
        <?php
        foreach ($stores as $storeId => $storeName) {?>
        <tr>
            <td><?=$storeName?> :</td>
            <td><?=in_array($storeId, $suppliers) ? 'Approved' : 'N/A'?></td>
        </tr>
        <?php
        }
        ?>
    </table>
</div>
