<?php
declare(strict_types=1);

require_once __DIR__ . '/cma-functions.php';

$listingIds = cma_load_listing_ids();
$properties = cma_fetch_properties($listingIds);
$thumbnailMap = cma_fetch_thumbnail_map($listingIds);
$subject = cma_load_subject();

function cma_get(array $row, array $keys): string
{
    foreach ($keys as $key) {
        if (array_key_exists($key, $row) && $row[$key] !== null && $row[$key] !== '') {
            return (string)$row[$key];
        }
    }

    return '';
}

function cma_money_decimal($value): string
{
    if ($value === null || $value === '' || !is_numeric($value)) {
        return '$0.00';
    }

    return '$' . number_format((float)$value, 2);
}

function cma_total_finished_sqft(array $row): float
{
    $above = cma_get($row, ['NST_AboveGradeSqFtTotal']);
    $below = cma_get($row, ['BelowGradeFinishedArea']);

    $aboveNum = is_numeric($above) ? (float)$above : 0.0;
    $belowNum = is_numeric($below) ? (float)$below : 0.0;

    return $aboveNum + $belowNum;
}

function cma_subject_value(string $rowKey, array $subject): string
{
    $map = [
        'Photo'          => 'photo',
        'Status'         => 'status',
        'MLS #'          => 'mls',
        'Street Address' => 'street_address',
        'Municipality'   => 'municipality',
        'SubType'        => 'subtype',
        'Bed'            => 'bed',
        'Bath'           => 'bath',
        'AGSF'           => 'agsf',
        'TFSF'           => 'tfsf',
        'Built'          => 'built',
        'Orig Price'     => 'orig_price',
        'List Price'     => 'list_price',
        'Sale Price'     => 'sale_price',
        'SP%LP'          => 'sp_lp',
        'Date'           => 'date',
        'DOM'            => 'dom',
        'CDOM'           => 'cdom',
        '$/AGSF'         => 'price_agsf',
        '$/TFSF'         => 'price_tfsf',
        'SC'             => 'sc',
        'Garage'         => 'garage',
        'longitude'      => 'longitude',
        'latitude'       => 'latitude',
    ];

    $key = $map[$rowKey] ?? '';
    $value = $key !== '' ? (string)($subject[$key] ?? '') : '';

    // Backward compatibility with earlier JSON keys before we switched to safe field names.
    if ($value === '') {
        $legacyMap = [
            'Photo'          => 'Photo',
            'Status'         => 'Status',
            'MLS #'          => 'MLS',
            'Street Address' => 'Street Address',
            'Municipality'   => 'Municipality',
            'SubType'        => 'SubType',
            'Bed'            => 'Bed',
            'Bath'           => 'Bath',
            'AGSF'           => 'AGSF',
            'TFSF'           => 'TFSF',
            'Built'          => 'Built',
            'Orig Price'     => 'Orig Price',
            'List Price'     => 'List Price',
            'Sale Price'     => 'Sale Price',
            'SP%LP'          => 'SP%LP',
            'Date'           => 'Date',
            'DOM'            => 'DOM',
            'CDOM'           => 'CDOM',
            '$/AGSF'         => '$/AGSF',
            '$/TFSF'         => '$/TFSF',
            'SC'             => 'SC',
            'Garage'         => 'Garage',
            'longitude'      => 'longitude',
            'latitude'       => 'latitude',
        ];

        $legacyKey = $legacyMap[$rowKey] ?? '';
        $value = $legacyKey !== '' ? (string)($subject[$legacyKey] ?? '') : '';
    }

    if ($rowKey === 'Photo' && trim($value) !== '') {
        return '<img class="cma-photo" src="' . cma_h($value) . '" alt="Subject photo">';
    }

    return cma_h($value);
}

