<?php

    use Mtc\Core\Models\CountryState;
    use Mtc\Modules\Members\Models\Member;

    // ---------- Normalize $order->address to ['billing'=>[], 'shipping'=>[]] arrays ----------
    $billing  = [];
    $shipping = [];

    if (isset($order->address)) {
        if ($order->address instanceof \Illuminate\Support\Collection) {
            // Relation loaded as a collection of address models
            foreach ($order->address as $addr) {
                $row = is_array($addr) ? $addr : (method_exists($addr, 'toArray') ? $addr->toArray() : []);
                if (($row['type'] ?? null) === 'billing')  { $billing  = $row; }
                if (($row['type'] ?? null) === 'shipping') { $shipping = $row; }
            }
        } elseif (is_array($order->address)) {
            // Already an array; might be keyed or a flat array
            if (isset($order->address['billing']) || isset($order->address['shipping'])) {
                $billing  = is_array($order->address['billing']  ?? null) ? $order->address['billing']  : [];
                $shipping = is_array($order->address['shipping'] ?? null) ? $order->address['shipping'] : [];
            } else {
                // Try to detect by 'type' on flat array(s)
                $row = $order->address;
                if (($row['type'] ?? null) === 'billing')  { $billing  = $row; }
                if (($row['type'] ?? null) === 'shipping') { $shipping = $row; }
            }
        }
    }

    // Fallback to dedicated relations if normalization above didn’t yield data
    if (!$billing && isset($order->billingAddress) && $order->billingAddress) {
        $billing = method_exists($order->billingAddress, 'toArray') ? $order->billingAddress->toArray() : (array)$order->billingAddress;
    }
    if (!$shipping && isset($order->shippingAddress) && $order->shippingAddress) {
        $shipping = method_exists($order->shippingAddress, 'toArray') ? $order->shippingAddress->toArray() : (array)$order->shippingAddress;
    }

    // Rebind into $order->address so the rest of the template can keep using it
    $order->address = ['billing' => $billing, 'shipping' => $shipping];

    // Short-hands (by reference for readability)
    $bill = &$order->address['billing'];
    $ship = &$order->address['shipping'];

    // Helpers
    $countryName = function (?string $code) use ($countries) {
        return clean_page($countries[$code] ?? ($code ?? ''));
    };
    $val = function ($arr, $key) {
        return clean_page($arr[$key] ?? '');
    };

    $edit = isset($_REQUEST['edit']) && $_REQUEST['edit'] == 1;

