<?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 with filtering and pagination
    public function viewSurveyResults() {
        // Filtering parameters
        $month = $_GET['month'] ?? null;
        $year = $_GET['year'] ?? null;

        // Pagination parameters
        $page = isset($_GET['p']) ? (int)$_GET['p'] : 1; // Using 'p' for page to avoid conflict with 'page' for routing
        $records_per_page = 10; // As requested

        $questions = $this->survey->getQuestions();
        
        // --- Aggregate Ratings (remain unchanged, but pass filters) ---
        $average_ratings = [];
        foreach ($questions as $question) {
            if ($question['question_type'] === 'rating_5') {
                $average_ratings[$question['id']] = $this->survey->getAverageRating($question['id'], $month, $year);
            }
        }
        $overall_avg_rating = $this->survey->getAverageRating(null, $month, $year);
        // --- End Aggregate Ratings ---


        // --- Individual Responses (Paginated and Grouped) ---
        // Get paginated unique respondent submissions
        $stmt_unique_submissions = $this->survey->getUniqueRespondentSubmissions($page, $records_per_page, $month, $year);
        $unique_submissions_paginated = $stmt_unique_submissions->fetchAll(PDO::FETCH_ASSOC);

        // Calculate total number of unique submissions for pagination
        $total_rows = $this->survey->countUniqueRespondentSubmissions($month, $year);
        $total_pages = ceil($total_rows / $records_per_page);

        // Adjust current page if out of bounds
        if ($page < 1) $page = 1;
        if ($page > $total_pages && $total_pages > 0) $page = $total_pages;

        $grouped_responses = [];
        foreach ($unique_submissions_paginated as $submission_summary) {
            // Use the email and created_at_min to fetch all individual responses for THIS submission
            $individual_responses_for_this_submission = $this->survey->getResponsesByRespondentSubmission(
                $submission_summary['email'],
                $submission_summary['created_at_min']
            );

            $grouped_responses[] = [
                'nama' => $submission_summary['nama'],
                'unit' => $submission_summary['unit'],
                'email' => $submission_summary['email'],
                'created_at' => $submission_summary['created_at_min'], // Using created_at_min as the submission timestamp
                'responses' => $individual_responses_for_this_submission
            ];
        }
        // No need for usort here, as getUniqueRespondentSubmissions already orders them.
        // --- End Individual Responses ---

        // Data to pass to view
        $view_data = [
            'questions' => $questions,
            'average_ratings' => $average_ratings,
            'overall_avg_rating' => $overall_avg_rating,
            'grouped_responses' => $grouped_responses, // This now contains full submission data for paginated unique submissions
            'month' => $month,
            'year' => $year,
            'page' => $page,
            'total_pages' => $total_pages,
            'total_rows' => $total_rows,
            'records_per_page' => $records_per_page
        ];

        extract($view_data); // Extract data to make it available in the view

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