function cma_comp_value(string $rowKey, array $property, array $thumbnailMap): string
{
    $closePrice = cma_get($property, ['ClosePrice']);
    $listPrice  = cma_get($property, ['ListPrice']);
    $origPrice  = cma_get($property, ['OriginalListPrice', 'ListPrice']);

    $agsfRaw = cma_get($property, ['NST_AboveGradeSqFtTotal']);
    $agsf = is_numeric($agsfRaw) ? (float)$agsfRaw : 0.0;

    $tfsf = cma_total_finished_sqft($property);

    return match ($rowKey) {
        'Photo' => '<img class="cma-photo" src="' . cma_h(cma_photo_url($property, $thumbnailMap)) . '" alt="Property photo">',
        'Status' => cma_h(cma_get($property, ['StandardStatus'])),
        'MLS #' => cma_h(str_replace('NST', '', cma_get($property, ['ListingId']))),
        'Street Address' => cma_h(cma_address($property)),
        'Municipality' => cma_h(cma_get($property, ['City'])),
        'SubType' => cma_h(cma_get($property, ['PropertySubType'])),
        'Bed' => cma_h(cma_get($property, ['BedroomsTotal'])),
        'Bath' => cma_h(cma_get($property, ['BathroomsTotalInteger'])),
        'AGSF' => cma_h($agsf > 0 ? cma_number($agsf) : ''),
        'TFSF' => cma_h($tfsf > 0 ? cma_number($tfsf) : ''),
        'Built' => cma_h(cma_get($property, ['YearBuilt'])),
        'Orig Price' => cma_h(cma_money($origPrice)),
        'List Price' => cma_h(cma_money($listPrice)),
        'Sale Price' => cma_h(cma_money($closePrice)),
        'SP%LP' => cma_h(cma_sp_lp($property)),
        'Date' => cma_h(cma_date(cma_get($property, ['CloseDate', 'CloseDate2']))),
        'DOM' => cma_h(cma_get($property, ['DaysOnMarket'])),
        'CDOM' => cma_h(cma_get($property, ['CumulativeDaysOnMarket', 'CDOM'])),
        '$/AGSF' => cma_h(cma_price_per_sqft($closePrice !== '' ? $closePrice : $listPrice, $agsf)),
        '$/TFSF' => cma_h(cma_price_per_sqft($closePrice !== '' ? $closePrice : $listPrice, $tfsf)),
        'SC' => cma_h(cma_money_decimal(cma_get($property, ['ConcessionsAmount']))),
        'Garage' => cma_h(cma_get($property, ['GarageSpaces'])),
        'longitude' => cma_h(cma_get($property, ['longitude', 'Longitude'])),
        'latitude' => cma_h(cma_get($property, ['latitude', 'Latitude'])),
        default => '',
    };
}

$rows = [
    'Photo',
    'Status',
    'MLS #',
    'Street Address',
    'Municipality',
    'SubType',
    'Bed',
    'Bath',
    'AGSF',
    'TFSF',
    'Built',
    'Orig Price',
    'List Price',
    'Sale Price',
    'SP%LP',
    'Date',
    'DOM',
    'CDOM',
    '$/AGSF',
    '$/TFSF',
    'SC',
    'Garage',
    'longitude',
    'latitude',
];

$extraRows = [];

