<?php
/**
 * Analytics Page
 * Research Survey Management System
 */

define('PAGE_TITLE', 'Analytics');
require_once __DIR__ . '/../includes/functions.php';
requireRole(['admin', 'analyst', 'researcher']);

$pdo = getDBConnection();
$surveyId = isset($_GET['survey_id']) ? (int)$_GET['survey_id'] : 0;

// Get all surveys for dropdown
$stmt = $pdo->prepare("SELECT survey_id, title FROM surveys ORDER BY created_at DESC");
$stmt->execute();
$allSurveys = $stmt->fetchAll();

$surveyData = null;
$questions = [];
$analytics = null;

if ($surveyId) {
    $surveyData = getSurveyWithQuestions($surveyId);
    $analytics = getSurveyAnalytics($surveyId);
    
    if ($surveyData) {
        // Get questions with their analytics
        $stmt = $pdo->prepare("
            SELECT q.*, 
                   ra.analytics_type, ra.analytics_data, ra.sample_size
            FROM survey_questions q
            LEFT JOIN response_analytics ra ON q.question_id = ra.question_id
            WHERE q.survey_id = :sid
            ORDER BY q.question_order, ra.analytics_type
        ");
        $stmt->execute(['sid' => $surveyId]);
        $questions = $stmt->fetchAll();
        
        // Get completion time distribution
        $stmt = $pdo->prepare("
            SELECT 
                CASE 
                    WHEN time_spent_seconds < 60 THEN '< 1 min'
                    WHEN time_spent_seconds BETWEEN 60 AND 180 THEN '1-3 min'
                    WHEN time_spent_seconds BETWEEN 181 AND 300 THEN '3-5 min'
                    WHEN time_spent_seconds BETWEEN 301 AND 600 THEN '5-10 min'
                    ELSE '> 10 min'
                END as time_range,
                COUNT(*) as count
            FROM survey_responses
            WHERE survey_id = :sid AND status = 'completed' AND time_spent_seconds IS NOT NULL
            GROUP BY time_range
            ORDER BY MIN(time_spent_seconds)
        ");
        $stmt->execute(['sid' => $surveyId]);
        $timeDistribution = $stmt->fetchAll();
        
        // Get response trend (daily)
        $stmt = $pdo->prepare("
            SELECT DATE(completed_at) as date, COUNT(*) as count
            FROM survey_responses
            WHERE survey_id = :sid AND status = 'completed'
            GROUP BY DATE(completed_at)
            ORDER BY date
        ");
        $stmt->execute(['sid' => $surveyId]);
        $responseTrend = $stmt->fetchAll();
    }
}

require_once __DIR__ . '/../includes/header.php';
?>

<div class="dashboard-header">
    <div>
        <h1><i class="fas fa-chart-bar me-2 text-primary"></i>Analytics & Research Functions</h1>
        <p>Advanced statistical analysis and research methodology tools</p>
    </div>
</div>

<!-- Survey Selector -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-8">
                <label class="form-label fw-medium">Select Survey for Analysis</label>
                <select class="form-select form-select-lg" name="survey_id" onchange="this.form.submit()">
                    <option value="">-- Choose a survey --</option>
                    <?php foreach ($allSurveys as $s): ?>
                    <option value="<?php echo $s['survey_id']; ?>" <?php echo $surveyId == $s['survey_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($s['title']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">Analyze</button>
            </div>
            <div class="col-md-2">
                <a href="<?php echo BASE_URL; ?>/pages/reports.php?survey_id=<?php echo $surveyId; ?>" 
                   class="btn btn-outline-success w-100 <?php echo !$surveyId ? 'disabled' : ''; ?>">
                    <i class="fas fa-file-alt me-1"></i> Report
                </a>
            </div>
        </form>
    </div>
</div>

<?php if ($surveyData && $analytics): ?>

<!-- Overview Cards -->
<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm bg-primary text-white h-100">
            <div class="card-body text-center">
                <i class="fas fa-reply-all fa-2x mb-2 opacity-75"></i>
                <h3 class="mb-0"><?php echo $analytics['total_responses']; ?></h3>
                <small>Total Responses</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm bg-success text-white h-100">
            <div class="card-body text-center">
                <i class="fas fa-percentage fa-2x mb-2 opacity-75"></i>
                <h3 class="mb-0"><?php echo number_format($analytics['completion_rate'], 1); ?>%</h3>
                <small>Completion Rate</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm bg-info text-white h-100">
            <div class="card-body text-center">
                <i class="fas fa-clock fa-2x mb-2 opacity-75"></i>
                <h3 class="mb-0"><?php echo formatDuration($analytics['average_time_spent']); ?></h3>
                <small>Avg. Completion Time</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm bg-warning text-white h-100">
            <div class="card-body text-center">
                <i class="fas fa-calculator fa-2x mb-2 opacity-75"></i>
                <h3 class="mb-0"><?php echo $analytics['overall_mean'] ? number_format($analytics['overall_mean'], 2) : 'N/A'; ?></h3>
                <small>Overall Mean Score</small>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <!-- Response Trend -->
    <div class="col-md-8">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-chart-line me-2 text-success"></i>Response Trend Over Time</h5>
            </div>
            <div class="card-body">
                <canvas id="responseTrendChart" height="120"></canvas>
            </div>
        </div>
    </div>
    
    <!-- Time Distribution -->
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-hourglass-half me-2 text-info"></i>Completion Time Distribution</h5>
            </div>
            <div class="card-body">
                <canvas id="timeDistChart" height="150"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- Descriptive Statistics Section -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-white">
        <h5 class="mb-0">
            <i class="fas fa-calculator me-2 text-primary"></i>Descriptive Statistics - Quantitative Analysis
        </h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead class="table-light">
                    <tr>
                        <th>Question</th>
                        <th>Type</th>
                        <th>N</th>
                        <th>Mean</th>
                        <th>Median</th>
                        <th>Std Dev</th>
                        <th>Variance</th>
                        <th>Min</th>
                        <th>Max</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $numericTypes = ['rating_scale', 'likert_scale', 'numerical', 'yes_no'];
                    $hasStats = false;
                    foreach ($surveyData['questions'] as $q): 
                        if (!in_array($q['question_type'], $numericTypes)) continue;
                        $hasStats = true;
                        
                        // Get stats from response_analytics
                        $meanData = $pdo->prepare("SELECT analytics_data FROM response_analytics 
                                                   WHERE question_id = :qid AND analytics_type = 'mean'");
                        $meanData->execute(['qid' => $q['question_id']]);
                        $mean = $meanData->fetchColumn();
                        
                        $medianData = $pdo->prepare("SELECT analytics_data FROM response_analytics 
                                                     WHERE question_id = :qid AND analytics_type = 'median'");
                        $medianData->execute(['qid' => $q['question_id']]);
                        $median = $medianData->fetchColumn();
                        
                        $stdData = $pdo->prepare("SELECT analytics_data FROM response_analytics 
                                                  WHERE question_id = :qid AND analytics_type = 'std_deviation'");
                        $stdData->execute(['qid' => $q['question_id']]);
                        $std = $stdData->fetchColumn();
                        
                        $rangeData = $pdo->prepare("SELECT analytics_data FROM response_analytics 
                                                    WHERE question_id = :qid AND analytics_type = 'range'");
                        $rangeData->execute(['qid' => $q['question_id']]);
                        $range = $rangeData->fetchColumn();
                        
                        $freqData = $pdo->prepare("SELECT analytics_data, sample_size FROM response_analytics 
                                                   WHERE question_id = :qid AND analytics_type = 'frequency'");
                        $freqData->execute(['qid' => $q['question_id']]);
                        $freq = $freqData->fetch();
                        
                        $m = json_decode($mean, true);
                        $med = json_decode($median, true);
                        $s = json_decode($std, true);
                        $r = json_decode($range, true);
                    ?>
                    <tr>
                        <td><?php echo htmlspecialchars(substr($q['question_text'], 0, 60)) . (strlen($q['question_text']) > 60 ? '...' : ''); ?></td>
                        <td><span class="badge bg-secondary"><?php echo str_replace('_', ' ', $q['question_type']); ?></span></td>
                        <td><?php echo $freq['sample_size'] ?? 0; ?></td>
                        <td><strong><?php echo $m ? number_format($m['mean'], 2) : 'N/A'; ?></strong></td>
                        <td><?php echo $med ? number_format($med['median'], 2) : 'N/A'; ?></td>
                        <td><?php echo $s ? number_format($s['std_deviation'], 2) : 'N/A'; ?></td>
                        <td><?php echo $s ? number_format($s['variance'], 2) : 'N/A'; ?></td>
                        <td><?php echo $r ? $r['min'] : 'N/A'; ?></td>
                        <td><?php echo $r ? $r['max'] : 'N/A'; ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (!$hasStats): ?>
                    <tr><td colspan="9" class="text-center text-muted py-3">No quantitative questions found in this survey</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Question-by-Question Analysis -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white">
        <h5 class="mb-0"><i class="fas fa-chart-pie me-2 text-success"></i>Per-Question Analysis & Frequency Distribution</h5>
    </div>
    <div class="card-body">
        <?php foreach ($surveyData['questions'] as $q): 
            $freqData = $pdo->prepare("SELECT analytics_data FROM response_analytics 
                                       WHERE question_id = :qid AND analytics_type = 'frequency'");
            $freqData->execute(['qid' => $q['question_id']]);
            $freqJson = $freqData->fetchColumn();
            $freq = json_decode($freqJson, true);
        ?>
        <div class="mb-4 p-3 bg-light rounded">
            <h6 class="fw-bold mb-1">
                <span class="badge bg-primary me-2">Q</span>
                <?php echo htmlspecialchars($q['question_text']); ?>
                <small class="text-muted ms-2">(<?php echo str_replace('_', ' ', $q['question_type']); ?>)</small>
            </h6>
            
            <?php if ($freq && isset($freq['distribution'])): ?>
            <div class="row g-2 mt-2">
                <?php foreach ($freq['distribution'] as $item): ?>
                <div class="col-auto">
                    <span class="badge bg-white text-dark border px-3 py-2">
                        <?php echo htmlspecialchars($item['value'] ?? ''); ?>
                        <span class="badge bg-primary ms-1"><?php echo $item['count'] ?? 0; ?></span>
                    </span>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            
            <?php if (!empty($q['options'])): ?>
            <div class="mt-2">
                <small class="text-muted">Options: </small>
                <?php foreach ($q['options'] as $opt): ?>
                <span class="badge bg-secondary me-1"><?php echo htmlspecialchars($opt['option_text'] ?? ''); ?></span>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Advanced Metrics Section -->
<div class="row g-3 mt-2 mb-4">
    <div class="col-md-6">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-star me-2 text-warning"></i>Advanced Metrics</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-6 text-center">
                        <div class="p-3 bg-light rounded">
                            <h6 class="text-muted">NPS Score</h6>
                            <h2 class="text-primary mb-0"><?php echo $analytics['overall_mean'] ? number_format(($analytics['overall_mean'] / 10) * 100, 0) : 'N/A'; ?></h2>
                            <small>Net Promoter Score</small>
                        </div>
                    </div>
                    <div class="col-6 text-center">
                        <div class="p-3 bg-light rounded">
                            <h6 class="text-muted">CSAT</h6>
                            <h2 class="text-success mb-0"><?php echo $analytics['completion_rate'] ? number_format($analytics['completion_rate'], 0) : 0; ?>%</h2>
                            <small>Completion Rate</small>
                        </div>
                    </div>
                    <div class="col-6 text-center">
                        <div class="p-3 bg-light rounded">
                            <h6 class="text-muted">Mean Score</h6>
                            <h2 class="text-info mb-0"><?php echo $analytics['overall_mean'] ? number_format($analytics['overall_mean'], 2) : 'N/A'; ?></h2>
                            <small>Average Rating</small>
                        </div>
                    </div>
                    <div class="col-6 text-center">
                        <div class="p-3 bg-light rounded">
                            <h6 class="text-muted">Std Deviation</h6>
                            <h2 class="text-warning mb-0"><?php echo $analytics['overall_std'] ? number_format($analytics['overall_std'], 2) : 'N/A'; ?></h2>
                            <small>Response Variability</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Qualitative Analysis -->
    <div class="col-md-6">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-comment-dots me-2 text-info"></i>Qualitative Text Analysis</h5>
            </div>
            <div class="card-body">
                <?php
                // Get text responses for analysis
                $stmt = $pdo->prepare("
                    SELECT qr.response_value, q.question_text
                    FROM question_responses qr
                    JOIN survey_questions q ON qr.question_id = q.question_id
                    JOIN survey_responses sr ON qr.response_id = sr.response_id
                    WHERE sr.survey_id = :sid 
                    AND q.question_type IN ('text_short', 'text_long', 'rich_text')
                    AND qr.response_value IS NOT NULL
                    AND qr.response_value != ''
                    LIMIT 10
                ");
                $stmt->execute(['sid' => $surveyId]);
                $textResponses = $stmt->fetchAll();
                ?>
                
                <?php if (empty($textResponses)): ?>
                <div class="text-center text-muted py-4">
                    <i class="fas fa-inbox fa-3x mb-2 d-block"></i>
                    <p class="mb-0">No text responses available for analysis</p>
                </div>
                <?php else: ?>
                <div class="list-group list-group-flush">
                    <?php foreach ($textResponses as $tr): ?>
                    <div class="list-group-item px-0">
                        <small class="text-muted d-block"><?php echo htmlspecialchars(substr($tr['question_text'], 0, 80)); ?></small>
                        <p class="mb-0 small">"<?php echo htmlspecialchars(substr($tr['response_value'], 0, 150)) . (strlen($tr['response_value']) > 150 ? '...' : ''); ?>"</p>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                
                <div class="mt-3">
                    <a href="<?php echo BASE_URL; ?>/pages/reports.php?survey_id=<?php echo $surveyId; ?>" class="btn btn-outline-primary btn-sm w-100">
                        <i class="fas fa-file-alt me-1"></i> Generate Full Report
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Response Trend
    const trendCtx = document.getElementById('responseTrendChart').getContext('2d');
    new Chart(trendCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode(array_column($responseTrend, 'date')); ?>,
            datasets: [{
                label: 'Responses',
                data: <?php echo json_encode(array_column($responseTrend, 'count')); ?>,
                borderColor: '#1cc88a',
                backgroundColor: 'rgba(28, 200, 138, 0.1)',
                fill: true,
                tension: 0.4,
                pointBackgroundColor: '#1cc88a',
                pointRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: true, ticks: { stepSize: 1 } }
            }
        }
    });
    
    // Time Distribution
    const timeCtx = document.getElementById('timeDistChart').getContext('2d');
    new Chart(timeCtx, {
        type: 'doughnut',
        data: {
            labels: <?php echo json_encode(array_column($timeDistribution, 'time_range')); ?>,
            datasets: [{
                data: <?php echo json_encode(array_column($timeDistribution, 'count')); ?>,
                backgroundColor: ['#4e73df', '#1cc88a', '#f6c23e', '#e74a3b', '#858796'],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: { padding: 10, font: { size: 10 } }
                }
            }
        }
    });
});
</script>

<?php elseif ($surveyId && !$surveyData): ?>
<div class="alert alert-warning">
    <i class="fas fa-exclamation-triangle me-2"></i>Survey not found or no data available for analysis.
</div>
<?php elseif (!$surveyId): ?>
<div class="card border-0 shadow-sm">
    <div class="card-body text-center py-5">
        <i class="fas fa-chart-simple fa-5x text-muted mb-3"></i>
        <h4>Select a Survey to Analyze</h4>
        <p class="text-muted">Choose a survey from the dropdown above to view advanced analytics including descriptive statistics, response trends, and qualitative text analysis.</p>
    </div>
</div>
<?php endif; ?>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>