<?php
$lang = Lang::current();
$reportName = $report['report_name_' . $lang] ?: $report['report_name_en'];
$columns = json_decode($report['default_columns'] ?? '[]', true) ?: [];
$chartType = $report['chart_type'] ?? null;
$chartConfig = json_decode($report['chart_config'] ?? '{}', true) ?: [];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="mb-1"><?= e($reportName) ?></h4>
        <p class="text-muted mb-0"><?= e($report['description_' . $lang] ?: $report['description_en'] ?: '') ?></p>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-warning btn-sm" id="btn-save-favorite" title="Save as Favorite"><i class="fas fa-star me-1"></i>Favorite</button>
        <a href="/reports" class="btn btn-outline-secondary btn-sm"><i class="fas fa-arrow-left me-1"></i><?= lang('common.back') ?></a>
    </div>
</div>

<!-- Parameters -->
<?php if (!empty($parameters)): ?>
<div class="card mb-4">
    <div class="card-header"><h6 class="mb-0"><i class="fas fa-filter me-2"></i><?= lang('reports.parameters') ?></h6></div>
    <div class="card-body">
        <form id="report-params-form">
            <div class="row g-3">
                <?php foreach ($parameters as $param):
                    $pName = $param['parameter_name'];
                    $pLabel = $param['parameter_label_' . $lang] ?: $param['parameter_label_en'];
                    $pType = $param['parameter_type'];
                    $pOpts = json_decode($param['options'] ?? '[]', true) ?: [];
                    $pDefault = $param['default_value'] ?? '';
                ?>
                <div class="col-md-3">
                    <label class="form-label"><?= e($pLabel) ?></label>
                    <?php if ($pType === 'select'): ?>
                        <select name="<?= e($pName) ?>" class="form-select form-select-sm">
                            <?php if (isset($pOpts['source'])): ?>
                                <option value="">-- All --</option>
                            <?php else: ?>
                                <?php foreach ($pOpts as $opt): ?>
                                <option value="<?= e($opt['value'] ?? '') ?>"><?= e($opt['label'] ?? $opt['value'] ?? '') ?></option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    <?php elseif ($pType === 'date'): ?>
                        <input type="date" name="<?= e($pName) ?>" class="form-control form-control-sm" value="<?= e($pDefault) ?>">
                    <?php elseif ($pType === 'number'): ?>
                        <input type="number" name="<?= e($pName) ?>" class="form-control form-control-sm" value="<?= e($pDefault) ?>">
                    <?php elseif ($pType === 'boolean'): ?>
                        <select name="<?= e($pName) ?>" class="form-select form-select-sm">
                            <option value="">--</option>
                            <option value="1">Yes</option>
                            <option value="0">No</option>
                        </select>
                    <?php else: ?>
                        <input type="text" name="<?= e($pName) ?>" class="form-control form-control-sm" value="<?= e($pDefault) ?>">
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary btn-sm me-2"><i class="fas fa-play me-1"></i><?= lang('reports.generate') ?></button>
                    <button type="reset" class="btn btn-outline-secondary btn-sm"><i class="fas fa-redo me-1"></i>Reset</button>
                </div>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- Chart Area -->
<?php if ($chartType): ?>
<div class="card mb-4" id="chart-card" style="display:none">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h6 class="mb-0"><i class="fas fa-chart-pie me-2"></i>Chart</h6>
        <button class="btn btn-sm btn-outline-secondary" id="toggle-chart"><i class="fas fa-eye-slash"></i></button>
    </div>
    <div class="card-body">
        <div style="max-height:350px;position:relative">
            <canvas id="report-chart"></canvas>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Export Buttons -->
<div class="mb-3 d-flex gap-2">
    <button class="btn btn-sm btn-outline-success" id="btn-export-csv"><i class="fas fa-file-csv me-1"></i>CSV</button>
    <button class="btn btn-sm btn-outline-primary" id="btn-export-excel"><i class="fas fa-file-excel me-1"></i>Excel</button>
    <button class="btn btn-sm btn-outline-danger" id="btn-export-print"><i class="fas fa-print me-1"></i>Print</button>
</div>

<!-- Results Table -->
<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table id="report-results-table" class="table table-striped table-hover w-100">
                <thead>
                    <tr>
                        <?php foreach ($columns as $col): ?>
                        <th><?= e($col['label'] ?? $col['key'] ?? '') ?></th>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
</div>

<!-- Favorite Modal -->
<div class="modal fade" id="favoriteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title"><i class="fas fa-star me-2"></i>Save Favorite</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <form id="favorite-form" data-ajax="true" action="/api/reports/favorites" method="POST">
                    <?= csrf_field() ?>
                    <input type="hidden" name="report_id" value="<?= (int)$report['id'] ?>">
                    <input type="hidden" name="saved_parameters" id="fav-params-json">
                    <div class="mb-3">
                        <label class="form-label">Favorite Name</label>
                        <input type="text" name="favorite_name" class="form-control" required>
                        <div class="invalid-feedback" data-field="favorite_name"></div>
                    </div>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Save</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php $__view->push('scripts') ?>
