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

define('PAGE_TITLE', 'Reports');
require_once __DIR__ . '/../includes/functions.php';
requireAuth();

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

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

$reportData = null;

if ($surveyId) {
    $survey = getSurveyWithQuestions($surveyId);
    $analytics = getSurveyAnalytics($surveyId);
    
    if ($survey) {
        // Get all completed responses with their answers
        $stmt = $pdo->prepare("
            SELECT sr.response_id, sr.completed_at, sr.time_spent_seconds,
                   qr.question_id, qr.response_value, qr.response_numeric, qr.sentiment_score,
                   q.question_text, q.question_type
            FROM survey_responses sr
            JOIN question_responses qr ON sr.response_id = qr.response_id
            JOIN survey_questions q ON qr.question_id = q.question_id
            WHERE sr.survey_id = :sid AND sr.status = 'completed'
            ORDER BY sr.completed_at DESC, q.question_order
        ");
        $stmt->execute(['sid' => $surveyId]);
        $responses = $stmt->fetchAll();
        
        // Group responses by response_id
        $groupedResponses = [];
        foreach ($responses as $r) {
            $rid = $r['response_id'];
            if (!isset($groupedResponses[$rid])) {
                $groupedResponses[$rid] = [
                    'response_id' => $rid,
                    'completed_at' => $r['completed_at'],
                    'time_spent' => $r['time_spent_seconds'],
                    'answers' => []
                ];
            }
            $groupedResponses[$rid]['answers'][] = $r;
        }
        
        $reportData = [
            'survey' => $survey,
            'analytics' => $analytics,
            'responses' => $groupedResponses
        ];
    }
}

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

<div class="dashboard-header">
    <div>
        <h1><i class="fas fa-file-alt me-2 text-primary"></i>Research Reports</h1>
        <p>Generate comprehensive survey reports with mixed methods analysis</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-6">
                <label class="form-label fw-medium">Select Survey for Report</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-3">
                <label class="form-label">&nbsp;</label>
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-file-alt me-1"></i> Generate Report
                </button>
            </div>
            <div class="col-md-3">
                <label class="form-label">&nbsp;</label>
                <div class="btn-group w-100">
                    <a href="<?php echo BASE_URL; ?>/api/export_survey.php?id=<?php echo $surveyId; ?>&format=csv" 
                       class="btn btn-outline-secondary <?php echo !$surveyId ? 'disabled' : ''; ?>">
                        <i class="fas fa-file-csv me-1"></i> CSV
                    </a>
                    <a href="<?php echo BASE_URL; ?>/api/export_survey.php?id=<?php echo $surveyId; ?>&format=excel" 
                       class="btn btn-outline-success <?php echo !$surveyId ? 'disabled' : ''; ?>">
                        <i class="fas fa-file-excel me-1"></i> Excel
                    </a>
                    <button class="btn btn-outline-primary" onclick="window.print()">
                        <i class="fas fa-print me-1"></i> Print
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<?php if ($reportData): ?>
<!-- Report Header -->
<div class="card border-0 shadow-sm mb-4" id="reportHeader">
    <div class="card-body text-center py-4">
        <h2 class="mb-1"><?php echo htmlspecialchars($reportData['survey']['title']); ?></h2>
        <p class="text-muted mb-2">Research Survey Report</p>
        <div class="d-flex justify-content-center gap-3 small text-muted">
            <span><i class="fas fa-calendar me-1"></i>Generated: <?php echo date('M d, Y H:i'); ?></span>
            <span><i class="fas fa-tag me-1"></i>Type: <?php echo ucfirst($reportData['survey']['survey_type']); ?></span>
            <span><i class="fas fa-check-circle me-1"></i>Status: <?php echo ucfirst($reportData['survey']['status']); ?></span>
        </div>
    </div>
</div>

<!-- Executive Summary -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-white">
        <h5 class="mb-0"><i class="fas fa-list-check me-2 text-primary"></i>Executive Summary</h5>
    </div>
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-3 text-center">
                <h3 class="text-primary mb-0"><?php echo $reportData['analytics']['total_responses'] ?? 0; ?></h3>
                <small class="text-muted">Total Responses</small>
            </div>
            <div class="col-md-3 text-center">
                <h3 class="text-success mb-0"><?php echo isset($reportData['analytics']['completion_rate']) ? number_format($reportData['analytics']['completion_rate'], 1) : 0; ?>%</h3>
                <small class="text-muted">Completion Rate</small>
            </div>
            <div class="col-md-3 text-center">
                <h3 class="text-info mb-0"><?php echo count($reportData['survey']['questions']); ?></h3>
                <small class="text-muted">Questions</small>
            </div>
            <div class="col-md-3 text-center">
                <h3 class="text-warning mb-0"><?php echo $reportData['analytics']['overall_mean'] ? number_format($reportData['analytics']['overall_mean'], 2) : 'N/A'; ?></h3>
                <small class="text-muted">Overall Mean</small>
            </div>
        </div>
        
        <?php if ($reportData['survey']['description']): ?>
        <div class="mt-3 p-3 bg-light rounded">
            <strong>Description:</strong>
            <p class="mb-0 mt-1"><?php echo nl2br(htmlspecialchars($reportData['survey']['description'])); ?></p>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Quantitative Analysis 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-success"></i>Quantitative Analysis</h5>
    </div>
    <div class="card-body">
        <?php 
        $numericTypes = ['rating_scale', 'likert_scale', 'numerical', 'yes_no'];
        $hasQuant = false;
        foreach ($reportData['survey']['questions'] as $q): 
            if (!in_array($q['question_type'], $numericTypes)) continue;
            $hasQuant = true;
            
            // Get numeric responses for this question
            $values = [];
            foreach ($reportData['responses'] as $resp) {
                foreach ($resp['answers'] as $ans) {
                    if ($ans['question_id'] == $q['question_id'] && $ans['response_numeric'] !== null) {
                        $values[] = $ans['response_numeric'];
                    }
                }
            }
            
            if (empty($values)) continue;
            
            $mean = array_sum($values) / count($values);
            sort($values);
            $median = $values[floor(count($values) / 2)];
            $min = min($values);
            $max = max($values);
        ?>
        <div class="mb-3 p-3 border rounded">
            <h6 class="fw-bold"><?php echo htmlspecialchars($q['question_text']); ?></h6>
            <div class="row g-2 small">
                <div class="col-auto"><span class="badge bg-primary">N: <?php echo count($values); ?></span></div>
                <div class="col-auto"><span class="badge bg-success">Mean: <?php echo number_format($mean, 2); ?></span></div>
                <div class="col-auto"><span class="badge bg-info">Median: <?php echo number_format($median, 2); ?></span></div>
                <div class="col-auto"><span class="badge bg-warning">Min: <?php echo $min; ?></span></div>
                <div class="col-auto"><span class="badge bg-danger">Max: <?php echo $max; ?></span></div>
            </div>
        </div>
        <?php endforeach; ?>
        <?php if (!$hasQuant): ?>
        <p class="text-muted text-center mb-0">No quantitative questions in this survey.</p>
        <?php endif; ?>
    </div>
</div>

<!-- Qualitative Analysis Section -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-white">
        <h5 class="mb-0"><i class="fas fa-comment me-2 text-info"></i>Qualitative Analysis - Text Responses</h5>
    </div>
    <div class="card-body">
        <?php 
        $textTypes = ['text_short', 'text_long', 'rich_text'];
        $hasText = false;
        foreach ($reportData['survey']['questions'] as $q): 
            if (!in_array($q['question_type'], $textTypes)) continue;
            $hasText = true;
        ?>
        <div class="mb-4">
            <h6 class="fw-bold border-bottom pb-2"><?php echo htmlspecialchars($q['question_text']); ?></h6>
            <?php 
            $textResponses = [];
            foreach ($reportData['responses'] as $resp) {
                foreach ($resp['answers'] as $ans) {
                    if ($ans['question_id'] == $q['question_id'] && !empty($ans['response_value'])) {
                        $textResponses[] = $ans['response_value'];
                    }
                }
            }
            ?>
            <?php if (empty($textResponses)): ?>
            <p class="text-muted small">No text responses.</p>
            <?php else: ?>
            <div class="list-group list-group-flush">
                <?php foreach ($textResponses as $i => $text): ?>
                <div class="list-group-item px-0">
                    <small class="text-muted">Response #<?php echo $i + 1; ?>:</small>
                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($text)); ?></p>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
        <?php if (!$hasText): ?>
        <p class="text-muted text-center mb-0">No qualitative questions in this survey.</p>
        <?php endif; ?>
    </div>
