<?php
/**
 * CSV template downloader for the three Collection-Dashboard upload formats.
 *
 *   /admin/template.php?kind=collection         Collection Raw template
 *   /admin/template.php?kind=facility-mapping   Facility Mapping template
 *
 * Templates match the exact header names the ingest engine recognises, plus
 * 2 illustrative example rows.
 */
require_once __DIR__ . '/../includes/config.php';
require_login('internal');

$kind = $_GET['kind'] ?? '';

$templates = [
    'collection' => [
        'filename' => 'collection_raw_template.csv',
        'header'   => [
            'Provider Name', 'Chart Number', 'VisitID', 'Patient Last Name', 'Patient First Name',
            'Financial Class',
            'Carrier 1 Code', 'Carrier 1 Name',
            'Carrier 2 Code', 'Carrier 2 Name',
            'Carrier 3 Code', 'Carrier 3 Name',
            'DOS', 'Charge Code Category Code', 'Charge Code', 'Charge Code Description',
            'Units', 'Charge Amount', 'Amount Allowed',
            'Primary Insurance Paid', 'Primary Insurance Payment Date',
            'Secondary Insurance Paid', 'Secondary Insurance Payment Date',
            'Tertiary Insurance Paid', 'Tertiary Insurance Payment Date',
            'Patient Payment Amount', 'Patient Payment Date',
            'WO Amount', 'WO Date',
            'Patient Balance', 'Insurance Balance',
        ],
        'sample_rows' => [
            [
                'JOHNSON,ROBERT', 'CN12345', '142799', 'BAIALA - BAIALARDO, NICHOLAS', 'KAREN',
                'MEDICARE',
                'HUM01', 'HUMANA',
                'N/A', 'N/A',
                'N/A', 'N/A',
                '3/15/2026', 'E&M', '99214', 'OFFICE O/P EST MOD 30 MIN',
                '1', '213.10', '142.81',
                '142.81', '4/2/2026',
                '0', '',
                '0', '',
                '0', '',
                '0', '',
                '0', '0',
            ],
            [
                'JOHNSON,ROBERT', 'CN67890', '98834', 'SMITH', 'ALICE',
                'MEDICARE',
                'MED274W', 'MEDICARE B NEW YORK - EMPIRE',
                'MED74W', 'NEW YORK MEDICAID',
                'N/A', 'N/A',
                '3/20/2026', 'ADD-ON', 'G2211', 'VISIT CPLX INHERENT E&M ASSOC MCS',
                '1', '26.01', '17.45',
                '17.45', '4/10/2026',
                '0', '',
                '0', '',
                '0', '',
                '0', '',
                '0', '0',
            ],
        ],
        'notes' => [
            'DOS accepts: M/D/YYYY, YYYY-MM-DD, D-MMM-YYYY (Excel serials also work).',
            'Empty / unknown carriers are accepted — the system stores them as "N/A" automatically (no need to fill blanks).',
            'Numeric columns accept "0" or empty for missing.',
            'Header order does NOT matter — the engine matches by name (case-insensitive).',
            'Only the listed columns are read; any extra columns are silently ignored.',
        ],
    ],

    'facility-mapping' => [
        'filename' => 'facility_mapping_template.csv',
        'header'   => ['Visit Number', 'Facility', 'Entry Date'],
        'sample_rows' => [
            ['142799', 'AAI - THE ARBORS ASSISTED LIVING AT ISLANDIA', '2025-03-15'],
            ['98834',  'NBM - NEW BROADVIEW MANOR', '2025-04-02'],
            ['180677', 'SANF - SANFORD MANOR', '2025-04-18'],
        ],
        'notes' => [
            '"Visit Number" and "Facility" are required; "Entry Date" is optional.',
            'Visit Number must match VisitID in the Collection Raw file (this is the join key).',
            'Entry Date (any common date format) is mapped onto the Collection data by Visit ID.',
            'Any extra columns in the file are silently ignored.',
        ],
    ],

    'deductible-mapping' => [
        'filename' => 'deductible_visits_template.csv',
        'header'   => ['Visit Number'],
        'sample_rows' => [
            ['142799'],
            ['98834'],
            ['180677'],
        ],
        'notes' => [
            'Upload ONLY the Visit Numbers that are deductible — one per row.',
            'Visit Number must match VisitID in the Collection Raw file (this is the join key).',
            'Charge amounts are read from the Collection data — do not include them here.',
            'Re-uploading fully replaces the list: a visit dropped from the file is no longer flagged.',
            'Any extra columns in the file are silently ignored.',
        ],
    ],
];

if (!isset($templates[$kind])) {
    http_response_code(400);
    exit('Unknown template kind. Use ?kind=collection | facility-mapping');
}

$tpl = $templates[$kind];

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $tpl['filename'] . '"');
header('Cache-Control: no-cache, no-store, must-revalidate');

$out = fopen('php://output', 'w');
// UTF-8 BOM so Excel opens it correctly
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, $tpl['header']);
foreach ($tpl['sample_rows'] as $row) {
    fputcsv($out, $row);
}
// Trailing notes as commented rows (Excel shows them as a final block)
fputcsv($out, []);
foreach ($tpl['notes'] as $n) {
    fputcsv($out, ['# ' . $n]);
}
fclose($out);