?>
<table>
    <tr>
        <td valign="top">
            <b>Shipping Address</b><br/>
            <?php if (SHIPPING_ADDRESS): ?>
                <?php if ($edit): ?>
                    <div class="row">
                        <select name="shipping_gender">
                            <option value="">Select gender</option>
                            <?php foreach (Member::$genders as $gender): ?>
                                <?php $selected = (($ship['gender'] ?? '') === $gender) ? 'selected' : ''; ?>
                                <option value="<?= $gender ?>" <?= $selected ?>><?= $gender ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <input type="text" name="shipping_firstname" placeholder="First Name" value="<?= $val($ship,'firstname'); ?>"/>
                    <input type="text" name="shipping_lastname"  placeholder="Last Name"  value="<?= $val($ship,'lastname');  ?>"/><br/>
                    <input type="text" name="shipping_address1"  placeholder="Address Line 1" value="<?= $val($ship,'address1'); ?>"/><br/>
                    <input type="text" name="shipping_address2"  placeholder="Address Line 2" value="<?= $val($ship,'address2'); ?>"/><br/>
                    <input type="text" name="shipping_city"      placeholder="City"          value="<?= $val($ship,'city');     ?>"/><br/>
                    <input type="text" name="shipping_country"   placeholder="Country Code"  value="<?= $val($ship,'country');  ?>"/><br/>
                    <input type="text" name="shipping_postcode"  placeholder="Postcode"      value="<?= $val($ship,'postcode'); ?>"/>
                <?php else: ?>
                    <?= $val($ship,'firstname'); ?> <?= $val($ship,'lastname'); ?> (<?= $val($ship,'gender'); ?>)<br/>
                    <?= $val($ship,'address1'); ?><br/>
                    <?php if (!empty($ship['address2'])): ?>
                        <?= clean_page($ship['address2']); ?><br/>
                    <?php endif; ?>
                    <?= $val($ship,'city'); ?><br/>
                    <?php
                    $shipCountry = $ship['country'] ?? null;
                    $shipState   = $ship['state']   ?? null;
                    if (!empty($shipState)) {
                        echo clean_page(CountryState::getNameByCode($shipCountry, $shipState)) . '<br/>';
                    }
                    ?>
                    <?= $countryName($shipCountry); ?><br/>
                    <?= $val($ship,'postcode'); ?><br/>
                <?php endif; ?>
            <?php else: ?>
                <?= $val($bill,'firstname'); ?> <?= $val($bill,'lastname'); ?> (<?= $val($bill,'gender'); ?>)<br/>
                <?= $val($bill,'address1'); ?><br/>
                <?php if (!empty($bill['address2'])): ?>
                    <?= clean_page($bill['address2']); ?><br/>
                <?php endif; ?>
                <?= $val($bill,'city'); ?><br/>
                <?php
                $billCountry = $bill['country'] ?? null;
                $billState   = $bill['state']   ?? null;
                if (!empty($billState)) {
                    echo clean_page(CountryState::getNameByCode($billCountry, $billState)) . '<br/>';
                }
                ?>
                <?= $countryName($billCountry); ?><br/>
                <?= $val($bill,'postcode'); ?><br/>
            <?php endif; ?>

            <?php if ($edit): ?>
                <input type="text" name="contact_no" value="<?= clean_page($order->info['contact_no'] ?? ''); ?>"/><br/>
            <?php else: ?>
                Phone: <?= clean_page($order->info['contact_no'] ?? ''); ?>
            <?php endif; ?>

            <?php if (!empty($ship['notes'])): ?>
                <p class="row">
                    <strong>Alternate shipping address notes</strong><br />
                    <?= clean_page($ship['notes']); ?>
                </p>
            <?php endif; ?>

            <?php if (defined('ORDER_NOTES_ENABLED') && ORDER_NOTES_ENABLED && !empty($order->info['message'])): ?>
                <p class="row">
                    <strong>Order notes</strong><br />
                    <?= clean_page($order->info['message']); ?>
                </p>
            <?php endif; ?>
        </td>

        <td valign="top">
            <b>Billing Address</b><br/>
            <?php if ($edit): ?>
                <div class="row">
                    <select name="billing_gender">
                        <option value="">Select gender</option>
                        <?php foreach (Member::$genders as $gender): ?>
                            <?php $selected = (($bill['gender'] ?? '') === $gender) ? 'selected' : ''; ?>
                            <option value="<?= $gender ?>" <?= $selected ?>><?= $gender ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <input type="text" name="billing_firstname" placeholder="First Name" value="<?= $val($bill,'firstname'); ?>"/>
                <input type="text" name="billing_lastname"  placeholder="Last Name"  value="<?= $val($bill,'lastname');  ?>"/><br/>
                <input type="text" name="billing_address1"  placeholder="Address Line 1" value="<?= $val($bill,'address1'); ?>"/><br/>
                <input type="text" name="billing_address2"  placeholder="Address Line 2" value="<?= $val($bill,'address2'); ?>"/><br/>
                <input type="text" name="billing_city"      placeholder="City"          value="<?= $val($bill,'city');     ?>"/><br/>
                <input type="text" name="billing_country"   placeholder="Country Code"  value="<?= $val($bill,'country');  ?>"/><br/>
                <input type="text" name="billing_postcode"  placeholder="Postcode"      value="<?= $val($bill,'postcode'); ?>"/>
            <?php else: ?>
                <?= $val($bill,'firstname'); ?> <?= $val($bill,'lastname'); ?> (<?= $val($bill,'gender'); ?>)<br/>
                <?= $val($bill,'address1'); ?><br/>
                <?php if (!empty($bill['address2'])): ?>
                    <?= clean_page($bill['address2']); ?><br/>
                <?php endif; ?>
                <?= $val($bill,'city'); ?><br/>
                <?php
                $billCountry = $bill['country'] ?? null;
                $billState   = $bill['state']   ?? null;
                if (!empty($billState)) {
                    echo clean_page(CountryState::getNameByCode($billCountry, $billState)) . '<br/>';
                }
                ?>
                <?= $countryName($billCountry); ?><br/>
                <?= $val($bill,'postcode'); ?><br/>
                Phone: <?= clean_page($order->info['contact_no'] ?? ''); ?>
            <?php endif; ?>
        </td>
    </tr>
</table>
