<?php
// ... (PHP code remains UNCHANGED for functionality) ...
// 1. ENABLE ERROR REPORTING (Remove these lines when live)
ini_set('display_errors', 1);

ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


// Database configuration (UPDATED)
$host = 'localhost';
$dbname = 'cyradriv_exam_time'; // NEW DATABASE NAME
$username = 'cyradriv_exam_time'; // NEW USERNAME
$password = '#2022Next'; // NEW PASSWORD

$success = false;
$error = '';
$training_details = null; 
$client_company_name = "[Client Company Name]"; // Will be overwritten by DB fetch


// ENCRYPTION/DECRYPTION KEY (DO NOT SHARE OR EXPOSE)
$key = "hG72kLmP94QwXc8tZbR1nT6pVfE3yU0A";

// Decrypting the training_id from the URL
$training_id = null;
if (isset($_GET['training_id'])) {
    $encrypted = $_GET['training_id'];

    // Restore base64 formatting
    $encrypted = strtr($encrypted, '-_', '+/');
    $encrypted = base64_decode($encrypted);

    if (strlen($encrypted) >= 16) {
        $iv = substr($encrypted, 0, 16);
        $ciphertext = substr($encrypted, 16);

        // Attempt decryption
        $decrypted_id = openssl_decrypt($ciphertext, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv);
        
        if ($decrypted_id !== false && !empty($decrypted_id)) {
            $training_id = $decrypted_id;
        }
    }
}

// --- DATABASE LOOKUP FOR TRAINING DETAILS (Including NEW client_name column) ---
if (!empty($training_id)) {
    try {
        // Re-establish PDO connection with new credentials
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // UPDATED QUERY to fetch the new client_name column
        $stmt = $pdo->prepare("SELECT `course_name`, `instructor_name`, `course_date`, `course_time`, `course_venue`, `client_name` FROM `tm_training` WHERE id = ?");
        $stmt->execute([(int)$training_id]);
        $training_details = $stmt->fetch(PDO::FETCH_OBJ);
        
        // Set the client company name from the DB
        if ($training_details && !empty($training_details->client_name)) {
            $client_company_name = $training_details->client_name;
        }

    } catch (PDOException $e) {
        error_log("Training Detail Lookup Error: " . $e->getMessage());
        $error = "Could not fetch training details. Check database connection/table structure.";
    }
}


// --- FEEDBACK QUESTIONS DEFINITION (Unchanged) ---
$feedback_questions = [
    [ 'category' => "Instructor Evaluation", 'questions' => [
        [ 'id' => "instructor_knowledge", 'text' => "Instructor’s knowledge of the subject matter" ], 
        [ 'id' => "instructor_response", 'text' => "Instructor’s response to questions" ], 
        [ 'id' => "instructor_relevance", 'text' => "Instructor’s ability to provide real world examples" ], 
        [ 'id' => "instructor_delivery", 'text' => "Instructor’s presentation skills" ], 
        [ 'id' => "instructor_overall", 'text' => "Instructor’s overall performance" ] 
    ]],
    [ 'category' => "Training Content", 'questions' => [
        [ 'id' => "content_clarity", 'text' => "Clarity of the training content" ], 
        [ 'id' => "content_flow", 'text' => "Flow of the training content" ], 
        [ 'id' => "content_depth", 'text' => "Depth of the training content" ], 
        [ 'id' => "content_effectiveness", 'text' => "Effectiveness of the exercises in knowledge/skills learned" ], 
        [ 'id' => "content_relevance", 'text' => "Relevance of the exercises to real world situations" ], 
        [ 'id' => "content_time", 'text' => "Time dedicated to discussions and practices" ] 
    ]],
    [ 'category' => "Learning Effectiveness", 'questions' => [
        [ 'id' => "learning_gained", 'text' => "Knowledge and skills gained from this training" ], 
        [ 'id' => "learning_impact", 'text' => "Impact of this training on your productivity related to the subject" ], 
        [ 'id' => "overall_rating", 'text' => "How do you rate the training overall?" ] 
    ]]
];

