<?php
/**
 * Responses Page - Response Review and Thematic Coding
 * Research Survey Management System
 */

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

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

$survey = null;
$codes = [];
$responses = [];

if ($surveyId) {
    $survey = getSurveyWithQuestions($surveyId);
    if (!$survey || !canViewSurvey($surveyId)) {
        $_SESSION['flash_message'] = 'Survey not found or insufficient permissions.';
        $_SESSION['flash_type'] = 'danger';
        header('Location: ' . BASE_URL . '/pages/surveys.php');
        exit;
    }
    
    $projectId = $survey['project_id'] ?? null;
    if ($projectId) {
        $stmt = $pdo->prepare("SELECT code_id, code_name, color_code FROM thematic_codes 
                               WHERE project_id = :pid OR survey_id = :sid ORDER BY code_name");
        $stmt->execute(['pid' => $projectId, 'sid' => $surveyId]);
        $codes = $stmt->fetchAll();
    }
    
    $stmt = $pdo->prepare("
        SELECT sr.response_id, sr.completed_at, sr.time_spent_seconds, sr.status,
               sp.email, sp.anonymous_identifier
        FROM survey_responses sr
        LEFT JOIN survey_participants sp ON sr.participant_id = sp.participant_id
        WHERE sr.survey_id = :sid
        ORDER BY sr.completed_at DESC
        LIMIT 100
    ");
    $stmt->execute(['sid' => $surveyId]);
    $rawResponses = $stmt->fetchAll();
    
    foreach ($rawResponses as $resp) {
        $stmt = $pdo->prepare("
            SELECT qr.question_response_id, qr.response_value, qr.response_numeric,
                   q.question_text, q.question_type
            FROM question_responses qr
            JOIN survey_questions q ON qr.question_id = q.question_id
            WHERE qr.response_id = :rid
            ORDER BY q.question_order
        ");
        $stmt->execute(['rid' => $resp['response_id']]);
        $answers = $stmt->fetchAll();
        
        $responses[] = array_merge($resp, ['answers' => $answers]);
    }
}

// Handle code application
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $qrid = isset($_POST['question_response_id']) ? (int)$_POST['question_response_id'] : 0;
    $codeId = isset($_POST['code_id']) ? (int)$_POST['code_id'] : 0;
    $action = $_POST['action'];
    
    if ($qrid && $codeId) {
        if ($action === 'add_code') {
            $stmt = $pdo->prepare("INSERT INTO coding_assignments (question_response_id, code_id, coder_id, is_auto_generated) 
                                   VALUES (:qrid, :cid, :uid, 0) 
                                   ON DUPLICATE KEY UPDATE coded_at = NOW()");
            $stmt->execute(['qrid' => $qrid, 'cid' => $codeId, 'uid' => $_SESSION['user_id']]);
            logAudit('create', 'coding_assignment', $qrid);
        } elseif ($action === 'remove_code') {
            $stmt = $pdo->prepare("DELETE FROM coding_assignments 
                                   WHERE question_response_id = :qrid AND code_id = :cid AND coder_id = :uid");
            $stmt->execute(['qrid' => $qrid, 'cid' => $codeId, 'uid' => $_SESSION['user_id']]);
            logAudit('delete', 'coding_assignment', $qrid);
        }
        
        header('Location: ' . BASE_URL . '/pages/responses.php?survey_id=' . $surveyId);
        exit;
    }
}

// Handle code removal via GET
if (isset($_GET['remove_code']) && isset($_GET['code_id']) && canViewSurvey($surveyId)) {
    $qrid = (int)$_GET['remove_code'];
    $cid = (int)$_GET['code_id'];
    $stmt = $pdo->prepare("DELETE FROM coding_assignments WHERE question_response_id = :qrid AND code_id = :cid AND coder_id = :uid");
    $stmt->execute(['qrid' => $qrid, 'cid' => $cid, 'uid' => $_SESSION['user_id']]);
    logAudit('delete', 'coding_assignment', $qrid);
    header('Location: ' . BASE_URL . '/pages/responses.php?survey_id=' . $surveyId);
    exit;
}

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

<div class="dashboard-header">
    <div>
        <h1><i class="fas fa-reply-all me-2 text-primary"></i>Responses</h1>
        <p>Review, analyze, and code qualitative responses</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</label>
                <select class="form-select form-select-lg" name="survey_id" onchange="this.form.submit()">
                    <option value="">-- Choose a survey --</option>
                    <?php
                    $stmt = $pdo->prepare("SELECT survey_id, title FROM surveys 
                                           WHERE created_by = :uid OR project_id IN (
                                               SELECT project_id FROM project_members WHERE user_id = :uid
                                           )
                                           ORDER BY created_at DESC");
                    $stmt->execute(['uid' => $_SESSION['user_id']]);
                    $accessibleSurveys = $stmt->fetchAll();
                    foreach ($accessibleSurveys 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">Load Responses</button>
            </div>
            <div class="col-md-2">
                <a href="<?php echo BASE_URL; ?>/pages/analytics.php?survey_id=<?php echo $surveyId; ?>" 
                   class="btn btn-outline-success w-100 <?php echo !$surveyId ? 'disabled' : ''; ?>">
                    <i class="fas fa-chart-bar me-1"></i> Analytics
                </a>
            </div>
        </form>
    </div>
</div>

<?php if ($surveyId && $survey): ?>

<?php if (empty($responses)): ?>
<div class="alert alert-info">
    <i class="fas fa-info-circle me-2"></i>No responses found for this survey yet.
</div>
<?php else: ?>

<!-- Response Stats -->
<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm bg-primary text-white">
            <div class="card-body text-center">
                <h3 class="mb-0"><?php echo count($responses); ?></h3>
                <small>Total Responses Loaded</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm bg-success text-white">
            <div class="card-body text-center">
                <h3 class="mb-0"><?php echo count($codes); ?></h3>
                <small>Available Codes</small>
            </div>
        </div>
    </div>
    <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-tags me-2 text-warning"></i>Available Codes</h5>
            </div>
            <div class="card-body">
                <div class="d-flex flex-wrap gap-2">
                    <?php foreach ($codes as $code): ?>
                    <span class="badge rounded-pill" style="background-color: <?php echo htmlspecialchars($code['color_code']); ?>20; color: <?php echo htmlspecialchars($code['color_code']); ?>;">
                        <?php echo htmlspecialchars($code['code_name']); ?>
                    </span>
                    <?php endforeach; ?>
                    <?php if (empty($codes)): ?>
                    <span class="text-muted">No codes defined. Go to Analytics > Thematic Codes to create them.</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Responses List -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white">
        <h5 class="mb-0"><i class="fas fa-list me-2 text-primary"></i>Response Details & Coding</h5>
    </div>
    <div class="card-body p-0">
        <?php foreach ($responses as $resp): ?>
        <div class="p-3 border-bottom">
            <div class="d-flex justify-content-between align-items-start mb-2">
                <div>
                    <h6 class="mb-0">
                        <span class="badge bg-primary me-2">Response #<?php echo $resp['response_id']; ?></span>
                        <?php echo formatDate($resp['completed_at'], 'M d, Y H:i'); ?>
                    </h6>
                    <small class="text-muted">
                        Time spent: <?php echo $resp['time_spent_seconds'] ? formatDuration($resp['time_spent_seconds']) : 'N/A'; ?>
                        <?php if ($resp['email']): ?>
                        &middot; <?php echo htmlspecialchars($resp['email']); ?>
                        <?php endif; ?>
                    </small>
                </div>
                <span class="badge bg-<?php echo $resp['status'] === 'completed' ? 'success' : 'warning'; ?>">
                    <?php echo ucfirst($resp['status']); ?>
                </span>
            </div>
            
            <?php foreach ($resp['answers'] as $ans): 
                $isText = in_array($ans['question_type'], ['text_short', 'text_long', 'rich_text']);
                if (!$isText || empty($ans['response_value'])) continue;
            ?>
            <div class="mt-3 p-3 bg-light rounded">
                <small class="text-muted d-block mb-1"><?php echo htmlspecialchars($ans['question_text']); ?></small>
                <p class="mb-2">"<?php echo htmlspecialchars($ans['response_value']); ?>"</p>
                
                <?php if (!empty($codes)): 
                    $stmt = $pdo->prepare("SELECT ca.coding_assignment_id, c.code_name, c.color_code
                                           FROM coding_assignments ca
                                           JOIN thematic_codes c ON ca.code_id = c.code_id
                                           WHERE ca.question_response_id = :qrid AND ca.coder_id = :uid");
                    $stmt->execute(['qrid' => $ans['question_response_id'], 'uid' => $_SESSION['user_id']]);
                    $appliedCodes = $stmt->fetchAll();
                    $appliedCodeIds = array_column($appliedCodes, 'code_id');
                ?>
                <div class="d-flex flex-wrap gap-2 mb-2">
                    <?php foreach ($appliedCodes as $ac): ?>
                    <span class="badge" style="background-color: <?php echo htmlspecialchars($ac['color_code']); ?>20; color: <?php echo htmlspecialchars($ac['color_code']); ?>;">
                        <?php echo htmlspecialchars($ac['code_name']); ?>
                        <a href="?survey_id=<?php echo $surveyId; ?>&remove_code=<?php echo $ans['question_response_id']; ?>&code_id=<?php echo $ac['code_id']; ?>" 
                           class="text-decoration-none ms-1" onclick="return confirm('Remove code?')">&times;</a>
                    </span>
                    <?php endforeach; ?>
                    <?php if (empty($appliedCodes)): ?>
                    <span class="text-muted small">No codes applied</span>
                    <?php endif; ?>
                </div>
                <form method="POST" class="d-flex gap-2">
                    <input type="hidden" name="action" value="add_code">
                    <input type="hidden" name="question_response_id" value="<?php echo $ans['question_response_id']; ?>">
                    <select class="form-select form-select-sm" name="code_id" style="max-width:200px">
                        <option value="">Apply Code...</option>
                        <?php foreach ($codes as $code): ?>
                        <option value="<?php echo $code['code_id']; ?>"><?php echo htmlspecialchars($code['code_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" class="btn btn-sm btn-primary">Apply</button>
                </form>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<?php endif; ?>
<?php elseif (!$surveyId): ?>
<div class="card border-0 shadow-sm">
    <div class="card-body text-center py-5">
        <i class="fas fa-reply-all fa-5x text-muted mb-3"></i>
        <h4>Select a Survey</h4>
        <p class="text-muted">Choose a survey from the dropdown above to review responses.</p>
    </div>
</div>
<?php endif; ?>

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