<?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 (isset($row[$key]) && $row[$key] !== '') {
            return (string)$row[$key];
        }
    }
    return '';
}

function cma_tfsf(array $row): string
{
    $agsf = cma_get($row, ['NST_AboveGradeSqFtTotal']);
    $below = cma_get($row, ['BelowGradeFinishedArea']);

    $agsfNum = is_numeric($agsf) ? (float)$agsf : 0;
    $belowNum = is_numeric($below) ? (float)$below : 0;

    $total = $agsfNum + $belowNum;

    return $total > 0 ? cma_number($total) : '';
}

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']);
    $belowRaw = cma_get($property, ['BelowGradeFinishedArea']);

    $agsf = is_numeric($agsfRaw) ? (float)$agsfRaw : 0;
    $below = is_numeric($belowRaw) ? (float)$belowRaw : 0;
    $tfsf = $agsf + $below;

    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(cma_number($agsf)),
        'TFSF' => cma_h(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 ?: $listPrice, $agsf)),
        '$/TFSF' => cma_h(cma_price_per_sqft($closePrice ?: $listPrice, $tfsf)),
        'SC' => cma_h(cma_money(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 => '',
    };
}

function cma_subject_value(string $rowKey, array $subject): string
{
    $subjectKey = $rowKey;

    if ($rowKey === 'MLS #') {
        $subjectKey = 'MLS';
    }

    $value = $subject[$subjectKey] ?? '';

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

    return cma_h((string)$value);
}

$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'])) {
            $extraRows[] = [
                'label' => (string)$extraRow['label'],
                'value' => (string)($extraRow['value'] ?? ''),
            ];
        }
    }
}
?>
<!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['value']); ?></td>

                                <?php foreach ($properties as $property): ?>
                                    <td></td>
                                <?php endforeach; ?>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

    <?php endif; ?>
</div>

</body>
</html>