$objective_options = [
    'objective_solve' => "Solve a particular problem", 
    'objective_prepare_deploy' => "Prepare for a new product deployment or software upgrade", 
    'objective_cert' => "Prepare for certification exam", 
    'objective_build' => "Build new skills and knowledge" 
];


function get_flat_questions($data, $objective_options) {
    $flat_questions = [];
    $flat_ids = [];
    
    // 1. Core Ratings
    foreach ($data as $category_data) {
        foreach ($category_data['questions'] as $q) {
            $flat_questions[$q['id']] = $q['text'];
            $flat_ids[] = $q['id'];
        }
    }
    
    // 2. Objectives (Checkboxes)
    foreach ($objective_options as $id => $text) {
        $flat_questions[$id] = $text;
        $flat_ids[] = $id;
    }
    
    // 3. Open-ended questions (Text areas)
    $flat_questions['open_suggestions'] = 'Suggestions for improving the course or Overall Training Experience?'; 
    $flat_questions['open_future_topics'] = 'Are there any additional training topics or courses you would be interested in attending in the future?'; 
    $flat_questions['open_objectives_others'] = 'Others (Please specify)'; 

    
    $flat_ids[] = 'open_suggestions';
    $flat_ids[] = 'open_future_topics';
    $flat_ids[] = 'open_objectives_others';

    return ['questions' => $flat_questions, 'ids' => $flat_ids];
}

$flat_data = get_flat_questions($feedback_questions, $objective_options);
$question_map = $flat_data['questions'];
$question_ids = $flat_data['ids'];


// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    if (empty($training_id)) {
        $error = "Invalid training link or ID.";
    } else {
        try {
            if (!isset($pdo)) {
                $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            
            $pdo->beginTransaction();
            
            // Company name is now explicitly set from the DB value (or default)
            $submitted_company_name = $_POST['company_name'] ?? $client_company_name; 
            
            $question_json = json_encode($question_map);
            
            // Collect all data points, including checkboxes
            $ratings_data = [];
            foreach ($question_ids as $id) {
                if (isset($_POST[$id])) {
                    $ratings_data[$id] = $_POST[$id];
                } else {
                    $ratings_data[$id] = null;
                }
            }
            
            $ratings_data['open_suggestions'] = $_POST['open_suggestions'] ?? ''; 
            $ratings_data['open_future_topics'] = $_POST['open_future_topics'] ?? ''; 
            $ratings_data['open_objectives_others'] = $_POST['open_objectives_others'] ?? ''; 


            $ratings_json = json_encode($ratings_data);
            
            // Insert into the combined tm_feedback table
            $stmt = $pdo->prepare("INSERT INTO tm_feedback (training_id, student_name, email, job_role, company_name, question_json, ratings_json, submitted_at) VALUES (:training_id, :student_name, :email, :job_role, :company_name, :question_json, :ratings_json, NOW())");
            
            $stmt->execute([
                ':training_id' => (int)$training_id, 
                ':student_name' => $_POST['full_name'],
                ':email' => !empty($_POST['email']) ? $_POST['email'] : null,
                ':job_role' => $_POST['job_role'] ?? null,
                ':company_name' => $submitted_company_name,
                ':question_json' => $question_json,
                ':ratings_json' => $ratings_json
            ]);
            
            $pdo->commit();
            $success = true;
            
        } catch (PDOException $e) {
            if (isset($pdo) && $pdo->inTransaction()) {
                $pdo->rollBack();
            }
            error_log("Feedback Submission Error: " . $e->getMessage()); 
            $error = "A database error occurred. Please try again or contact support.";
        } catch (Exception $e) {
            $error = "An unexpected error occurred: " . $e->getMessage();
        }
    }
}

// --- PHP FUNCTIONS FOR FORM GENERATION ---

function generate_star_rating($name, $required = true) {
    echo '<div class="star-rating-container">';
    echo '<div class="star-rating">';
    for ($i = 5; $i >= 1; $i--) {
        $id = $name . '-' . $i;
        $reqAttr = ($required && $i === 5) ? ' required' : ''; 
        echo '<input type="radio" id="' . $id . '" name="' . $name . '" value="' . $i . '"' . $reqAttr . '>';
        echo '<label for="' . $id . '" title="' . $i . ' stars">&#9733;</label>'; 
    }
    echo '</div>';
    echo '</div>';
}