</div>

<!-- Individual Responses -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fas fa-list me-2 text-secondary"></i>Individual Responses (<?php echo count($reportData['responses']); ?>)</h5>
    </div>
    <div class="card-body p-0">
        <?php foreach ($reportData['responses'] as $resp): ?>
        <div class="p-3 border-bottom">
            <div class="d-flex justify-content-between mb-2">
                <small class="text-muted">
                    <i class="fas fa-clock me-1"></i><?php echo formatDate($resp['completed_at']); ?>
                </small>
                <small class="text-muted">
                    <i class="fas fa-hourglass me-1"></i><?php echo $resp['time_spent'] ? formatDuration($resp['time_spent']) : 'N/A'; ?>
                </small>
            </div>
            <?php foreach ($resp['answers'] as $ans): ?>
            <div class="mb-1">
                <small class="fw-medium"><?php echo htmlspecialchars(substr($ans['question_text'], 0, 100)); ?>:</small>
                <span class="small">
                    <?php 
                    if ($ans['response_numeric'] !== null) {
                        echo $ans['response_numeric'];
                    } elseif (!empty($ans['response_value'])) {
                        echo htmlspecialchars(substr($ans['response_value'], 0, 200));
                    } else {
                        echo '<em class="text-muted">No response</em>';
                    }
                    ?>
                </span>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<?php elseif ($surveyId && !$reportData): ?>
<div class="alert alert-warning">
    <i class="fas fa-exclamation-triangle me-2"></i>Survey not found or no data available.
</div>
<?php elseif (!$surveyId): ?>
<div class="card border-0 shadow-sm">
    <div class="card-body text-center py-5">
        <i class="fas fa-file-alt fa-5x text-muted mb-3"></i>
        <h4>Generate a Survey Report</h4>
        <p class="text-muted">Select a survey to generate a comprehensive report with quantitative statistics, qualitative text analysis, and individual response data.</p>
    </div>
</div>
<?php endif; ?>

<style>
@media print {
    .navbar, .footer, .btn, form, .btn-group { display: none !important; }
    .card { box-shadow: none !important; border: 1px solid #dee2e6 !important; }
    #reportHeader { border: none !important; }
}
</style>

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