<?php
require_once dirname(__DIR__) . '/models/Survey.php';
require_once dirname(__DIR__) . '/../config/db.php';

class SurveyController {
    private $conn;
    private $survey;

    public function __construct() {
        $this->conn = connectDB();
        $this->survey = new Survey($this->conn);
    }

    // Public form for customer satisfaction survey
    public function showSurveyForm() {
        $questions = $this->survey->getQuestions();
        require_once dirname(__DIR__) . '/../views/survey/form.php';
    }

    // Process public survey submission
    public function submitSurvey() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $questions = $this->survey->getQuestions();
            $success = true;

            $nama = $_POST['nama'] ?? '';
            $unit = $_POST['unit'] ?? '';
            $email = $_POST['email'] ?? '';

            // Basic validation for new fields
            if (empty($nama) || empty($unit) || empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                header("Location: ?page=survey_form&error=empty_or_invalid_user_data");
                exit();
            }

            foreach ($questions as $question) {
                $question_id = $question['id'];
                $response_value = $_POST['question_' . $question_id] ?? '';

                if ($question['question_type'] === 'rating_5' && !in_array($response_value, ['1','2','3','4','5'])) {
                    $success = false; // Invalid rating
                    break;
                }
                // Text questions can be optional, or add validation if required
                // if ($question['question_type'] === 'text' && empty($response_value)) { /* ... */ }

                $this->survey->survey_question_id = $question_id;
                $this->survey->response_value = $response_value;
                // Pass new user info to the model's save method
                if (!$this->survey->saveResponseWithUserInfo($nama, $unit, $email)) { // Assuming a new method or updated one
                    $success = false;
                    break;
                }
            }

            if ($success) {
                header("Location: ?page=survey_form&message=survey_success");
                exit();
            } else {
                header("Location: ?page=survey_form&error=submit_failed");
                exit();
            }
        }
    }

    // Admin view: Display aggregated survey results and individual responses
    public function viewSurveyResults() {
        $questions = $this->survey->getQuestions();
        $all_raw_responses = $this->survey->getAllResponses(); // Get all individual responses
        
        $average_ratings = [];
        foreach ($questions as $question) {
            if ($question['question_type'] === 'rating_5') {
                $average_ratings[$question['id']] = $this->survey->getAverageRating($question['id']);
            }
        }

        // Calculate overall average rating (only for rating_5 questions)
        $overall_avg_rating = $this->survey->getAverageRating();

        // Group responses by user (nama, unit, email)
        $grouped_responses = [];
        foreach ($all_raw_responses as $response) {
            $respondent_key = $response['nama'] . ' - ' . $response['email']; // Using email for better uniqueness
            if (!isset($grouped_responses[$respondent_key])) {
                $grouped_responses[$respondent_key] = [
                    'nama' => $response['nama'],
                    'unit' => $response['unit'],
                    'email' => $response['email'],
                    'created_at' => $response['created_at'], // Take the first response's timestamp as the user's survey submission time
                    'responses' => []
                ];
            }
            $grouped_responses[$respondent_key]['responses'][] = $response;
        }

        // Sort grouped responses by created_at (descending)
        usort($grouped_responses, function($a, $b) {
            return strtotime($b['created_at']) - strtotime($a['created_at']);
        });


        require_once dirname(__DIR__) . '/../views/survey/results.php';
    }
}