function generate_checkbox_input($id) {
    echo '<div class="checkbox-input-container">';
    echo '<input type="checkbox" id="' . $id . '_cb" name="' . $id . '" value="1" class="custom-checkbox">';
    echo '</div>';
}

function generate_text_input($name, $placeholder = 'Enter your answer', $required = false, $rows = 5) {
    echo '<div class="text-input-container">';
    $reqAttr = $required ? ' required' : '';
    echo '<textarea class="text-input" name="' . $name . '" rows="' . $rows . '"' . $reqAttr . ' placeholder="' . $placeholder . '"></textarea>';
    echo '</div>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Time Training Center Feedback Form</title>
    <style>
        /* BASE STYLES & RESET */
        * { margin: 0; padding: 0; box-sizing: border-box; }
        :root {
            --primary-color: #004B75; /* TTC Dark Blue (Main Brand Color) */
            --secondary-color: #333333; /* Dark Gray (Text/Headers) */
            --accent-color: #ffc107; /* Star Yellow */
            --bg-color: #f4f7f9; 
            --font-color-dark: #222222;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: var(--bg-color); 
            min-height: 100vh;
            padding: 20px 10px; 
        }
        .container {
            max-width: 800px; 
            margin: 0 auto;
            background: white;
            border-radius: 16px; 
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            position: relative;
        }
        .alert-success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; padding: 15px; margin: 20px; border-radius: 8px; }
        .alert-error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; padding: 15px; margin: 20px; border-radius: 8px; }

        /* --- HEADER & BRANDING (REFINED) --- */
        .header {
            background: linear-gradient(135deg, var(--primary-color) 0%, #006b9b 100%); /* Subtle Gradient */
            padding: 30px 40px; 
            color: white;
            text-align: center;
            border-bottom: 5px solid var(--accent-color); /* Highlight color line */
        }
        .logo-container { margin-bottom: 10px; }
        .logo-container img { max-width: 180px; height: auto; filter: brightness(0) invert(1); /* Invert logo for white background */ } 
        .header h1 { 
            font-size: 32px; 
            font-weight: 800; 
            margin-bottom: 5px; 
            color: white;
            text-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
        }
        .header p { 
            font-size: 16px; 
            opacity: 0.9;
        }

        /* Training Details Block */
        .header-info {
            font-size: 15px; 
            line-height: 1.6; 
            background: rgba(255, 255, 255, 0.1); /* Slightly transparent white background */
            padding: 15px 20px;
            border-radius: 8px;
            margin-top: 20px;
            text-align: left;
        }
        .header-info div {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
        }
        .header-info strong { 
            font-weight: 600; 
            display: inline-block; 
            min-width: 100px;
            color: var(--accent-color); /* Highlight labels in yellow */
            margin-right: 10px;
        }
        .header-info span {
            color: white;
            font-weight: 400;
        }
        .form-content { padding: 40px; }

        /* SECTION TITLES */
        .section-title {
            font-weight: 700; 
            font-size: 24px; 
            color: var(--primary-color); 
            border-left: 5px solid var(--accent-color); 
            padding-left: 15px;
            margin-bottom: 30px; 
            margin-top: 40px; 
            text-transform: uppercase;
        }

        /* INPUTS & GROUPS */
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; }
        .form-group label { font-size: 15px; color: var(--font-color-dark); margin-bottom: 8px; display: block; font-weight: 600; }
        .form-input {
            width: 100%; padding: 12px; border: 1px solid #d0d0d0;
            border-radius: 8px; 
            font-size: 15px; font-family: inherit;
            transition: border-color 0.2s, box-shadow 0.2s;
        }
        .form-input:focus { outline: none; border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(0, 75, 117, 0.15); } 
        .form-input.invalid { border-color: #d32f2f; }
        
        /* QUESTION LAYOUT (Rating/Checkbox) */
        .question { 
            margin-bottom: 25px; 
            display: flex; 
            align-items: center; 
            justify-content: space-between;
            padding: 15px 0; 
            border-bottom: 1px solid #e0e0e0;
        }
        .question-block {
            display: flex; 
            align-items: flex-start; 
            flex-grow: 1;
            padding-right: 20px;
        }
        .question-text { 
            color: var(--font-color-dark); 
            font-size: 16px; 
            line-height: 1.4; 
            font-weight: 500;
        }
        .required { color: #d32f2f; margin-left: 4px; }
        
        /* STAR RATING */
        .star-rating-container { 
            flex-shrink: 0; 
            padding-right: 5px;
        }
        .star-rating { 
            display: flex; 
            flex-direction: row-reverse; 
            gap: 2px; 
        }
        .star-rating input[type="radio"] { 
            opacity: 0;
            width: 0;
            height: 0;
            position: absolute;
        }
        .star-rating label {
            font-size: 28px; 
            color: #ddd; 
            cursor: pointer;
            transition: color 0.2s; 
            line-height: 1; 
            padding: 0 3px;
        }
        .star-rating label:hover, .star-rating label:hover ~ label, .star-rating input:checked ~ label { color: var(--accent-color); }
        
        /* Error Message Styles */
        .error-msg { 
            font-size: 12px; 
            color: #d32f2f; 
            display: none; 
            width: 100%; 
            padding-top: 5px;
            order: 3; /* Move error message to the bottom on mobile */
        }
        
        /* CHECKBOX OBJECTIVES STYLES */
        .objective-list-container {
            padding-top: 15px;
            padding-bottom: 5px;
            border-bottom: 1px solid #f0f0f0; 
        }
        .objective-item {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        .custom-checkbox {
            appearance: none;
            width: 22px;
            height: 22px;
            border: 2px solid var(--primary-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            transition: background-color 0.2s, border-color 0.2s;
            flex-shrink: 0;
        }
        .custom-checkbox:checked {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        .custom-checkbox:checked::before {
            content: '\2713'; 
            display: block;
            width: 100%;
            height: 100%;
            text-align: center;
            line-height: 18px;
            font-size: 16px;
            font-weight: bold;
            color: white;
        }
        .checkbox-label { 
            margin-left: 12px; 
            color: #333;
            font-weight: 500;
            cursor: pointer;
        }

        /* TEXT AREAS */
        .text-input-container { margin-top: 8px; } 

        .text-input {
            width: 100%; padding: 14px; border: 1px solid #d0d0d0;
            border-radius: 8px; 
            font-size: 15px; font-family: inherit;
            resize: vertical; min-height: 100px;
        }
        
        /* BUTTONS & FOOTER */
        .buttons-container {
            margin-top: 40px; 
            padding-top: 20px;
            text-align: center;
        }
        .btn-submit {
            display: inline-block; 
            width: 100%;
            max-width: 350px; 
            padding: 15px 30px; 
            font-size: 18px;
            background-color: var(--primary-color); 
            border: none;
            color: white;
            font-weight: 600;
            cursor: pointer;
            border-radius: 50px; 
            transition: background-color 0.3s, box-shadow 0.3s;
        }
        .btn-submit:hover { 
            background-color: #003657; 
            box-shadow: 0 6px 15px rgba(0, 75, 117, 0.3);
        }

        .footer { background: #f5f5f5; padding: 20px 40px; border-top: 1px solid #e0e0e0; text-align: center; border-radius: 0 0 16px 16px; }
        
        /* --- RESPONSIVE LAYOUT (REFINED) --- */
        @media (max-width: 768px) {
            body { padding: 10px; }
            .container { border-radius: 8px; }
            .header, .form-content, .footer { padding: 20px; }
            .header h1 { font-size: 28px; }
            .header-info div { /* Adjust header info for single column on mobile */
                flex-direction: column;
                align-items: flex-start;
                margin-bottom: 10px;
            }
            .header-info strong {
                min-width: unset;
                margin-right: 0;
                margin-bottom: 4px;
            }
            .form-row { grid-template-columns: 1fr; }
            .section-title { font-size: 20px; margin-top: 30px; }
            
            /* Question stacking on mobile */
            .question { 
                flex-direction: column;
                align-items: flex-start;
                padding: 15px 0;
            }
            .question-block {
                padding-right: 0;
                margin-bottom: 10px;
                width: 100%;
            }
            .star-rating-container {
                width: 100%;
                /* Use flex for centering on mobile */
                display: flex;
                justify-content: center;
                padding-right: 0;
            }
            .star-rating {
                justify-content: center;
                gap: 5px; 
            }
            .star-rating label {
                font-size: 38px; /* Larger tap target */
            }
            .error-msg {
                text-align: left;
                margin-top: 5px;
            }
            .btn-submit {
                max-width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <?php if ($success): ?>
            <div class="alert alert-success">
                <strong>Success!</strong> Your feedback has been submitted successfully for Time Training Center.
            </div>
            <div class="footer">
                <div class="footer-brand"><span>Time Training Center - Upskilling Abu Dhabi since 1993</span></div>
            </div>
        <?php elseif ($error): ?>
            <div class="alert alert-error"><strong>Error!</strong> <?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <?php if (!$success): ?>
        <div class="header">
            <div class="logo-container">
                <img src="https://www.timetraining.ae/design/images/new_logo.png" alt="Time Training Center Logo">
            </div>
            
            <h1 id="client-greeting">Welcome to the Feedback Form</h1>
            
            <div class="header-info">
                <?php if ($training_details): ?>
                    <div><strong>Company:</strong> <span id="client-company-display"><?php echo htmlspecialchars($client_company_name); ?></span></div>
                    <div><strong>Course:</strong> <span><?php echo htmlspecialchars($training_details->course_name); ?></span></div>
                    <div><strong>Instructor:</strong> <span><?php echo htmlspecialchars($training_details->instructor_name); ?></span></div>
                    <div><strong>Venue:</strong> <span><?php echo htmlspecialchars($training_details->course_venue); ?></span></div>
                    <div><strong>Date/Time:</strong> <span><?php echo date('M d, Y', strtotime($training_details->course_date)); ?> at <?php echo date('h:i A', strtotime($training_details->course_time)); ?></span></div>
                <?php else: ?>
                    <p>Training details could not be loaded. Please proceed with the form.</p>
                <?php endif; ?>
            </div>
        </div>

        <form class="form-content" id="feedbackForm" method="POST" action="">
            
            <input type="hidden" name="company_name" value="<?php echo htmlspecialchars($client_company_name); ?>">

            <div class="section-title">Participant Information</div>
            <div class="form-group">
                <label for="full_name">Full Name <span class="required">*</span></label>
                <input type="text" id="full_name" name="full_name" class="form-input" required placeholder="Enter your full name">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Designation (Job Role)</label>
                    <input type="text" name="job_role" class="form-input" placeholder="Your Designation">
                </div>
                <div class="form-group">
                    <label>Email Address</label>
                    <input type="email" name="email" class="form-input" placeholder="your.email@example.com (Participant Email)">
                </div>
            </div>
            <div class="section-title">Pre-Training Objective</div>
            <div class="question" style="display: block; border-bottom: none;" data-required="false">
                <div class="question-block">
                    <div class="question-text">
                        What was your main objective for the training? (Tick all that apply)
                    </div>
                </div>
                
                <div class="objective-list-container space-y-3">
                    <?php foreach ($objective_options as $id => $text): ?>
                        <div class="objective-item">
                            <input type="checkbox" id="<?php echo $id; ?>" name="<?php echo $id; ?>" value="1" class="custom-checkbox">
                            <label for="<?php echo $id; ?>" class="checkbox-label"><?php echo htmlspecialchars($text); ?></label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <label style="color:red">Please rate your level of agreement with each of the following statements, 5 is the highest level of agreement. ✓</label>
            
            <?php 
            foreach ($feedback_questions as $category_data): 
            ?>
                <div class="section-title"><?php echo htmlspecialchars($category_data['category']); ?></div>
                <?php 
                foreach ($category_data['questions'] as $q): 
                ?>
                    <div class="question" data-required="true">
                        <div class="question-block">
                            <div class="question-text">
                                <?php echo htmlspecialchars($q['text']); ?> <span class="required">*</span>
                            </div>
                        </div>
                        <?php 
                        generate_star_rating($q['id'], true); 
                        ?>
                        <div class="error-msg">Please select a rating.</div>
                    </div>
                <?php endforeach; ?>
            <?php endforeach; ?>
            
            <div class="section-title">Pre-Training Objective</div>
            <div class="question" style="display: block; border-bottom: none;" data-required="false">
                <div class="question-block">
                    <div class="question-text">
                        What was your main objective for the training? (Tick all that apply)
                    </div>
                </div>
                
                <div class="objective-list-container space-y-3">
                    <?php foreach ($objective_options as $id => $text): ?>
                        <div class="objective-item">
                            <input type="checkbox" id="<?php echo $id; ?>" name="<?php echo $id; ?>" value="1" class="custom-checkbox">
                            <label for="<?php echo $id; ?>" class="checkbox-label"><?php echo htmlspecialchars($text); ?></label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div class="form-group" style="padding-bottom: 20px; border-bottom: 1px solid #f0f0f0;">
                <label>Others (Please specify):</label>
                <input type="text" name="open_objectives_others" class="form-input" placeholder="Specify other objective...">
            </div>


            <div class="section-title">Suggestions and Future Interests</div>
            
            <div class="form-group">
                <label>What are your **Suggestions** for improving the course or Overall Training Experience?</label>
                <?php generate_text_input('open_suggestions', 'Suggestions...', false, 5); ?>
            </div>

            <div class="form-group">
                <label>Are there any additional training topics or courses you would be interested in attending in the future?</label>
                <?php generate_text_input('open_future_topics', 'If yes, please specify topic/course...', false, 3); ?>
            </div>

            <div class="buttons-container">
                <button type="submit" class="btn btn-submit">
                    Submit Feedback
                </button>
            </div>
        </form>

        <div class="footer">
            <div class="footer-brand"><span>Time Training Center - Upskilling Abu Dhabi since 1993</span></div>
        </div>
        <?php endif; ?>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Function to update the header greeting
            const updateClientName = () => {
                const fullNameInput = document.getElementById('full_name');
                const clientGreeting = document.getElementById('client-greeting');
                
                let name = fullNameInput ? fullNameInput.value.trim() : '';
                
                if (clientGreeting) {
                    if (name) {
                        // Display a personalized greeting
                        clientGreeting.textContent = `Thank you, ${name}, for your valuable feedback.`;
                    } else {
                        // Default greeting
                        clientGreeting.textContent = 'Training Feedback Form';
                    }
                }
            };

            // Initial call and attach event listener
            const fullNameInput = document.getElementById('full_name');
            if (fullNameInput) {
                fullNameInput.addEventListener('input', updateClientName);
                // Call once to set initial state if name is pre-filled or empty
                updateClientName(); 
            }
            
            // --- Simple Form Validation for the Single Page View ---
            document.getElementById('feedbackForm').addEventListener('submit', function(e) {
                let isValid = true;
                
                // 1. Validate required text/email inputs
                const requiredInputs = this.querySelectorAll('input[required]');
                requiredInputs.forEach(input => {
                    if (input.value.trim() === '') {
                        input.classList.add('invalid');
                        isValid = false;
                    } else {
                        input.classList.remove('invalid');
                    }
                });
                
                // 2. Validate mandatory star rating groups
                const ratingContainers = this.querySelectorAll('.question[data-required="true"]');
                let firstInvalidRating = null;

                ratingContainers.forEach(container => {
                    const radioInput = container.querySelector('input[type="radio"]');
                    if (!radioInput) return;

                    const name = radioInput.name;
                    const isChecked = container.querySelector(`input[name="${name}"]:checked`);
                    const errorMsg = container.querySelector('.error-msg');
                    
                    if (!isChecked) {
                        if (errorMsg) errorMsg.style.display = 'block';
                        if (!firstInvalidRating) firstInvalidRating = container;
                        isValid = false;
                    } else {
                        if (errorMsg) errorMsg.style.display = 'none';
                    }
                });

                if (!isValid) {
                    e.preventDefault();
                    // Scroll to the first invalid element
                    const firstInvalidInput = this.querySelector('.invalid');
                    const scrollToElement = firstInvalidInput || firstInvalidRating;
                    
                    if (scrollToElement) {
                        scrollToElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }
                    alert("Please fill in all required fields and complete all star ratings.");
                }
            });
        });
    </script>
</body>
</html>