<?php
/**
 * Report definition builder. Create / edit a report's metadata,
 * input columns, and output specs in one screen.
 */
require_once __DIR__ . '/../includes/config.php';
$me = require_login('internal');

$pdo    = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';
$id     = (int) ($_GET['id'] ?? $_POST['id'] ?? 0);

/* ---------------------- POST handlers ---------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();

    if ($action === 'save_meta') {
        $data = [
            'process_id'         => (int) input('process_id'),
            'name'               => trim((string) input('name')),
            'code'               => strtoupper(trim((string) input('code'))),
            'description'        => trim((string) input('description')) ?: null,
            'report_type'        => in_array(input('report_type'), ['standard','custom'], true) ? input('report_type') : 'standard',
            'handler'            => ((string) input('handler') === 'collection_dashboard') ? 'collection_dashboard' : null,
            'upload_strategy'    => in_array(input('upload_strategy'), ['append','replace_all','replace_by_period','upsert'], true) ? input('upload_strategy') : 'replace_all',
            'period_column'      => trim((string) input('period_column')) ?: null,
            'unique_key_columns' => json_encode(array_filter(array_map('trim', explode(',', (string) input('unique_key_columns'))))),
            'status'             => in_array(input('status'), ['draft','active','archived'], true) ? input('status') : 'draft',
        ];

        $errors = [];
        if (!$data['process_id']) $errors[] = 'Process is required.';
        if ($data['name'] === '') $errors[] = 'Name is required.';
        if (!preg_match('/^[A-Z0-9_-]{2,80}$/', $data['code'])) $errors[] = 'Code must be 2-80 chars: A-Z 0-9 _ -';
        if ($errors) { foreach ($errors as $e) flash('error', $e); redirect('/admin/report-builder.php?action=' . ($id ? 'edit&id=' . $id : 'new')); }

        if ($id) {
            $before = $pdo->query("SELECT * FROM reports WHERE id=$id")->fetch();
            $pdo->prepare('UPDATE reports SET process_id=?, name=?, code=?, description=?, report_type=?, handler=?,
                upload_strategy=?, period_column=?, unique_key_columns=?, status=?, updated_at=NOW() WHERE id=?')
                ->execute([$data['process_id'], $data['name'], $data['code'], $data['description'], $data['report_type'], $data['handler'],
                           $data['upload_strategy'], $data['period_column'], $data['unique_key_columns'], $data['status'], $id]);
            audit_log('report.update', 'report', $id, $before, $data);
        } else {
            $pdo->prepare('INSERT INTO reports
                (process_id, name, code, description, report_type, handler, upload_strategy, period_column,
                 unique_key_columns, status, created_by, created_at, updated_at)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())')
                ->execute([$data['process_id'], $data['name'], $data['code'], $data['description'], $data['report_type'], $data['handler'],
                           $data['upload_strategy'], $data['period_column'], $data['unique_key_columns'], $data['status'], $me['id']]);
            $id = (int) $pdo->lastInsertId();
            audit_log('report.create', 'report', $id, null, $data);
        }
        flash('success', 'Report metadata saved.');
        // Collection Dashboard reports don't use builder columns/outputs — go straight
        // to the dashboard so the user can upload Collection Raw + Facility Mapping.
        if ($data['handler'] === 'collection_dashboard') {
            redirect('/admin/collection.php?id=' . $id);
        }
        redirect('/admin/report-builder.php?action=edit&id=' . $id . '&tab=columns');
    }

    if ($action === 'save_column') {
        $reportId = (int) input('report_id');
        if (!$reportId) { flash('error','Report id missing.'); redirect('/admin/report-builder.php'); }
        $colId = (int) input('col_id');
        $row = [
            'col_order'       => (int) input('col_order') ?: 1,
            'col_name'        => preg_replace('/[^a-z0-9_]/', '_', strtolower(trim((string) input('col_name')))),
            'col_label'       => trim((string) input('col_label')),
            'data_type'       => in_array(input('data_type'), ['text','int','decimal','date','datetime','bool'], true) ? input('data_type') : 'text',
            'is_required'     => input('is_required')     ? 1 : 0,
            'is_groupable'    => input('is_groupable')    ? 1 : 0,
            'is_aggregatable' => input('is_aggregatable') ? 1 : 0,
            'default_agg'     => in_array(input('default_agg'), ['sum','count','avg','min','max','none'], true) ? input('default_agg') : 'none',
            'is_period_col'   => input('is_period_col')   ? 1 : 0,
            'is_key_col'      => input('is_key_col')      ? 1 : 0,
            'is_displayed'    => input('is_displayed')    ? 1 : 0,
        ];
        if ($colId) {
            $pdo->prepare('UPDATE report_columns SET col_order=?, col_name=?, col_label=?, data_type=?,
                is_required=?, is_groupable=?, is_aggregatable=?, default_agg=?,
                is_period_col=?, is_key_col=?, is_displayed=?, updated_at=NOW() WHERE id=?')
                ->execute([$row['col_order'], $row['col_name'], $row['col_label'], $row['data_type'],
                           $row['is_required'], $row['is_groupable'], $row['is_aggregatable'], $row['default_agg'],
                           $row['is_period_col'], $row['is_key_col'], $row['is_displayed'], $colId]);
        } else {
            $pdo->prepare('INSERT INTO report_columns (report_id, col_order, col_name, col_label, data_type,
                is_required, is_groupable, is_aggregatable, default_agg, is_period_col, is_key_col, is_displayed,
                created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())')
                ->execute([$reportId, $row['col_order'], $row['col_name'], $row['col_label'], $row['data_type'],
                           $row['is_required'], $row['is_groupable'], $row['is_aggregatable'], $row['default_agg'],
                           $row['is_period_col'], $row['is_key_col'], $row['is_displayed']]);
        }
        audit_log($colId ? 'report.column.update' : 'report.column.create', 'report_column', $colId ?: null, null, $row + ['report_id'=>$reportId]);
        flash('success', 'Column saved.');
        redirect('/admin/report-builder.php?action=edit&id=' . $reportId . '&tab=columns');
    }

    if ($action === 'delete_column') {
        $colId = (int) input('col_id');
        $reportId = (int) input('report_id');
        $pdo->prepare('DELETE FROM report_columns WHERE id=? AND report_id=?')->execute([$colId, $reportId]);
        audit_log('report.column.delete', 'report_column', $colId);
        flash('success', 'Column removed.');
        redirect('/admin/report-builder.php?action=edit&id=' . $reportId . '&tab=columns');
    }

    if ($action === 'save_output') {
        $reportId = (int) input('report_id');
        $outId = (int) input('out_id');
        $row = [
            'output_name'   => trim((string) input('output_name')),
            'output_type'   => in_array(input('output_type'), ['dashboard','summary','pivot','chart','kpi','detail'], true) ? input('output_type') : 'summary',
            'group_by_cols' => json_encode(array_values(array_filter(array_map('trim', explode(',', (string) input('group_by_cols')))))),
            'agg_cols'      => trim((string) input('agg_cols')) ?: '[]',
            'filter_rules'  => trim((string) input('filter_rules')) ?: '{}',
            'sort_rules'    => trim((string) input('sort_rules'))   ?: '[]',
            'chart_config'  => trim((string) input('chart_config')) ?: '{}',
            'display_order' => (int) input('display_order'),
        ];
        // Validate JSON inputs
        foreach (['agg_cols','filter_rules','sort_rules','chart_config'] as $k) {
            if (json_decode($row[$k], true) === null && $row[$k] !== 'null') {
                flash('error', "$k must be valid JSON.");
                redirect('/admin/report-builder.php?action=edit&id=' . $reportId . '&tab=outputs');
            }
        }
        if ($outId) {
            $pdo->prepare('UPDATE report_outputs SET output_name=?, output_type=?, group_by_cols=?, agg_cols=?,
                filter_rules=?, sort_rules=?, chart_config=?, display_order=?, updated_at=NOW() WHERE id=?')
                ->execute([$row['output_name'], $row['output_type'], $row['group_by_cols'], $row['agg_cols'],
                           $row['filter_rules'], $row['sort_rules'], $row['chart_config'], $row['display_order'], $outId]);
        } else {
            $pdo->prepare('INSERT INTO report_outputs (report_id, output_name, output_type, group_by_cols, agg_cols,
                filter_rules, sort_rules, chart_config, display_order, created_at, updated_at)
                VALUES (?,?,?,?,?,?,?,?,?,NOW(),NOW())')
                ->execute([$reportId, $row['output_name'], $row['output_type'], $row['group_by_cols'], $row['agg_cols'],
                           $row['filter_rules'], $row['sort_rules'], $row['chart_config'], $row['display_order']]);
        }
        flash('success', 'Output saved.');
        redirect('/admin/report-builder.php?action=edit&id=' . $reportId . '&tab=outputs');
    }

    if ($action === 'delete_output') {
        $outId = (int) input('out_id');
        $reportId = (int) input('report_id');
        $pdo->prepare('DELETE FROM report_outputs WHERE id=? AND report_id=?')->execute([$outId, $reportId]);
        flash('success', 'Output removed.');
        redirect('/admin/report-builder.php?action=edit&id=' . $reportId . '&tab=outputs');
    }
}

$pageTitle = 'Report builder';
require __DIR__ . '/../includes/header.php';

$processes = $pdo->query("SELECT p.id, p.name AS pname, c.name AS cname, v.name AS vname
    FROM processes p JOIN clients c ON c.id = p.client_id JOIN verticals v ON v.id = c.vertical_id
    WHERE p.deleted_at IS NULL ORDER BY v.name, c.name, p.name")->fetchAll();

if ($action === 'list') {
    $reports = $pdo->query("SELECT r.*, p.name AS process_name, c.name AS client_name,
        (SELECT COUNT(*) FROM report_columns rc WHERE rc.report_id = r.id) AS col_count,
        (SELECT COUNT(*) FROM report_outputs ro WHERE ro.report_id = r.id) AS out_count
        FROM reports r JOIN processes p ON p.id = r.process_id JOIN clients c ON c.id = p.client_id
        WHERE r.deleted_at IS NULL ORDER BY r.updated_at DESC")->fetchAll();
?>
<div class="page-header"><div class="container-xl">
    <div class="row align-items-center">
        <div class="col"><h2 class="page-title">Report builder</h2><div class="text-secondary">Create and edit report definitions.</div></div>
        <div class="col-auto"><a href="<?= e(url('/admin/report-builder.php?action=new')) ?>" class="btn btn-primary"><i class="ti ti-plus me-1"></i>New report</a></div>
    </div>
</div></div>
<div class="page-body"><div class="container-xl"><div class="card">
    <table class="table table-vcenter card-table">
        <thead><tr><th>Name</th><th>Code</th><th>Process</th><th>Mode</th><th>Cols</th><th>Outputs</th><th>Status</th><th></th></tr></thead>
        <tbody>
        <?php foreach ($reports as $r): ?>
            <tr>
                <td><strong><?= e($r['name']) ?></strong>
                    <?php if (($r['handler'] ?? '') === 'collection_dashboard'): ?>
                        <span class="badge bg-azure-lt ms-1" title="Uses the Collection Dashboard viewer"><i class="ti ti-layout-dashboard me-1"></i>Collection Dashboard</span>
                    <?php endif; ?>
                </td>
                <td><code><?= e($r['code']) ?></code></td>
                <td class="small"><?= e($r['client_name']) ?> &raquo; <?= e($r['process_name']) ?></td>
                <td><span class="badge bg-secondary-lt"><?= e($r['upload_strategy']) ?></span></td>
                <td><?= (int) $r['col_count'] ?></td><td><?= (int) $r['out_count'] ?></td>
                <td><span class="badge bg-<?= $r['status']==='active'?'success':($r['status']==='draft'?'yellow':'secondary') ?>-lt"><?= e($r['status']) ?></span></td>
                <td>
                    <div class="btn-list flex-nowrap">
                        <?php $isColl = (($r['handler'] ?? '') === 'collection_dashboard'); ?>
                        <a href="<?= e(url(($isColl ? '/admin/collection.php?id=' : '/admin/report-view.php?id=').$r['id'])) ?>" class="btn btn-sm btn-primary" title="Open"><i class="ti ti-chart-pie-2"></i> View</a>
                        <a href="<?= e(url(($isColl ? '/admin/upload-collection.php?id=' : '/admin/upload.php?report_id=').$r['id'])) ?>" class="btn btn-sm btn-outline-primary" title="Upload data"><i class="ti ti-upload"></i></a>
                        <a href="<?= e(url('/admin/report-builder.php?action=edit&id='.$r['id'])) ?>" class="btn btn-sm" title="Edit definition"><i class="ti ti-edit"></i></a>
                    </div>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div></div></div>
<?php
} else {
    // edit / new
    $tab = $_GET['tab'] ?? 'meta';
    $report = ['id'=>0,'process_id'=>0,'name'=>'','code'=>'','description'=>'','report_type'=>'standard','handler'=>null,
               'upload_strategy'=>'replace_all','period_column'=>'','unique_key_columns'=>'[]','status'=>'draft'];
    if ($action === 'edit' && $id) {
        $stmt = $pdo->prepare('SELECT * FROM reports WHERE id=? AND deleted_at IS NULL');
        $stmt->execute([$id]);
        $report = $stmt->fetch() ?: $report;
        if (!$report['id']) { flash('error','Report not found.'); redirect('/admin/report-builder.php'); }
    }
?>
<div class="page-header"><div class="container-xl">
    <a href="<?= e(url('/admin/report-builder.php')) ?>" class="text-secondary"><i class="ti ti-chevron-left"></i> All reports</a>
    <h2 class="page-title"><?= $report['id'] ? e($report['name']) : 'New report' ?></h2>
</div></div>
<div class="page-body"><div class="container-xl">
    <?php if (($report['handler'] ?? '') === 'collection_dashboard' && $report['id']): ?>
    <div class="alert alert-info d-flex align-items-center mb-3">
        <i class="ti ti-layout-dashboard me-2 fs-2"></i>
        <div class="flex-fill">
            <strong>This report uses the Collection Dashboard viewer.</strong>
            The <em>Input columns</em> and <em>Outputs</em> tabs are not used &mdash; open the dashboard to upload <strong>Collection Raw</strong> + <strong>Facility Mapping</strong> data and view the analytics.
        </div>
        <a href="<?= e(url('/admin/collection.php?id=' . $report['id'])) ?>" class="btn btn-primary ms-3"><i class="ti ti-external-link me-1"></i>Open dashboard</a>
    </div>
    <?php endif; ?>
    <ul class="nav nav-tabs mb-3">
        <li class="nav-item"><a class="nav-link <?= $tab==='meta'?'active':'' ?>" href="?action=<?= $report['id']?'edit&id='.$report['id']:'new' ?>&tab=meta">1. Metadata</a></li>
        <li class="nav-item"><a class="nav-link <?= $tab==='columns'?'active':'' ?> <?= !$report['id']?'disabled':'' ?>" href="?action=edit&id=<?= $report['id'] ?>&tab=columns">2. Input columns</a></li>
        <li class="nav-item"><a class="nav-link <?= $tab==='outputs'?'active':'' ?> <?= !$report['id']?'disabled':'' ?>" href="?action=edit&id=<?= $report['id'] ?>&tab=outputs">3. Outputs</a></li>
    </ul>

    <?php if ($tab === 'meta'): ?>
        <form method="POST" action="<?= e(url('/admin/report-builder.php?action=save_meta')) ?>" class="card">
            <?= csrf_field() ?>
            <input type="hidden" name="id" value="<?= (int) $report['id'] ?>">
            <div class="card-body row g-3">
                <div class="col-md-6">
                    <label class="form-label required">Process</label>
                    <select name="process_id" class="form-select" required>
                        <option value="">-- choose --</option>
                        <?php foreach ($processes as $p): ?>
                            <option value="<?= (int)$p['id'] ?>" <?= $report['process_id']==$p['id']?'selected':'' ?>>
                                <?= e($p['vname']) ?> &raquo; <?= e($p['cname']) ?> &raquo; <?= e($p['pname']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6"><label class="form-label required">Name</label><input type="text" name="name" class="form-control" required value="<?= e($report['name']) ?>"></div>
                <div class="col-md-3"><label class="form-label required">Code</label><input type="text" name="code" class="form-control text-uppercase" required value="<?= e($report['code']) ?>"></div>
                <div class="col-md-3"><label class="form-label">Type</label>
                    <select name="report_type" class="form-select">
                        <option value="standard" <?= $report['report_type']==='standard'?'selected':'' ?>>standard</option>
                        <option value="custom"   <?= $report['report_type']==='custom'  ?'selected':'' ?>>custom (PHP class)</option>
                    </select></div>
                <div class="col-md-3"><label class="form-label">Report viewer</label>
                    <select name="handler" class="form-select">
                        <option value="" <?= empty($report['handler'])?'selected':'' ?>>Generic (builder output)</option>
                        <option value="collection_dashboard" <?= ($report['handler']??'')==='collection_dashboard'?'selected':'' ?>>Collection Dashboard</option>
                    </select></div>
                <div class="col-12">
                    <div class="small text-secondary"><i class="ti ti-info-circle me-1"></i>
                        <strong>Report viewer</strong> &mdash; choose <em>Collection Dashboard</em> for data in the <strong>Collection Raw + Facility Mapping</strong> format (PY-Medical SNF style).
                        It turns this report into the full multi-tab analytics dashboard and shows the <strong>Replace Collection</strong> / <strong>Mapping</strong> upload buttons; the Input columns &amp; Outputs tabs below are not used.
                        Leave as <em>Generic</em> for a builder-defined table report.
                    </div>
                </div>
                <div class="col-md-3"><label class="form-label">Upload mode</label>
                    <select name="upload_strategy" class="form-select">
                        <?php foreach (['append','replace_all','replace_by_period','upsert'] as $m): ?>
                            <option value="<?= $m ?>" <?= $report['upload_strategy']===$m?'selected':'' ?>><?= $m ?></option>
                        <?php endforeach; ?>
                    </select></div>
                <div class="col-md-3"><label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <?php foreach (['draft','active','archived'] as $s): ?>
                            <option value="<?= $s ?>" <?= $report['status']===$s?'selected':'' ?>><?= $s ?></option>
                        <?php endforeach; ?>
                    </select></div>
                <div class="col-md-6"><label class="form-label">Period column (label)</label><input type="text" name="period_column" class="form-control" value="<?= e($report['period_column']) ?>" placeholder="DOS"></div>
                <div class="col-md-6"><label class="form-label">Unique key columns (comma sep labels)</label><input type="text" name="unique_key_columns" class="form-control" value="<?= e(implode(', ', json_decode($report['unique_key_columns'] ?: '[]', true) ?: [])) ?>" placeholder="Visit ID, DOS, Charge Code"></div>
                <div class="col-12"><label class="form-label">Description</label><textarea name="description" class="form-control" rows="2"><?= e($report['description']) ?></textarea></div>
            </div>
            <div class="card-footer"><button class="btn btn-primary"><i class="ti ti-check me-1"></i>Save metadata</button></div>
        </form>
    <?php elseif ($tab === 'columns'): ?>
        <?php
        $cols = $pdo->prepare('SELECT * FROM report_columns WHERE report_id=? ORDER BY col_order');
        $cols->execute([$id]); $cols = $cols->fetchAll();
        $editCol = null;
        if ($cid = (int)($_GET['cid'] ?? 0)) {
            $st = $pdo->prepare('SELECT * FROM report_columns WHERE id=? AND report_id=?');
            $st->execute([$cid, $id]); $editCol = $st->fetch();
        }
        ?>
        <div class="row">
            <div class="col-md-7">
                <div class="card">
                    <div class="card-header"><h3 class="card-title"><?= count($cols) ?> input columns</h3></div>
                    <div class="table-responsive"><table class="table table-vcenter card-table table-sm">
                        <thead><tr><th>#</th><th>Name</th><th>Label</th><th>Type</th><th>Flags</th><th></th></tr></thead><tbody>
                        <?php foreach ($cols as $c): ?>
                            <tr>
                                <td><?= (int)$c['col_order'] ?></td>
                                <td><code><?= e($c['col_name']) ?></code></td>
                                <td><?= e($c['col_label']) ?></td>
                                <td><span class="badge bg-secondary-lt"><?= e($c['data_type']) ?></span></td>
                                <td class="small">
                                    <?php $f = []; if ($c['is_required']) $f[]='req';
                                    if ($c['is_period_col']) $f[]='period'; if ($c['is_key_col']) $f[]='key';
                                    if ($c['is_groupable']) $f[]='grp'; if ($c['is_aggregatable']) $f[]=$c['default_agg']; echo e(implode(' ', $f)); ?>
                                </td>
                                <td>
                                    <a href="?action=edit&id=<?= $id ?>&tab=columns&cid=<?= $c['id'] ?>" class="btn btn-sm"><i class="ti ti-edit"></i></a>
                                    <form method="POST" action="?action=delete_column" style="display:inline" onsubmit="return confirm('Delete column?');">
                                        <?= csrf_field() ?><input type="hidden" name="col_id" value="<?= $c['id'] ?>"><input type="hidden" name="report_id" value="<?= $id ?>">
                                        <button class="btn btn-sm btn-ghost-danger"><i class="ti ti-trash"></i></button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody></table></div>
                </div>
            </div>
            <div class="col-md-5">
                <div class="card">
                    <div class="card-header"><h3 class="card-title"><?= $editCol ? 'Edit column' : 'Add column' ?></h3></div>
                    <form method="POST" action="?action=save_column" class="card-body">
                        <?= csrf_field() ?>
                        <input type="hidden" name="report_id" value="<?= $id ?>">
                        <input type="hidden" name="col_id" value="<?= $editCol['id'] ?? '' ?>">
                        <div class="row g-2">
                            <div class="col-3"><label class="form-label">Order</label><input type="number" name="col_order" class="form-control" value="<?= e($editCol['col_order'] ?? count($cols)+1) ?>"></div>
                            <div class="col-9"><label class="form-label required">Label</label><input type="text" name="col_label" class="form-control" required value="<?= e($editCol['col_label'] ?? '') ?>"></div>
                            <div class="col-6"><label class="form-label required">Field name</label><input type="text" name="col_name" class="form-control" required value="<?= e($editCol['col_name'] ?? '') ?>" placeholder="snake_case"></div>
                            <div class="col-6"><label class="form-label">Data type</label>
                                <select name="data_type" class="form-select">
                                    <?php foreach (['text','int','decimal','date','datetime','bool'] as $t): ?>
                                        <option value="<?= $t ?>" <?= ($editCol['data_type'] ?? 'text')===$t?'selected':'' ?>><?= $t ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-6"><label class="form-label">Default agg</label>
                                <select name="default_agg" class="form-select">
                                    <?php foreach (['none','sum','count','avg','min','max'] as $a): ?>
                                        <option value="<?= $a ?>" <?= ($editCol['default_agg'] ?? 'none')===$a?'selected':'' ?>><?= $a ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-6 mt-3">
                                <label class="form-check"><input type="checkbox" name="is_required" value="1" <?= !empty($editCol['is_required'])?'checked':'' ?> class="form-check-input"><span class="form-check-label">Required</span></label>
                                <label class="form-check"><input type="checkbox" name="is_groupable" value="1" <?= !empty($editCol['is_groupable'])?'checked':'' ?> class="form-check-input"><span class="form-check-label">Groupable</span></label>
                                <label class="form-check"><input type="checkbox" name="is_aggregatable" value="1" <?= !empty($editCol['is_aggregatable'])?'checked':'' ?> class="form-check-input"><span class="form-check-label">Aggregatable</span></label>
                            </div>
                            <div class="col-6 mt-3">
                                <label class="form-check"><input type="checkbox" name="is_period_col" value="1" <?= !empty($editCol['is_period_col'])?'checked':'' ?> class="form-check-input"><span class="form-check-label">Period column</span></label>
                                <label class="form-check"><input type="checkbox" name="is_key_col" value="1" <?= !empty($editCol['is_key_col'])?'checked':'' ?> class="form-check-input"><span class="form-check-label">Key column</span></label>
                                <label class="form-check"><input type="checkbox" name="is_displayed" value="1" <?= !isset($editCol['is_displayed']) || $editCol['is_displayed']?'checked':'' ?> class="form-check-input"><span class="form-check-label">Displayed</span></label>
                            </div>
                        </div>
                        <div class="form-footer"><button class="btn btn-primary w-100"><i class="ti ti-check me-1"></i>Save column</button></div>
                    </form>
                </div>
            </div>
        </div>
    <?php elseif ($tab === 'outputs'): ?>
        <?php
        $outs = $pdo->prepare('SELECT * FROM report_outputs WHERE report_id=? ORDER BY display_order, id');
        $outs->execute([$id]); $outs = $outs->fetchAll();
        $editOut = null;
        if ($oid = (int)($_GET['oid'] ?? 0)) {
            $st = $pdo->prepare('SELECT * FROM report_outputs WHERE id=? AND report_id=?');
            $st->execute([$oid, $id]); $editOut = $st->fetch();
        }
        ?>
        <div class="row"><div class="col-md-6">
            <div class="card"><div class="card-header"><h3 class="card-title"><?= count($outs) ?> outputs</h3></div>
                <div class="table-responsive"><table class="table card-table"><thead><tr><th>#</th><th>Name</th><th>Type</th><th></th></tr></thead><tbody>
                <?php foreach ($outs as $o): ?>
                    <tr><td><?= (int)$o['display_order'] ?></td><td><strong><?= e($o['output_name']) ?></strong></td>
                        <td><span class="badge bg-blue-lt"><?= e($o['output_type']) ?></span></td>
                        <td>
                            <a href="?action=edit&id=<?= $id ?>&tab=outputs&oid=<?= $o['id'] ?>" class="btn btn-sm"><i class="ti ti-edit"></i></a>
                            <form method="POST" action="?action=delete_output" style="display:inline" onsubmit="return confirm('Delete output?');">
                                <?= csrf_field() ?><input type="hidden" name="out_id" value="<?= $o['id'] ?>"><input type="hidden" name="report_id" value="<?= $id ?>">
                                <button class="btn btn-sm btn-ghost-danger"><i class="ti ti-trash"></i></button>
                            </form>
                        </td></tr>
                <?php endforeach; ?>
                </tbody></table></div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card"><div class="card-header"><h3 class="card-title"><?= $editOut ? 'Edit output' : 'Add output' ?></h3></div>
                <form method="POST" action="?action=save_output" class="card-body">
                    <?= csrf_field() ?>
                    <input type="hidden" name="report_id" value="<?= $id ?>">
                    <input type="hidden" name="out_id" value="<?= $editOut['id'] ?? '' ?>">
                    <div class="row g-2">
                        <div class="col-md-8"><label class="form-label required">Name</label><input type="text" name="output_name" class="form-control" required value="<?= e($editOut['output_name'] ?? '') ?>"></div>
                        <div class="col-md-2"><label class="form-label">Order</label><input type="number" name="display_order" class="form-control" value="<?= e($editOut['display_order'] ?? count($outs)+1) ?>"></div>
                        <div class="col-md-2"><label class="form-label">Type</label>
                            <select name="output_type" class="form-select">
                                <?php foreach (['dashboard','summary','pivot','chart','kpi','detail'] as $t): ?>
                                    <option value="<?= $t ?>" <?= ($editOut['output_type'] ?? 'summary')===$t?'selected':'' ?>><?= $t ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12"><label class="form-label">Group by columns (comma sep field names; can include synthetic dos_year/dos_month/dos_day)</label>
                            <input type="text" name="group_by_cols" class="form-control" value="<?= e(implode(', ', json_decode($editOut['group_by_cols'] ?? '[]', true) ?: [])) ?>"></div>
                        <div class="col-12"><label class="form-label">Agg cols JSON</label>
                            <textarea name="agg_cols" class="form-control" rows="3"><?= e($editOut['agg_cols'] ?? '[{"col":"charge_amount","agg":"sum","label":"Total"}]') ?></textarea></div>
                        <div class="col-12"><label class="form-label">Chart config JSON (optional)</label>
                            <textarea name="chart_config" class="form-control" rows="3"><?= e($editOut['chart_config'] ?? '{}') ?></textarea></div>
                        <input type="hidden" name="filter_rules" value="{}">
                        <input type="hidden" name="sort_rules" value="[]">
                    </div>
                    <div class="form-footer"><button class="btn btn-primary w-100"><i class="ti ti-check me-1"></i>Save output</button></div>
                </form>
            </div>
        </div></div>
    <?php endif; ?>
</div></div>
<?php
}
require __DIR__ . '/../includes/footer.php';