<script>
(function() {
    var reportId = <?= (int)$report['id'] ?>;
    var columns = <?= json_encode($columns) ?>;
    var chartType = <?= json_encode($chartType) ?>;
    var chartConfig = <?= json_encode($chartConfig) ?>;
    var dtColumns = [];
    var chartInstance = null;

    columns.forEach(function(c) {
        var def = { data: c.key, title: c.label || c.key, orderable: true };
        if (c.key === 'status') {
            def.render = function(data) {
                if (!data) return '';
                var cls = {'active':'success','pending':'warning','suspended':'danger','frozen':'info','completed':'success','expired':'secondary','overdue':'danger','closed':'secondary','resolved':'success'};
                return '<span class="badge bg-'+(cls[data]||'secondary')+'">'+data.replace(/_/g,' ')+'</span>';
            };
        }
        if (c.key && (c.key.indexOf('amount') !== -1 || c.key.indexOf('balance') !== -1 || c.key.indexOf('paid') !== -1 || c.key.indexOf('invoiced') !== -1 || c.key.indexOf('overdue_amount') !== -1)) {
            def.render = function(data) { return data !== null && data !== '' ? parseFloat(data).toLocaleString('en', {minimumFractionDigits:2, maximumFractionDigits:2}) : '0.00'; };
        }
        dtColumns.push(def);
    });

    var table = $('#report-results-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '/api/reports/execute/' + reportId,
            type: 'POST',
            data: function(d) {
                d.params = {};
                $('#report-params-form').serializeArray().forEach(function(item) {
                    if (item.value) d.params[item.name] = item.value;
                });
                return d;
            },
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            }
        },
        columns: dtColumns,
        order: [[0, 'asc']],
        pageLength: 25,
        lengthMenu: [10, 25, 50, 100],
        language: { emptyTable: 'No data — adjust parameters and generate', processing: '<div class="spinner-border spinner-border-sm"></div>' },
        drawCallback: function(settings) {
            if (chartType && settings.json && settings.json.data) {
                buildChart(settings.json.data);
            }
        }
    });

    $('#report-params-form').on('submit', function(e) {
        e.preventDefault();
        table.ajax.reload();
    });

    function getParams() {
        var p = {};
        $('#report-params-form').serializeArray().forEach(function(item) {
            if (item.value) p[item.name] = item.value;
        });
        return p;
    }

    function exportReport(format) {
        var form = $('<form method="POST" action="/api/reports/export/' + reportId + '"></form>');
        form.append('<input type="hidden" name="_token" value="' + $('meta[name="csrf-token"]').attr('content') + '">');
        form.append('<input type="hidden" name="format" value="' + format + '">');
        var params = getParams();
        for (var k in params) {
            form.append('<input type="hidden" name="params[' + k + ']" value="' + params[k] + '">');
        }
        $('body').append(form);
        form.submit();
        form.remove();
    }

    $('#btn-export-csv').on('click', function() { exportReport('csv'); });
    $('#btn-export-excel').on('click', function() { exportReport('excel'); });
    $('#btn-export-print').on('click', function() { window.print(); });

    $('#btn-save-favorite').on('click', function() {
        $('#fav-params-json').val(JSON.stringify(getParams()));
        new bootstrap.Modal('#favoriteModal').show();
    });

    $('#favorite-form').on('submit', function(e) {
        e.preventDefault();
        var fd = new FormData(this);
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: fd,
            processData: false,
            contentType: false,
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), 'X-Requested-With': 'XMLHttpRequest'},
            success: function(res) {
                if (res.success) {
                    bootstrap.Modal.getInstance(document.getElementById('favoriteModal')).hide();
                    Swal.fire({icon:'success',title:'Saved!',timer:1500,showConfirmButton:false,toast:true,position:'top-end'});
                }
            }
        });
    });

    function buildChart(data) {
        if (!chartType || !data.length) return;
        $('#chart-card').show();
        var canvas = document.getElementById('report-chart');
        if (!canvas) return;

        if (chartInstance) chartInstance.destroy();

        var groupCol = chartConfig.group_column || chartConfig.label_column || (columns[0] ? columns[0].key : '');
        var valueCol = chartConfig.value_column || (columns.length > 1 ? columns[columns.length - 1].key : '');

        var grouped = {};
        data.forEach(function(row) {
            var label = row[groupCol] || 'Unknown';
            var val = parseFloat(row[valueCol]) || 1;
            grouped[label] = (grouped[label] || 0) + val;
        });

        var labels = Object.keys(grouped);
        var values = Object.values(grouped);
        var colors = ['#2c5282','#38a169','#dd6b20','#e53e3e','#805ad5','#d69e2e','#319795','#ed64a6','#718096','#4299e1'];

        chartInstance = new Chart(canvas, {
            type: chartType === 'doughnut' ? 'doughnut' : (chartType === 'pie' ? 'pie' : 'bar'),
            data: {
                labels: labels,
                datasets: [{
                    data: values,
                    backgroundColor: colors.slice(0, labels.length),
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { position: chartType === 'bar' ? 'top' : 'right' } }
            }
        });
    }

    $('#toggle-chart').on('click', function() {
        var body = $(this).closest('.card').find('.card-body');
        body.toggle();
        $(this).find('i').toggleClass('fa-eye-slash fa-eye');
    });

    // Load dynamic select options
    <?php foreach ($parameters as $param):
        $opts = json_decode($param['options'] ?? '[]', true) ?: [];
        if (isset($opts['source'])):
            $source = $opts['source'];
    ?>
    (function() {
        var selectEl = $('select[name="<?= e($param['parameter_name']) ?>"]');
        $.get('/api/reports/param-options?source=<?= e($source) ?>', function(res) {
            if (res && res.data) {
                res.data.forEach(function(item) {
                    selectEl.append('<option value="'+item.id+'">'+item.name+'</option>');
                });
            }
        }).fail(function() {
            // Load from DB directly via simple query
        });
    })();
    <?php endif; endforeach; ?>

    // Try to load select options from known sources
    $('select[name="membership_type_id"]').each(function() {
        var sel = $(this);
        if (sel.children().length <= 1) {
            $.get('/api/members/search?type=membership_types', function(res) {}).fail(function(){});
        }
    });
})();
</script>
<?php $__view->endPush() ?>