<?php
if (!isset($_SESSION['csv_analysis'])) {
    echo '<p>No data available to generate a dashboard.</p>';
    return;
}

$analysis = $_SESSION['csv_analysis'];
$schema = $analysis['schema'];
$suggestions = $analysis['suggestions'];
$sample = $analysis['sample'];

// Apply user-defined types from preview screen
if (isset($_POST['column_types'])) {
    foreach ($_POST['column_types'] as $col => $type) {
        if (isset($schema[$col])) {
            $schema[$col]['type'] = $type;
        }
    }
    // Re-run suggestions with updated types
    // (This requires the suggestion logic to be available here)
    // For now, we'll just use the updated schema
}

?>

<div class="row">
    <!-- Filters -->
    <div class="col-12 mb-4">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">Filters</h5>
                <div class="row">
                    <?php if (isset($suggestions['time_chart'])): ?>
                        <div class="col-md-4">
                            <label for="dateRange" class="form-label">Date Range</label>
                            <input type="text" class="form-control" id="dateRange" placeholder="Select date range...">
                        </div>
                    <?php endif; ?>
                    <?php foreach ($suggestions['filters'] as $filter_col): ?>
                        <div class="col-md-4">
                            <label for="filter_<?php echo htmlspecialchars($filter_col); ?>" class="form-label"><?php echo htmlspecialchars($filter_col); ?></label>
                            <select class="form-select" id="filter_<?php echo htmlspecialchars($filter_col); ?>">
                                <option value="">All</option>
                                <?php 
                                    $unique_values = array_unique(array_column($sample, $filter_col));
                                    sort($unique_values);
                                    foreach ($unique_values as $value): 
                                ?>
                                    <option value="<?php echo htmlspecialchars($value); ?>"><?php echo htmlspecialchars($value); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- KPIs -->
    <div class="col-12 mb-4">
        <div class="row row-cols-1 row-cols-md-3 g-4">
            <?php if (!empty($suggestions['kpis'])): ?>
                <div class="col">
                    <div class="card text-center h-100 p-4">
                        <h6 class="card-subtitle mb-2 text-muted">Total Rows</h6>
                        <p class="card-text fs-2 fw-bold"><?php echo count($sample); ?></p>
                    </div>
                </div>
                 <div class="col">
                    <div class="card text-center h-100 p-4">
                        <h6 class="card-subtitle mb-2 text-muted">Avg. <?php echo htmlspecialchars($suggestions['kpis'][0]); ?></h6>
                        <p class="card-text fs-2 fw-bold"><?php echo round(array_sum(array_column($sample, $suggestions['kpis'][0])) / count($sample), 2); ?></p>
                    </div>
                </div>
                 <div class="col">
                    <div class="card text-center h-100 p-4">
                        <h6 class="card-subtitle mb-2 text-muted">Total <?php echo htmlspecialchars($suggestions['kpis'][0]); ?></h6>
                        <p class="card-text fs-2 fw-bold"><?php echo array_sum(array_column($sample, $suggestions['kpis'][0])); ?></p>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Charts -->
    <div class="row mt-5">
        <div class="col-md-8 mb-4">
            <?php if (isset($suggestions['time_chart'])): ?>
                <div class="card p-4 h-100">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">Time Chart</h5>
                        <button class="btn btn-sm btn-outline-secondary export-png" data-chart="timeChart">Export to PNG</button>
                    </div>
                    <canvas id="timeChart"></canvas>
                </div>
            <?php elseif (isset($suggestions['histogram'])): ?>
                 <div class="card p-4 h-100">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">Histogram</h5>
                        <button class="btn btn-sm btn-outline-secondary export-png" data-chart="histogramChart">Export to PNG</button>
                    </div>
                    <canvas id="histogramChart"></canvas>
                </div>
            <?php endif; ?>
        </div>
        <div class="col-md-4 mb-4">
             <?php if (isset($suggestions['category_chart'])): ?>
                <div class="card p-4 h-100">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">Category Chart</h5>
                        <button class="btn btn-sm btn-outline-secondary export-png" data-chart="categoryChart">Export to PNG</button>
                    </div>
                    <canvas id="categoryChart"></canvas>
                </div>
            <?php elseif (isset($suggestions['category_table'])): ?>
                <div class="card p-4 h-100">
                     <h5>Top Categories</h5>
                     <table class="table">
                        <!-- category table rendering -->
                     </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Data Table -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card p-4">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0">Sample Data</h5>
                    <button class="btn btn-sm btn-outline-secondary" id="exportCsv">Export to CSV</button>
                </div>
                <div class="table-responsive">
                    <table class="table table-sm table-striped">
                        <thead>
                            <tr>
                            <?php foreach ($analysis['header'] as $col): ?>
                                <th><?php echo htmlspecialchars($col); ?></th>
                            <?php endforeach; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($sample as $row): ?>
                            <tr>
                                <?php foreach ($row as $value): ?>
                                <td><?php echo htmlspecialchars($value); ?></td>
                                <?php endforeach; ?>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
var sampleData = <?php echo json_encode($sample); ?>;
var charts = {};
document.addEventListener('DOMContentLoaded', function () {
    <?php if (isset($suggestions['time_chart'])): ?>
    charts.timeChart = new Chart(document.getElementById('timeChart'), {
        type: 'line',
        data: {
            labels: <?php echo json_encode(array_column($sample, $suggestions['time_chart']['time_col'])); ?>,
            datasets: [{
                label: '<?php echo htmlspecialchars($suggestions['time_chart']['metric_col']); ?> over Time',
                data: <?php echo json_encode(array_column($sample, $suggestions['time_chart']['metric_col'])); ?>,
                borderColor: '#D4A373',
                tension: 0.1
            }]
        }
    });
    <?php endif; ?>

    <?php 
    if (isset($suggestions['category_chart'])):
        $cat_col = $suggestions['category_chart']['category_col'];
        $met_col = $suggestions['category_chart']['metric_col'];
        $grouped_data = [];
        foreach ($sample as $row) {
            $category = $row[$cat_col];
            if (!isset($grouped_data[$category])) {
                $grouped_data[$category] = 0;
            }
            $grouped_data[$category] += (float)$row[$met_col];
        }
        arsort($grouped_data);
        $top_10 = array_slice($grouped_data, 0, 10);
        $chart_labels = array_keys($top_10);
        $chart_data = array_values($top_10);
    ?>
    charts.categoryChart = new Chart(document.getElementById('categoryChart'), {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($chart_labels); ?>,
            datasets: [{
                label: 'Top 10 by <?php echo htmlspecialchars($met_col); ?>',
                data: <?php echo json_encode($chart_data); ?>,
                backgroundColor: '#F7F3ED'
            }]
        },
        options: {
            indexAxis: 'y',
        }
    });
    <?php endif; ?>
    
    <?php if (isset($suggestions['histogram'])): ?>
    charts.histogramChart = new Chart(document.getElementById('histogramChart'), {
        type: 'bar',
        data: {
            labels: <?php echo json_encode(array_column($sample, $suggestions['histogram']['metric_col'])); ?>,
            datasets: [{
                label: 'Histogram of <?php echo htmlspecialchars($suggestions['histogram']['metric_col']); ?>',
                data: <?php echo json_encode(array_column($sample, $suggestions['histogram']['metric_col'])); ?>,
                backgroundColor: '#F7F3ED'
            }]
        }
    });
    <?php endif; ?>
});
</script>
