<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Load report builder class
require_once 'ReportBuilder.php';
$reportBuilder = new ReportBuilder($conn, $_SESSION['user_id'], $_SESSION['role_id']);

// Get template ID from query string
$template_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$template_id) {
    header('Location: report_builder.php');
    exit();
}

// Get template details
$result = $reportBuilder->getTemplateDetails($template_id);

if (!$result['success']) {
    $_SESSION['error_msg'] = $result['error'];
    header('Location: report_builder.php');
    exit();
}

$template = $result['data']['template'];
$parameters = $result['data']['parameters'];

// Check if form is submitted
$report_data = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Extract parameter values
    $param_values = [];
    foreach ($parameters as $param) {
        $param_name = $param['param_name'];
        if (isset($_POST[$param_name])) {
            $param_values[$param_name] = $_POST[$param_name];
        }
    }
    
    // Process report format
    $format = isset($_POST['report_format']) ? $_POST['report_format'] : 'html';
    
    // Generate report
    $report_result = $reportBuilder->generateReport($template_id, $param_values, $format);
    
    // If not HTML format, the function will handle the download
    if ($format !== 'html' && $report_result['success']) {
        // Download handled by the function, exit to prevent further output
        exit();
    }
    
    // For HTML format, store the data for display
    if ($report_result['success']) {
        $report_data = $report_result['data'];
    } else {
        $_SESSION['error_msg'] = $report_result['error'];
    }
}

// Function to render chart using HTML/CSS/JS
function renderChart($section) {
    $chartType = strtolower($section['chart_type']);
    $chartId = 'chart_' . uniqid();
    $chartData = [];
    
    // Prepare data for chart
    $labels = [];
    $datasets = [];
    
    if (!empty($section['rows']) && !empty($section['columns'])) {
        // First column is labels
        $labelColumn = $section['columns'][0];
        
        // Each additional column is a dataset
        for ($i = 1; $i < count($section['columns']); $i++) {
            $dataColumn = $section['columns'][$i];
            $data = [];
            
            foreach ($section['rows'] as $row) {
                if ($i === 1) {
                    // Add label only once
                    $labels[] = $row[$labelColumn];
                }
                
                $data[] = floatval($row[$dataColumn]);
            }
            
            $datasets[] = [
                'label' => $dataColumn,
                'data' => $data,
                'backgroundColor' => getRandomColor($i - 1),
                'borderColor' => getRandomColor($i - 1, 0.8),
                'borderWidth' => 1
            ];
        }
    }
    
    $chartData = [
        'labels' => $labels,
        'datasets' => $datasets
    ];
    
    // Determine chart type and render appropriate HTML
    switch ($chartType) {
        case 'pie':
            return '<div class="chart-container" style="position: relative; height:350px; width:100%;">
                <canvas id="' . $chartId . '"></canvas>
            </div>
            <script>
                document.addEventListener("DOMContentLoaded", function() {
                    new Chart(document.getElementById("' . $chartId . '"), {
                        type: "pie",
                        data: ' . json_encode($chartData) . ',
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: "right"
                                },
                                title: {
                                    display: true,
                                    text: "' . $section['name'] . '"
                                }
                            }
                        }
                    });
                });
            </script>';
            
        case 'bar':
            return '<div class="chart-container" style="position: relative; height:350px; width:100%;">
                <canvas id="' . $chartId . '"></canvas>
            </div>
            <script>
                document.addEventListener("DOMContentLoaded", function() {
                    new Chart(document.getElementById("' . $chartId . '"), {
                        type: "bar",
                        data: ' . json_encode($chartData) . ',
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                y: {
                                    beginAtZero: true
                                }
                            },
                            plugins: {
                                legend: {
                                    position: "top"
                                },
                                title: {
                                    display: true,
                                    text: "' . $section['name'] . '"
                                }
                            }
                        }
                    });
                });
            </script>';
            
        case 'line':
        default:
            return '<div class="chart-container" style="position: relative; height:350px; width:100%;">
                <canvas id="' . $chartId . '"></canvas>
            </div>
            <script>
                document.addEventListener("DOMContentLoaded", function() {
                    new Chart(document.getElementById("' . $chartId . '"), {
                        type: "line",
                        data: ' . json_encode($chartData) . ',
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                y: {
                                    beginAtZero: true
                                }
                            },
                            plugins: {
                                legend: {
                                    position: "top"
                                },
                                title: {
                                    display: true,
                                    text: "' . $section['name'] . '"
                                }
                            }
                        }
                    });
                });
            </script>';
    }
}

