<?php
// feedback.php

$dbHost = "localhost";
$dbName = "raintelsnew";
$dbUser = "dbuser";
$dbPass = "RaiSr#5an";

try {
    $pdo = new PDO(
        "mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4",
        $dbUser,
        $dbPass,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (Exception $e) {
    die("Database connection failed.");
}

$token = $_GET['token'] ?? '';

if (!$token) {
    die("Invalid feedback link.");
}

$stmt = $pdo->prepare("SELECT * FROM feedback_tokens WHERE token = ?");
$stmt->execute([$token]);
$tokenData = $stmt->fetch();

if (!$tokenData) {
    die("Invalid or expired feedback link.");
}

if ($tokenData['is_used']) {
    $alreadySubmitted = true;
} else {
    $alreadySubmitted = false;
}

 $alreadySubmitted = false;

$success = false;
$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$alreadySubmitted) {
    $required = ['q1','q2','q3','q4','q5','q6','q7','q9','q10','q11','q12'];

    foreach ($required as $field) {
        if (!isset($_POST[$field]) || $_POST[$field] === '') {
            $error = "Please answer all required questions.";
            break;
        }
    }

    if (!$error) {
        $q8 = isset($_POST['q8']) ? implode(", ", $_POST['q8']) : "";

        $insert = $pdo->prepare("
            INSERT INTO feedback_responses
            (
                token_id,
                client_name,
                client_email,
                q1, q2, q3, q4, q5,
                q6, q7, q8, q9,
                q10, q11, q12, q13,
                ip_address,
                user_agent
            )
            VALUES
            (
                ?, ?, ?,
                ?, ?, ?, ?, ?,
                ?, ?, ?, ?,
                ?, ?, ?, ?,
                ?, ?
            )
        ");

        $insert->execute([
            $tokenData['id'],
            $_POST['client_name'],
            $_POST['client_email'],

            $_POST['q1'],
            $_POST['q2'],
            $_POST['q3'],
            $_POST['q4'],
            $_POST['q5'],
            $_POST['q6'],
            $_POST['q7'],
            $q8,
            $_POST['q9'],
            $_POST['q10'],
            $_POST['q11'],
            $_POST['q12'],
            $_POST['q13'],

            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);

        $update = $pdo->prepare("
            UPDATE feedback_tokens 
            SET is_used = 1, submitted_at = NOW()
            WHERE id = ?
        ");
        $update->execute([$tokenData['id']]);

        $success = true;
        $alreadySubmitted = true;
    }
}

function ratingScale($name, $max = 5) {
    echo '<div class="rating-row">';
    for ($i = 1; $i <= $max; $i++) {
        echo '
        <label class="rating-box">
            <input type="radio" name="'.$name.'" value="'.$i.'" required>
            <span>'.$i.'</span>
        </label>';
    }
    echo '</div>';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>mHealth Application CSAT Survey | Raintels</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: "Inter", "Segoe UI", Arial, sans-serif;
            background: linear-gradient(135deg, #e8f7f7, #f8fbff);
            color: #243042;
        }

        .page {
            max-width: 980px;
            margin: 0 auto;
            padding: 28px 16px 60px;
        }

        .hero {
            background: linear-gradient(135deg, #008080, #0e5f73);
            color: white;
            border-radius: 26px;
            padding: 34px;
            box-shadow: 0 20px 45px rgba(0, 80, 90, 0.25);
            margin-bottom: 24px;
        }

        .hero h1 {
            margin: 0 0 10px;
            font-size: 32px;
            line-height: 1.2;
        }

        .hero p {
            margin: 0;
            opacity: 0.92;
            font-size: 16px;
            max-width: 760px;
        }

        .badges {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 20px;
        }

        .badge {
            background: rgba(255,255,255,0.16);
            border: 1px solid rgba(255,255,255,0.25);
            padding: 8px 13px;
            border-radius: 999px;
            font-size: 13px;
        }

        .form-card {
            background: white;
            border-radius: 26px;
            padding: 30px;
            box-shadow: 0 12px 35px rgba(25, 60, 80, 0.12);
        }

        .section-title {
            margin: 34px 0 18px;
            color: #008080;
            font-size: 18px;
            font-weight: 800;
            letter-spacing: 0.04em;
            text-transform: uppercase;
            border-bottom: 1px solid #e6eff1;
            padding-bottom: 10px;
        }

        .section-title:first-child {
            margin-top: 0;
        }

        .question {
            margin-bottom: 26px;
            padding: 20px;
            border: 1px solid #edf1f4;
            border-radius: 20px;
            background: #fbfefe;
        }

        .question h3 {
            margin: 0 0 12px;
            font-size: 17px;
            color: #1f2d3d;
            line-height: 1.5;
        }

        .hint {
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #6b7c8f;
            font-size: 13px;
            margin-top: 10px;
            width: 100%;
        }

        .hint span {
            width: 48%;
        }

        .hint span:last-child {
            text-align: right;
        }

        .rating-row {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 14px;
        }

        .rating-box input {
            position: absolute;
            opacity: 0;
            pointer-events: none;
        }

        .question.validation-error {
            border-color: #e53935;
            background: #fff7f7;
            box-shadow: 0 0 0 3px rgba(229, 57, 53, 0.08);
        }

        .field-error {
            color: #c62828;
            font-size: 13px;
            margin-top: 10px;
            font-weight: 600;
        }

        .rating-box span {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 48px;
            height: 44px;
            border-radius: 14px;
            border: 1px solid #d9e6e8;
            background: white;
            cursor: pointer;
            font-weight: 700;
            transition: 0.2s ease;
        }

        .rating-box input:checked + span {
            background: #008080;
            color: white;
            border-color: #008080;
            transform: translateY(-2px);
            box-shadow: 0 8px 16px rgba(0,128,128,0.25);
        }

        .option-list {
            display: grid;
            gap: 12px;
            margin-top: 14px;
        }

        .option {
            display: flex;
            gap: 10px;
            align-items: flex-start;
            padding: 13px 14px;
            border: 1px solid #dfeaed;
            border-radius: 14px;
            background: white;
            cursor: pointer;
            line-height: 1.4;
        }

        .option input {
            margin-top: 3px;
            accent-color: #008080;
        }

        textarea {
            width: 100%;
            min-height: 130px;
            border: 1px solid #dfeaed;
            border-radius: 16px;
            padding: 14px;
            font-size: 15px;
            resize: vertical;
            font-family: inherit;
        }

        textarea:focus {
            outline: none;
            border-color: #008080;
            box-shadow: 0 0 0 3px rgba(0,128,128,0.12);
        }

        .submit-area {
            margin-top: 34px;
            text-align: center;
        }

        .text-input {
            width: 100%;
            border: 1px solid #dfeaed;
            border-radius: 16px;
            padding: 14px;
            font-size: 15px;
            font-family: inherit;
            background: white;
        }

        .text-input:focus {
            outline: none;
            border-color: #008080;
            box-shadow: 0 0 0 3px rgba(0,128,128,0.12);
        }

        button {
            border: none;
            background: linear-gradient(135deg, #008080, #006d7a);
            color: white;
            font-size: 16px;
            font-weight: 800;
            padding: 15px 34px;
            border-radius: 999px;
            cursor: pointer;
            box-shadow: 0 12px 24px rgba(0,128,128,0.25);
        }

        button:hover {
            transform: translateY(-1px);
        }

        .message {
            background: white;
            border-radius: 24px;
            padding: 38px;
            text-align: center;
            box-shadow: 0 12px 35px rgba(25, 60, 80, 0.12);
        }

        .message h2 {
            color: #008080;
            margin-top: 0;
        }

        .error {
            background: #fff2f2;
            color: #a33131;
            padding: 14px 18px;
            border-radius: 14px;
            margin-bottom: 18px;
            border: 1px solid #ffd1d1;
        }

        .footer {
            text-align: center;
            margin-top: 24px;
            font-size: 13px;
            color: #7a8a99;
        }

        @media (max-width: 600px) {
            .hero {
                padding: 26px 22px;
                border-radius: 22px;
            }

            .hero h1 {
                font-size: 25px;
            }

            .form-card {
                padding: 20px;
            }

            .question {
                padding: 16px;
            }

            .rating-box span {
                width: 42px;
                height: 40px;
            }

            
        }

        @media (max-width: 600px) {

            .hint {
                display: flex;
                justify-content: space-between;
                flex-direction: row;
                gap: 10px;
                font-size: 12px;
            }

            .hint span:first-child {
                text-align: left;
            }

            .hint span:last-child {
                text-align: right;
            }
        }
    </style>
</head>

<body>
<div class="page">

    <div class="hero">
        <h1>mHealth Application CSAT Survey</h1>
        <p>
            Your feedback helps us ensure the solution meets your strategic and operational expectations.
            This survey covers the overall quality, delivery, collaboration, and value of the mHealth application
            developed by Raintels.
        </p>

        <div class="badges">
            <div class="badge">13 Questions</div>
            <div class="badge">~5 Minutes</div>
            <div class="badge">Confidential</div>
            <div class="badge">Raintels CSAT Survey</div>
        </div>
    </div>

    <?php if ($success): ?>

        <div class="message">
            <h2>Thank you for your feedback.</h2>
            <p>Your response has been submitted successfully.</p>
        </div>

    <?php elseif ($alreadySubmitted): ?>

        <div class="message">
            <h2>Feedback Already Submitted</h2>
            <p>This secure feedback link has already been used.</p>
        </div>

    <?php else: ?>

        <form method="POST" class="form-card">

            <?php if ($error): ?>
                <div class="error"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <div class="section-title">Respondent Details</div>

            <div class="question">
                <h3>Your Name</h3>
                <input 
                    type="text" 
                    name="client_name" 
                    required
                    placeholder="Enter your full name"
                    class="text-input"
                >
            </div>

            <div class="question">
                <h3>Email Address</h3>
                <input 
                    type="email" 
                    name="client_email" 
                    required
                    placeholder="Enter your email address"
                    class="text-input"
                >
            </div>

            <div class="section-title">Overall Satisfaction</div>

            <div class="question">
                <h3>Q1. How satisfied are you with the overall quality of the mHealth application delivered by Raintels?</h3>
                <?php ratingScale("q1"); ?>
                <div class="hint"><span>Very dissatisfied</span><span>Very satisfied</span></div>
            </div>

            <div class="question">
                <h3>Q2. How well did the delivered solution align with the project objectives and requirements defined at the outset?</h3>
                <?php ratingScale("q2"); ?>
                <div class="hint"><span>Not at all</span><span>Completely</span></div>
            </div>

            <div class="question">
                <h3>Q3. How would you rate the reliability and stability of the application based on your observations during UAT and demos?</h3>
                <?php ratingScale("q3"); ?>
                <div class="hint"><span>Very poor</span><span>Excellent</span></div>
            </div>

            <div class="section-title">Delivery & Execution</div>

            <div class="question">
                <h3>Q4. How satisfied are you with Raintels' adherence to timelines and milestone commitments throughout the project?</h3>
                <?php ratingScale("q4"); ?>
                <div class="hint"><span>Very dissatisfied</span><span>Very satisfied</span></div>
            </div>

            <div class="question">
                <h3>Q5. How effectively were risks, blockers, and change requests managed and communicated during the engagement?</h3>
                <div class="option-list">
                    <?php
                    $q5Options = [
                        "Extremely well — proactive and transparent at all times",
                        "Well — issues were addressed without significant delays",
                        "Adequately — some gaps in communication but manageable",
                        "Poorly — escalations were reactive rather than proactive",
                        "Very poorly — communication was a consistent challenge"
                    ];
                    foreach ($q5Options as $opt) {
                        echo '<label class="option"><input type="radio" name="q5" value="'.htmlspecialchars($opt).'" required> '.htmlspecialchars($opt).'</label>';
                    }
                    ?>
                </div>
            </div>

            <div class="question">
                <h3>Q6. How would you rate the technical competence of the Raintels team across mobile development, backend, and dashboard components?</h3>
                <?php ratingScale("q6"); ?>
                <div class="hint"><span>Very poor</span><span>Excellent</span></div>
            </div>

            <div class="section-title">Solution Quality & Design</div>

            <div class="question">
                <h3>Q7. How satisfied are you with the user experience and interface design for end-user roles — doctors, health officials, and citizens?</h3>
                <?php ratingScale("q7"); ?>
                <div class="hint"><span>Very dissatisfied</span><span>Very satisfied</span></div>
            </div>

            <div class="question">
                <h3>Q8. Which of the following aspects of the solution did you find most impressive? Select all that apply.</h3>
                <div class="option-list">
                    <?php
                    $q8Options = [
                        "UI/UX design and ease of use",
                        "Data capture and workflow accuracy",
                        "Web dashboard and reporting capabilities",
                        "Training & assessment module design",
                        "Offline/low-connectivity functionality",
                        "Data security and privacy compliance"
                    ];
                    foreach ($q8Options as $opt) {
                        echo '<label class="option"><input type="checkbox" name="q8[]" value="'.htmlspecialchars($opt).'"> '.htmlspecialchars($opt).'</label>';
                    }
                    ?>
                </div>
            </div>

            <div class="question">
                <h3>Q9. How confident are you in the scalability and long-term maintainability of the architecture delivered?</h3>
                <div class="option-list">
                    <?php
                    $q9Options = [
                        "Very confident — architecture is future-ready",
                        "Confident — minor concerns but nothing significant",
                        "Somewhat confident — a few areas need revisiting",
                        "Not very confident — notable architectural concerns",
                        "Not confident at all"
                    ];
                    foreach ($q9Options as $opt) {
                        echo '<label class="option"><input type="radio" name="q9" value="'.htmlspecialchars($opt).'" required> '.htmlspecialchars($opt).'</label>';
                    }
                    ?>
                </div>
            </div>

            <div class="section-title">Collaboration & Support</div>

            <div class="question">
                <h3>Q10. How would you rate the responsiveness and support provided by the Raintels team during the project lifecycle?</h3>
                <?php ratingScale("q10"); ?>
                <div class="hint"><span>Very poor</span><span>Excellent</span></div>
            </div>

            <div class="question">
                <h3>Q11. How satisfied are you with the documentation, handover materials, and knowledge transfer provided?</h3>
                <?php ratingScale("q11"); ?>
                <div class="hint"><span>Very dissatisfied</span><span>Very satisfied</span></div>
            </div>

            <div class="section-title">Value & Recommendation</div>

            <div class="question">
                <h3>Q12. How likely are you to recommend Raintels as a technology delivery partner to peers or other organisations in the public health domain?</h3>
                <?php ratingScale("q12", 10); ?>
                <div class="hint"><span>Not at all likely</span><span>Extremely likely</span></div>
            </div>

            <div class="section-title">Open Feedback</div>

            <div class="question">
                <h3>Q13. Is there anything specific you feel Raintels did exceptionally well, or any area where you would have expected a stronger outcome?</h3>
                <textarea name="q13" placeholder="Please share your feedback here..."></textarea>
            </div>

            <div class="submit-area">
                <button type="submit">Submit Survey Response</button>
            </div>

        </form>

    <?php endif; ?>

    <div class="footer">
        © <?= date('Y') ?> Raintels · mHealth Application · Customer Satisfaction Survey · Confidential
    </div>

</div>

<script>
document.querySelector('form')?.addEventListener('submit', function(e) {
    document.querySelectorAll('.validation-error').forEach(el => {
        el.classList.remove('validation-error');
    });

    document.querySelectorAll('.field-error').forEach(el => {
        el.remove();
    });

    const requiredRadioGroups = [
        'q1','q2','q3','q4','q5','q6','q7','q9','q10','q11','q12'
    ];

    for (let name of requiredRadioGroups) {
        const selected = document.querySelector(`input[name="${name}"]:checked`);

        if (!selected) {
            e.preventDefault();

            const firstInput = document.querySelector(`input[name="${name}"]`);
            const questionBox = firstInput.closest('.question');

            questionBox.classList.add('validation-error');

            const error = document.createElement('div');
            error.className = 'field-error';
            error.innerText = 'Please answer this question.';
            questionBox.appendChild(error);

            questionBox.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
            });

            return false;
        }
    }

   
});
</script>
</body>
</html>