<?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_comp_value(string $rowKey, array $property, array $thumbnailMap): string
{
    $closePrice = $property['ClosePrice'] ?? '';
    $listPrice  = $property['ListPrice'] ?? '';
    $origPrice  = $property['OriginalListPrice'] ?? ($property['ListPrice'] ?? '');
    $afsf       = $property['LivingArea'] ?? '';
    $tfsf       = $property['NST_SQFTTotal'] ?? ($property['LivingArea'] ?? '');

    return match ($rowKey) {
        'Photo' => '<img class="cma-photo" src="' . cma_h(cma_photo_url($property, $thumbnailMap)) . '" alt="Property photo">',
        'Status' => cma_h($property['StandardStatus'] ?? ''),
        'MLS #' => cma_h(str_replace('NST', '', (string)($property['ListingId'] ?? ''))),
        'Street Address' => cma_h(cma_address($property)),
        'Municipality' => cma_h($property['City'] ?? ''),
        'SubType' => cma_h($property['PropertySubType'] ?? ''),
        'Bed' => cma_h((string)($property['BedroomsTotal'] ?? '')),
        'Bath' => cma_h((string)($property['BathroomsTotalInteger'] ?? '')),
        'AFSF' => cma_h(cma_number($afsf)),
        'TFSF' => cma_h(cma_number($tfsf)),
        'Built' => cma_h((string)($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($property['CloseDate'] ?? '')),
        'DOM' => cma_h((string)($property['DaysOnMarket'] ?? '')),
        'CDOM' => cma_h((string)($property['CumulativeDaysOnMarket'] ?? ($property['CDOM'] ?? ''))),
        '$/AFSF' => cma_h(cma_price_per_sqft($closePrice ?: $listPrice, $afsf)),
        '$/TFSF' => cma_h(cma_price_per_sqft($closePrice ?: $listPrice, $tfsf)),
        'SC' => cma_h((string)($property['SellingOfficeName'] ?? ($property['BuyerOfficeName'] ?? ''))),
        'Garage' => cma_h((string)($property['GarageSpaces'] ?? '')),
        'longitude' => cma_h((string)($property['Longitude'] ?? '')),
        'latitude' => cma_h((string)($property['Latitude'] ?? '')),
        default => '',
    };
}

$rows = [
    'Photo',
    'Status',
    'MLS #',
    'Street Address',
    'Municipality',
    'SubType',
    'Bed',
    'Bath',
    'AFSF',
    'TFSF',
    'Built',
    'Orig Price',
    'List Price',
    'Sale Price',
    'SP%LP',
    'Date',
    'DOM',
    'CDOM',
    '$/AFSF',
    '$/TFSF',
    'SC',
    'Garage',
    'longitude',
    'latitude',
];

function cma_subject_value(string $rowKey, array $subject): string
{
    $subjectKey = $rowKey;

    if ($rowKey === 'MLS #') {
        $subjectKey = 'MLS';
    }

    $value = $subject[$subjectKey] ?? '';

    if ($rowKey === 'Photo' && $value !== '') {
        return '<img class="cma-photo" src="' . cma_h($value) . '" alt="Subject photo">';
    }

    return cma_h((string)$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($property['ListingId'] ?? ''); ?>"
                                    data-lat="<?php echo cma_h((string)($property['Latitude'] ?? '')); ?>"
                                    data-lng="<?php echo cma_h((string)($property['Longitude'] ?? '')); ?>"
                                >
                                    <?php echo cma_comp_value($rowKey, $property, $thumbnailMap); ?>
                                </td>
                            <?php endforeach; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

    <?php endif; ?>
</div>

</body>
</html>