// Helper function to generate random colors
function getRandomColor($index = null, $alpha = 0.5) {
    $colors = [
        'rgba(54, 162, 235, ' . $alpha . ')',
        'rgba(255, 99, 132, ' . $alpha . ')',
        'rgba(255, 206, 86, ' . $alpha . ')',
        'rgba(75, 192, 192, ' . $alpha . ')',
        'rgba(153, 102, 255, ' . $alpha . ')',
        'rgba(255, 159, 64, ' . $alpha . ')',
        'rgba(199, 199, 199, ' . $alpha . ')',
        'rgba(83, 102, 255, ' . $alpha . ')',
        'rgba(40, 167, 69, ' . $alpha . ')',
        'rgba(220, 53, 69, ' . $alpha . ')'
    ];
    
    if ($index !== null && isset($colors[$index])) {
        return $colors[$index];
    }
    
    return $colors[array_rand($colors)];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Run Report')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <!-- Chart.js for visualizations -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Reports', 'title' => 'Run Report')); ?>

                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1"><?php echo htmlspecialchars($template['template_name']); ?></h4>
                                    <div class="flex-shrink-0">
                                        <a href="report_builder.php" class="btn btn-soft-primary">
                                            <i class="ri-arrow-left-line align-middle me-1"></i> Back to Templates
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <?php if (!empty($template['description'])): ?>
                                    <div class="alert alert-info mb-4">
                                        <?php echo htmlspecialchars($template['description']); ?>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if (isset($_SESSION['error_msg'])): ?>
                                    <div class="alert alert-danger alert-dismissible fade show mb-4" role="alert">
                                        <?php echo $_SESSION['error_msg']; ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                    </div>
                                    <?php unset($_SESSION['error_msg']); endif; ?>
                                    
                                    <!-- Report parameters form -->
                                    <form method="post" id="reportForm">
                                        <?php if (!empty($parameters)): ?>
                                        <div class="row mb-4">
                                            <div class="col-lg-12">
                                                <div class="card border">
                                                    <div class="card-header bg-soft-primary">
                                                        <h5 class="card-title mb-0">Report Parameters</h5>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="row">
                                                            <?php foreach ($parameters as $param): ?>
                                                            <div class="col-md-4 mb-3">
                                                                <label class="form-label" for="<?php echo $param['param_name']; ?>">
                                                                    <?php echo htmlspecialchars($param['display_name']); ?>
                                                                    <?php if ($param['is_required']): ?>
                                                                    <span class="text-danger">*</span>
                                                                    <?php endif; ?>
                                                                </label>
                                                                
                                                                <?php
                                                                $value = isset($_POST[$param['param_name']]) ? $_POST[$param['param_name']] : $param['default_value'];
                                                                switch ($param['param_type']):
                                                                    case 'text':
                                                                ?>
                                                                    <input type="text" class="form-control" id="<?php echo $param['param_name']; ?>" 
                                                                           name="<?php echo $param['param_name']; ?>" 
                                                                           value="<?php echo htmlspecialchars($value ?? ''); ?>"
                                                                           <?php echo $param['is_required'] ? 'required' : ''; ?>>
                                                                <?php break; case 'number': ?>
                                                                    <input type="number" class="form-control" id="<?php echo $param['param_name']; ?>" 
                                                                           name="<?php echo $param['param_name']; ?>" 
                                                                           value="<?php echo htmlspecialchars($value ?? ''); ?>"
                                                                           <?php echo $param['is_required'] ? 'required' : ''; ?>>
                                                                <?php break; case 'date': ?>
                                                                    <input type="date" class="form-control" id="<?php echo $param['param_name']; ?>" 
                                                                           name="<?php echo $param['param_name']; ?>" 
                                                                           value="<?php echo htmlspecialchars($value ?? ''); ?>"
                                                                           <?php echo $param['is_required'] ? 'required' : ''; ?>>
                                                                <?php break; case 'dropdown': ?>
                                                                    <select class="form-select" id="<?php echo $param['param_name']; ?>" 
                                                                            name="<?php echo $param['param_name']; ?>"
                                                                            <?php echo $param['is_required'] ? 'required' : ''; ?>>
                                                                        <option value="">Select...</option>
                                                                        <?php 
                                                                        $options = json_decode($param['options'], true) ?: [];
                                                                        foreach ($options as $option_value => $option_label): 
                                                                        ?>
                                                                        <option value="<?php echo htmlspecialchars($option_value); ?>" 
                                                                                <?php echo $value == $option_value ? 'selected' : ''; ?>>
                                                                            <?php echo htmlspecialchars($option_label); ?>
                                                                        </option>
                                                                        <?php endforeach; ?>
                                                                    </select>
                                                                <?php break; case 'multi-select': ?>
                                                                    <select class="form-select" id="<?php echo $param['param_name']; ?>" 
                                                                            name="<?php echo $param['param_name']; ?>[]" 
                                                                            multiple
                                                                            <?php echo $param['is_required'] ? 'required' : ''; ?>>
                                                                        <?php 
                                                                        $options = json_decode($param['options'], true) ?: [];
                                                                        $selected_values = is_array($value) ? $value : explode(',', $value ?? '');
                                                                        foreach ($options as $option_value => $option_label): 
                                                                        ?>
                                                                        <option value="<?php echo htmlspecialchars($option_value); ?>" 
                                                                                <?php echo in_array($option_value, $selected_values) ? 'selected' : ''; ?>>
                                                                            <?php echo htmlspecialchars($option_label); ?>
                                                                        </option>
                                                                        <?php endforeach; ?>
                                                                    </select>
                                                                <?php break; default: ?>
                                                                    <input type="text" class="form-control" id="<?php echo $param['param_name']; ?>" 
                                                                           name="<?php echo $param['param_name']; ?>" 
                                                                           value="<?php echo htmlspecialchars($value ?? ''); ?>"
                                                                           <?php echo $param['is_required'] ? 'required' : ''; ?>>
                                                                <?php endswitch; ?>
                                                            </div>
                                                            <?php endforeach; ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="row mb-4">
                                            <div class="col-lg-12">
                                                <div class="hstack gap-2">
                                                    <select class="form-select w-md" name="report_format">
                                                        <option value="html">View HTML</option>
                                                        <option value="pdf">Export PDF</option>
                                                        <option value="excel">Export Excel</option>
                                                    </select>
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="ri-play-line align-middle me-1"></i> Run Report
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                    
                                    <?php if ($report_data): ?>
                                    <!-- Report Results -->
                                    <div class="row mt-4">
                                        <div class="col-lg-12">
                                            <div class="card border">
                                                <div class="card-header bg-soft-success">
                                                    <div class="d-flex align-items-center">
                                                        <h5 class="card-title mb-0 flex-grow-1">Report Results</h5>
                                                        <div class="flex-shrink-0">
                                                            <span class="badge bg-success-subtle text-success">
                                                                Generated: <?php echo $report_data['generated_at']; ?>
                                                            </span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="card-body">
                                                    <!-- Display each section -->
                                                    <?php foreach ($report_data['sections'] as $index => $section): ?>
                                                    <div class="section mb-5">
                                                        <h4 class="mb-3"><?php echo htmlspecialchars($section['name']); ?></h4>
                                                        
                                                        <?php if (!empty($section['rows'])): ?>
                                                            <?php if (!empty($section['chart_type'])): ?>
                                                            <div class="row mb-4">
                                                                <div class="col-lg-12">
                                                                    <?php echo renderChart($section); ?>
                                                                </div>
                                                            </div>
                                                            <?php endif; ?>
                                                            
                                                            <div class="table-responsive">
                                                                <table class="table table-bordered table-striped">
                                                                    <thead class="bg-light">
                                                                        <tr>
                                                                            <?php foreach ($section['columns'] as $col): ?>
                                                                            <th><?php echo htmlspecialchars($col); ?></th>
                                                                            <?php endforeach; ?>
                                                                        </tr>
                                                                    </thead>
                                                                    <tbody>
                                                                        <?php foreach ($section['rows'] as $row): ?>
                                                                        <tr>
                                                                            <?php foreach ($section['columns'] as $col): ?>
                                                                            <td>
                                                                                <?php 
                                                                                if (isset($row[$col])) {
                                                                                    // Format numbers with thousands separator
                                                                                    if (is_numeric($row[$col])) {
                                                                                        if (floor($row[$col]) == $row[$col]) {
                                                                                            echo number_format($row[$col]);
                                                                                        } else {
                                                                                            echo number_format($row[$col], 2);
                                                                                        }
                                                                                    } else {
                                                                                        echo htmlspecialchars($row[$col]);
                                                                                    }
                                                                                } else {
                                                                                    echo '-';
                                                                                }
                                                                                ?>
                                                                            </td>
                                                                            <?php endforeach; ?>
                                                                        </tr>
                                                                        <?php endforeach; ?>
                                                                    </tbody>
                                                                </table>
                                                            </div>
                                                        <?php else: ?>
                                                            <div class="alert alert-warning mb-0">
                                                                No data found for this section.
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    
                                                    <?php if ($index < count($report_data['sections']) - 1): ?>
                                                    <hr class="my-4">
                                                    <?php endif; ?>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize multi-select dropdowns
            const multiSelects = document.querySelectorAll('select[multiple]');
            multiSelects.forEach(select => {
                $(select).select2({
                    width: '100%',
                    placeholder: 'Select options'
                });
            });
        });
    </script>
</body>
</html>