if (!empty($subject['extra_rows']) && is_array($subject['extra_rows'])) {
    foreach ($subject['extra_rows'] as $extraRow) {
        if (empty($extraRow['label'])) {
            continue;
        }

        $values = [];

        if (!empty($extraRow['values']) && is_array($extraRow['values'])) {
            foreach ($extraRow['values'] as $value) {
                $values[] = (string)$value;
            }
        } elseif (isset($extraRow['value'])) {
            // Backward compatibility with the first extra-row version.
            $values[] = (string)$extraRow['value'];
        }

        $extraRows[] = [
            'label'  => (string)$extraRow['label'],
            'values' => $values,
        ];
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CMA Comparison</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background: #f6f7fb;
        }

        .cma-wrap {
            background: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 8px 22px rgba(0,0,0,.08);
        }

        .cma-topbar {
            display: flex;
            justify-content: space-between;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
            margin-bottom: 16px;
        }

        .button {
            background: #01377d;
            color: #fff;
            border: 0;
            padding: 9px 14px;
            border-radius: 6px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }

        .cma-scroll {
            max-height: 78vh;
            overflow: auto;
            border: 1px solid #d8dbe4;
        }

        table.cma-table {
            border-collapse: separate;
            border-spacing: 0;
            min-width: 1200px;
            width: max-content;
            background: #fff;
        }

        .cma-table th,
        .cma-table td {
            border-right: 1px solid #d8dbe4;
            border-bottom: 1px solid #d8dbe4;
            padding: 8px 10px;
            min-width: 150px;
            max-width: 230px;
            vertical-align: top;
            font-size: 14px;
            background: #fff;
        }

        .cma-table thead th {
            position: sticky;
            top: 0;
            z-index: 4;
            background: #01377d;
            color: #fff;
            text-align: left;
        }

        .cma-table .row-label {
            position: sticky;
            left: 0;
            z-index: 3;
            min-width: 150px;
            background: #eef2f7;
            color: #111;
            font-weight: bold;
        }

        .cma-table thead .row-label {
            z-index: 5;
            background: #01377d;
            color: #fff;
        }

        .subject-col {
            background: #fffceb !important;
            font-weight: bold;
        }

        .hidden-map-row {
            display: none;
        }

        .cma-photo {
            width: 160px;
            height: 110px;
            object-fit: cover;
            border-radius: 6px;
            background: #eee;
        }

        .empty {
            padding: 20px;
            background: #fff3cd;
            border: 1px solid #ffe29b;
            border-radius: 8px;
        }

        @media print {
            body {
                background: #fff;
                margin: 0;
            }

            .cma-topbar {
                display: none;
            }

            .cma-scroll {
                max-height: none;
                overflow: visible;
            }
        }
    </style>
</head>
<body>

<div class="cma-wrap">
    <div class="cma-topbar">
        <div>
            <h1>CMA Comparison</h1>
            <div><?php echo count($properties); ?> comparable properties loaded.</div>
        </div>
        <div>
            <a class="button" href="cma-listings.php">Edit MLS List</a>
            <a class="button" href="cma-subject.php">Edit Subject</a>
        </div>
    </div>

    <?php if (empty($properties) && empty($subject)): ?>
        <div class="empty">
            No CMA data yet. Start by adding MLS numbers and subject property information.
        </div>
    <?php else: ?>

        <div class="cma-scroll">
            <table class="cma-table">
                <thead>
                    <tr>
                        <th class="row-label">Feature</th>
                        <th class="subject-col">Subject Property</th>

                        <?php foreach ($properties as $i => $property): ?>
                            <th>
                                Comp <?php echo $i + 1; ?><br>
                                <?php echo cma_h(cma_address($property)); ?>
                            </th>
                        <?php endforeach; ?>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($rows as $rowKey): ?>
                        <?php
                        $hiddenClass = in_array($rowKey, ['longitude', 'latitude'], true)
                            ? ' hidden-map-row'
                            : '';
                        ?>
                        <tr class="<?php echo $hiddenClass; ?>">
                            <td class="row-label"><?php echo cma_h($rowKey); ?></td>
                            <td class="subject-col"><?php echo cma_subject_value($rowKey, $subject); ?></td>

                            <?php foreach ($properties as $property): ?>
                                <td
                                    data-listing-id="<?php echo cma_h(cma_get($property, ['ListingId'])); ?>"
                                    data-lat="<?php echo cma_h(cma_get($property, ['latitude', 'Latitude'])); ?>"
                                    data-lng="<?php echo cma_h(cma_get($property, ['longitude', 'Longitude'])); ?>"
                                >
                                    <?php echo cma_comp_value($rowKey, $property, $thumbnailMap); ?>
                                </td>
                            <?php endforeach; ?>
                        </tr>
                    <?php endforeach; ?>

                    <?php if (!empty($extraRows)): ?>
                        <?php foreach ($extraRows as $extraRow): ?>
                            <tr>
                                <td class="row-label"><?php echo cma_h($extraRow['label']); ?></td>

                                <td class="subject-col">
                                    <?php echo cma_h($extraRow['values'][0] ?? ''); ?>
                                </td>

                                <?php foreach ($properties as $i => $property): ?>
                                    <td>
                                        <?php echo cma_h($extraRow['values'][$i + 1] ?? ''); ?>
                                    </td>
                                <?php endforeach; ?>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

    <?php endif; ?>
</div>

</body>
</html>
