<?php

namespace App\Http\Controllers;

use App\Models\Survey;
use App\Models\SurveyQuestion;
use App\Models\SurveyResponse;
use App\Models\SurveyAnswer;
use App\Models\SurveyInvitation;
use App\Models\Guest;
use App\Models\Staff;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;
use App\Mail\SurveyInvitationMail;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class SurveyController extends Controller
{
    /**
     * Append uploaded files to survey media JSON; optionally remove items by index.
     *
     * @param  array<int, array{path: string, type: string}>  $existing
     * @return array<int, array{path: string, type: string}>
     */
    private function mergeSurveyMedia(Request $request, Survey $survey, array $existing): array
    {
        $media = $existing;

        if ($request->has('remove_media')) {
            foreach ((array) $request->input('remove_media', []) as $idx) {
                $idx = (int) $idx;
                if (isset($media[$idx]['path'])) {
                    Storage::disk('public')->delete($media[$idx]['path']);
                    unset($media[$idx]);
                }
            }
            $media = array_values($media);
        }

        if ($request->hasFile('media')) {
            foreach ($request->file('media') as $file) {
                if (! $file || ! $file->isValid()) {
                    continue;
                }
                $path = $file->store('surveys/'.$survey->id, 'public');
                $mime = (string) $file->getMimeType();
                $media[] = [
                    'path' => $path,
                    'type' => str_starts_with($mime, 'video/') ? 'video' : 'image',
                ];
            }
        }

        return $media;
    }

    /**
     * Display a listing of surveys.
     */
    public function index()
    {
        // Load surveys with questions count and responses count
        $surveys = Survey::withCount(['questions', 'responses'])
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        
        // For each survey, calculate response rate
        foreach ($surveys as $survey) {
            $survey->invitations_count = SurveyInvitation::where('survey_id', $survey->id)->count();
            $survey->response_count = $survey->responses()->count();
            $survey->response_rate = $survey->invitations_count > 0 
                ? round(($survey->response_count / $survey->invitations_count) * 100, 1) 
                : 0;
        }
        
        // Calculate stats for dashboard
        $totalSurveys = Survey::count();
        $activeSurveys = Survey::where('status', 'active')->count();
        $totalResponses = SurveyResponse::count();
        
        // Calculate average response rate
        $totalInvitations = SurveyInvitation::count();
        $responseRate = $totalInvitations > 0 ? round(($totalResponses / $totalInvitations) * 100, 1) : 0;
        
        $stats = [
            'total_surveys' => $totalSurveys,
            'active_surveys' => $activeSurveys,
            'total_responses' => $totalResponses,
            'response_rate' => $responseRate
        ];

        // Get recent responses - REMOVED staff relation
        try {
            $recentResponses = SurveyResponse::with(['survey', 'guest'])
                ->orderBy('submitted_at', 'desc')
                ->limit(5)
                ->get();
        } catch (\Exception $e) {
            $recentResponses = collect();
        }

        return view('surveys.index', compact('surveys', 'recentResponses', 'stats'));
    }

    /**
     * Show the form for creating a new survey.
     */
    public function create()
    {
        return view('surveys.create');
    }

    /**
     * Store a newly created survey in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'status' => 'required|in:draft,active,completed',
            'questions' => 'required|array|min:1',
            'questions.*.text' => 'required|string|max:500',
            'questions.*.type' => 'required|in:text,rating,multiple_choice,yes_no',
            'questions.*.options' => 'nullable|string',
            'questions.*.required' => 'nullable|boolean',
            'media' => 'nullable|array',
            'media.*' => 'file|max:10240',
        ]);

        // Create the survey
        $survey = Survey::create([
            'hotel_id' => auth()->user()->hotel_id,
            'title' => $validated['title'],
            'description' => $validated['description'],
            'status' => $validated['status'],
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Create questions
        foreach ($validated['questions'] as $index => $questionData) {
            $question = new SurveyQuestion([
                'hotel_id' => auth()->user()->hotel_id,
                'question' => $questionData['text'],
                'type' => $questionData['type'],
                'order' => $index,
                'is_required' => isset($questionData['required']) ? 1 : 0,
            ]);

            // Handle options for multiple choice questions
            if ($questionData['type'] === 'multiple_choice' && !empty($questionData['options'])) {
                $options = explode("\n", $questionData['options']);
                $options = array_map('trim', $options);
                $options = array_filter($options);
                $question->options = json_encode(array_values($options));
            }

            $survey->questions()->save($question);
        }

        $media = $this->mergeSurveyMedia($request, $survey, []);
        if ($media !== []) {
            $survey->update(['media' => $media]);
        }

        return redirect()->route('surveys.index')
            ->with('success', 'Survey created successfully!');
    }

    /**
     * Display the specified survey - FIXED to remove staff relation
     */
    /**
 * Display the specified survey - FIXED to remove staff relation
 */
/**
 * Display the specified survey
 */
public function show(Survey $survey)
{
    // Load questions and invitations
    $survey->load(['questions', 'invitations']);
    
    // Decode options for each question
    foreach ($survey->questions as $question) {
        if ($question->options) {
            $question->options = json_decode($question->options, true);
        }
    }
    
    // Get responses with answers
    $responses = SurveyResponse::where('survey_id', $survey->id)
        ->with('guest')
        ->orderBy('submitted_at', 'desc')
        ->get();
        
    foreach ($responses as $response) {
        $response->answers = SurveyAnswer::where('response_id', $response->id)
            ->with('question')
            ->get();
    }
    
    return view('surveys.show', compact('survey', 'responses'));
}    /**
     * Show the form for editing the specified survey.
     */
    public function edit(Survey $survey)
    {
        $survey->load('questions');
        
        // Decode options for multiple choice questions
        foreach ($survey->questions as $question) {
            if ($question->options) {
                $question->options = json_decode($question->options, true);
            }
        }
        
        return view('surveys.edit', compact('survey'));
    }

    /**
     * Update the specified survey in storage.
     */
  /**
 * Update the specified survey in storage.
 */
public function update(Request $request, Survey $survey)
{
    // Log the incoming request data for debugging
    Log::info('Survey update request received', [
        'survey_id' => $survey->id,
        'request_data' => $request->except('_token', '_method')
    ]);

    $validator = Validator::make($request->all(), [
        'title' => 'required|string|max:255',
        'description' => 'nullable|string',
        'status' => 'sometimes|in:draft,active,completed',
        'questions' => 'required|array|min:1',
        'questions.*.question' => 'required|string|max:500',
        'questions.*.type' => 'required|in:text,rating,multiple_choice,yes_no',
        'questions.*.options' => 'nullable|string',
        'questions.*.is_required' => 'nullable|boolean',
        'media' => 'nullable|array',
        'media.*' => 'file|max:10240',
        'remove_media' => 'nullable|array',
        'remove_media.*' => 'integer',
    ]);

    if ($validator->fails()) {
        Log::warning('Survey update validation failed', [
            'errors' => $validator->errors()->toArray()
        ]);
        return redirect()->back()
            ->withErrors($validator)
            ->withInput();
    }

    try {
        // Update survey details
        $survey->update([
            'title' => $request->title,
            'description' => $request->description,
            'status' => $request->status ?? $survey->status,
            'expires_at' => $request->expires_at ? \Carbon\Carbon::parse($request->expires_at) : null,
            'allow_anonymous' => $request->has('allow_anonymous'),
            'updated_at' => now()
        ]);

        // Delete existing questions
        $survey->questions()->delete();

        // Add updated questions
        $questionOrder = 0;
        foreach ($request->questions as $index => $questionData) {
            // Skip if question text is empty
            if (empty(trim($questionData['question']))) {
                continue;
            }

            $question = new SurveyQuestion([
                'hotel_id' => $survey->hotel_id,
                'question' => trim($questionData['question']),
                'type' => $questionData['type'],
                'order' => $questionOrder,
                'is_required' => isset($questionData['is_required']) && $questionData['is_required'] == '1' ? 1 : 0,
            ]);

            // Handle options for multiple choice questions
            if ($questionData['type'] === 'multiple_choice' && !empty($questionData['options'])) {
                // Split options by new line and clean up
                $options = explode("\n", $questionData['options']);
                $options = array_map('trim', $options);
                $options = array_filter($options, function($opt) {
                    return !empty($opt);
                });
                
                if (count($options) > 0) {
                    $question->options = json_encode(array_values($options));
                } else {
                    // If no valid options, default to some placeholder options
                    $question->options = json_encode(['Option 1', 'Option 2']);
                }
            }

            $survey->questions()->save($question);
            $questionOrder++;
        }

        $existingMedia = is_array($survey->media) ? $survey->media : [];
        $media = $this->mergeSurveyMedia($request, $survey, $existingMedia);
        $survey->update(['media' => $media]);

        Log::info('Survey updated successfully', [
            'survey_id' => $survey->id,
            'questions_count' => $questionOrder
        ]);

        return redirect()->route('surveys.show', $survey)
            ->with('success', 'Survey updated successfully.');

    } catch (\Exception $e) {
        Log::error('Error updating survey: ' . $e->getMessage(), [
            'survey_id' => $survey->id,
            'trace' => $e->getTraceAsString()
        ]);

        return redirect()->back()
            ->with('error', 'An error occurred while updating the survey. Please try again.')
            ->withInput();
    }
}
    /**
     * Remove the specified survey from storage.
     */
    public function destroy(Survey $survey)
    {
        if (is_array($survey->media)) {
            foreach ($survey->media as $item) {
                $path = is_array($item) ? ($item['path'] ?? null) : $item;
                if ($path) {
                    Storage::disk('public')->delete($path);
                }
            }
        }

        $survey->delete();

        return redirect()->route('surveys.index')
            ->with('success', 'Survey deleted successfully.');
    }

    /**
     * Activate a survey.
     */
    public function activate(Survey $survey)
    {
        $survey->update(['status' => 'active']);

        return redirect()->back()->with('success', 'Survey activated successfully.');
    }

    /**
     * Deactivate a survey.
     */
    public function deactivate(Survey $survey)
    {
        $survey->update(['status' => 'completed']);

        return redirect()->back()->with('success', 'Survey deactivated successfully.');
    }

    /**
     * Archive a survey.
     */
    public function archive(Survey $survey)
    {
        $survey->update(['status' => 'archived']);

        return redirect()->back()->with('success', 'Survey archived successfully.');
    }

    /**
     * Display a public survey for taking (direct access by ID)
     */
    public function public($id)
    {
        try {
            $survey = Survey::with(['questions'])
                ->where('id', $id)
                ->whereIn('status', ['active', 'completed'])
                ->firstOrFail();
            
            // Decode options for multiple choice questions
            foreach ($survey->questions as $question) {
                if ($question->options) {
                    $question->options = json_decode($question->options, true);
                }
            }
            
            return view('surveys.public', compact('survey'));
            
        } catch (\Exception $e) {
            Log::error('Error loading public survey: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Survey not found or unavailable',
                'timestamp' => now()->format('Y-m-d H:i:s')
            ], 404);
        }
    }

    /**
     * Submit survey responses (public)
     */
    public function submit(Request $request, $id)
    {
        try {
            $survey = Survey::findOrFail($id);
            
            // Validate that answers is an array
            $validator = Validator::make($request->all(), [
                'answers' => 'required|array',
            ], [
                'answers.required' => 'Please answer all questions.',
            ]);
            
            if ($validator->fails()) {
                return redirect()->back()
                    ->withErrors($validator)
                    ->withInput();
            }
            
            // Create response record - with nullable fields set to null
            $response = SurveyResponse::create([
                'hotel_id' => $survey->hotel_id, // IMPORTANT: Set hotel_id from survey
                'survey_id' => $survey->id,
                'guest_id' => null,
                'submitted_at' => now(),
                'created_at' => now(),
                'updated_at' => now()
            ]);
            
            // Save answers
            $answersSaved = 0;
            foreach ($request->answers as $questionId => $answer) {
                // Make sure the question exists for this survey
                $question = SurveyQuestion::where('id', $questionId)
                    ->where('survey_id', $survey->id)
                    ->first();
                    
                if ($question) {
                    SurveyAnswer::create([
                        'hotel_id' => $survey->hotel_id, // IMPORTANT: Set hotel_id from survey
                        'response_id' => $response->id,
                        'question_id' => $questionId,
                        'answer' => is_array($answer) ? json_encode($answer) : $answer,
                        'created_at' => now(),
                        'updated_at' => now()
                    ]);
                    $answersSaved++;
                }
            }
            
            Log::info('Survey response saved', [
                'survey_id' => $survey->id,
                'response_id' => $response->id,
                'answers_count' => $answersSaved,
                'ip' => $request->ip()
            ]);
            
            return redirect()->route('survey.thank-you', $survey->id)
                ->with('success', 'Thank you for completing the survey!');
                
        } catch (\Exception $e) {
            Log::error('Error submitting survey: ' . $e->getMessage(), [
                'survey_id' => $id ?? null,
                'trace' => $e->getTraceAsString()
            ]);
            
            return redirect()->back()
                ->with('error', 'There was an error submitting your response. Please try again. ' . $e->getMessage())
                ->withInput();
        }
    }

    /**
     * Display thank you page
     */
    public function thankYou($id)
    {
        $survey = Survey::findOrFail($id);
        return view('surveys.thank-you', compact('survey'));
    }

    /**
     * Get chart data for dashboard
     */
    public function getChartData()
    {
        try {
            // Get weekly response data using submitted_at
            $weeklyResponses = SurveyResponse::selectRaw('DAYOFWEEK(submitted_at) as day, COUNT(*) as count')
                ->where('submitted_at', '>=', now()->subDays(30))
                ->groupBy('day')
                ->orderBy('day')
                ->get()
                ->pluck('count', 'day')
                ->toArray();
            
            // Default values for each day of week (1=Sunday, 7=Saturday)
            $days = [0, 0, 0, 0, 0, 0, 0];
            $dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
            
            foreach ($weeklyResponses as $day => $count) {
                $index = $day - 1;
                if ($index >= 0 && $index < 7) {
                    $days[$index] = (int)$count;
                }
            }
            
            // Get response data for pie chart
            $totalResponses = SurveyResponse::count();
            $totalInvitations = SurveyInvitation::count();
            $pending = max(0, $totalInvitations - $totalResponses);
            
            // Get response counts by survey for bar chart
            $surveys = Survey::withCount('responses')
                ->orderBy('created_at', 'desc')
                ->limit(5)
                ->get();
            
            $surveyNames = $surveys->pluck('title')->toArray();
            $responseCounts = $surveys->pluck('responses_count')->toArray();
            
            return response()->json([
                'weeklyResponses' => $days,
                'weeklyLabels' => $dayNames,
                'responseData' => [
                    'labels' => ['Completed', 'Pending'],
                    'datasets' => [[
                        'data' => [$totalResponses, $pending],
                        'backgroundColor' => ['#1a936f', '#c6dabf'],
                        'borderWidth' => 0
                    ]]
                ],
                'surveyData' => [
                    'labels' => $surveyNames,
                    'datasets' => [[
                        'label' => 'Responses',
                        'data' => $responseCounts,
                        'backgroundColor' => '#1a936f'
                    ]]
                ]
            ]);
            
        } catch (\Exception $e) {
            Log::error('Error in getChartData: ' . $e->getMessage());
            
            // Return fallback data
            return response()->json([
                'weeklyResponses' => [0, 0, 0, 0, 0, 0, 0],
                'weeklyLabels' => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
                'responseData' => [
                    'labels' => ['Completed', 'Pending'],
                    'datasets' => [[
                        'data' => [0, 0],
                        'backgroundColor' => ['#1a936f', '#c6dabf'],
                        'borderWidth' => 0
                    ]]
                ],
                'surveyData' => [
                    'labels' => ['No Data'],
                    'datasets' => [[
                        'label' => 'Responses',
                        'data' => [0],
                        'backgroundColor' => '#1a936f'
                    ]]
                ]
            ]);
        }
    }

    /**
     * Display survey responses - FIXED to remove staff relation
     */
   /**
 * Display survey responses - FIXED to include all required variables
 */
public function responses(Survey $survey)
{
    $survey->load(['questions']);
    
    // Get all responses with answers
    $responses = SurveyResponse::where('survey_id', $survey->id)
        ->with(['guest', 'staff'])
        ->orderBy('submitted_at', 'desc')
        ->get();
        
    foreach ($responses as $response) {
        $response->answers = SurveyAnswer::where('response_id', $response->id)
            ->with('question')
            ->get();
    }
    
    // Calculate response statistics
    $totalResponses = $responses->count();
    
    // Calculate respondent type counts
    $guestResponses = $responses->whereNotNull('guest_id')->count();
    $staffResponses = $responses->whereNotNull('staff_id')->count();
    
    // Calculate response rate based on invitations
    $responseRate = 0;
    $invitationsCount = SurveyInvitation::where('survey_id', $survey->id)->count();
    if ($invitationsCount > 0) {
        $responseRate = round(($totalResponses / $invitationsCount) * 100, 1);
    }
    
    // Group responses by date for chart - FIXED: using submitted_at instead of created_at
    $responsesByDate = SurveyResponse::where('survey_id', $survey->id)
        ->selectRaw('DATE(submitted_at) as date, COUNT(*) as count')
        ->groupBy('date')
        ->orderBy('date')
        ->get();
    
    return view('surveys.responses', compact(
        'survey', 
        'responses',
        'totalResponses', 
        'responseRate',
        'guestResponses',
        'staffResponses',
        'responsesByDate'  // Make sure this is included
    ));
}
    /**
     * Get recipient counts for sending surveys
     */
    public function getRecipientCounts(Request $request)
    {
        $recipientType = $request->get('recipient_type');
        
        $guestsCount = 0;
        $staffCount = 0;
        $guestsSummary = '';
        $staffSummary = '';
        
        // Calculate guest counts based on filters
        if ($recipientType === 'guests' || $recipientType === 'both') {
            $guestQuery = Guest::query();
            
            // Apply guest filters
            switch ($request->get('guest_status')) {
                case 'checked_in':
                    $guestQuery->where('status', 'checked_in');
                    $guestsSummary = 'Currently checked in guests';
                    break;
                case 'recent':
                case 'checked_out_last_week':
                    $guestQuery->where('check_out_date', '>=', now()->subWeek());
                    $guestsSummary = 'Guests checked out last week';
                    break;
                case 'last_month':
                    $guestQuery->where('check_out_date', '>=', now()->subMonth());
                    $guestsSummary = 'Guests checked out last month';
                    break;
                case 'frequent':
                    $guestQuery->where('stay_count', '>=', 3);
                    $guestsSummary = 'Frequent guests (3+ stays)';
                    break;
                case 'first_time':
                    $guestQuery->where('stay_count', 1);
                    $guestsSummary = 'First time guests';
                    break;
                default:
                    $guestsSummary = 'All guests';
            }
            
            $guestsCount = $guestQuery->count();
        }
        
        // Calculate staff counts based on filters
        if ($recipientType === 'staff' || $recipientType === 'both') {
            $staffQuery = Staff::query();
            
            // Apply staff filters
            if ($request->get('department') && $request->get('department') !== 'all') {
                $staffQuery->where('department', $request->get('department'));
                $staffSummary = ucfirst(str_replace('_', ' ', $request->get('department'))) . ' department';
            } else {
                $staffSummary = 'All departments';
            }
            
            $staffCount = $staffQuery->count();
        }
        
        return response()->json([
            'guests_count' => $guestsCount,
            'staff_count' => $staffCount,
            'guests_summary' => $guestsSummary,
            'staff_summary' => $staffSummary
        ]);
    }

    /**
     * Send survey invitations
     */
    public function sendInvitations(Request $request, Survey $survey)
    {
        Log::info('Sending survey invitations', [
            'survey_id' => $survey->id,
            'recipient_type' => $request->input('recipient_type'),
            'user_id' => auth()->id()
        ]);

        try {
            $recipientType = $request->input('recipient_type');
            $sendEmail = $request->input('send_email', true);
            $includeMessage = $request->input('include_message', false);
            $personalMessage = $request->input('personal_message', '');
            $filters = $request->input('filters', []);
            
            $invitationsSent = 0;
            
            switch ($recipientType) {
                case 'guests':
                    $guests = $this->getFilteredGuests($filters);
                    foreach ($guests as $guest) {
                        $this->createInvitation($survey, $guest, $sendEmail, $includeMessage, $personalMessage);
                        $invitationsSent++;
                    }
                    break;
                    
                case 'staff':
                    $staff = $this->getFilteredStaff($filters);
                    foreach ($staff as $staffMember) {
                        $this->createInvitation($survey, $staffMember, $sendEmail, $includeMessage, $personalMessage);
                        $invitationsSent++;
                    }
                    break;
                    
                case 'both':
                    $guests = $this->getFilteredGuests($filters);
                    $staff = $this->getFilteredStaff($filters);
                    
                    foreach ($guests as $guest) {
                        $this->createInvitation($survey, $guest, $sendEmail, $includeMessage, $personalMessage);
                        $invitationsSent++;
                    }
                    
                    foreach ($staff as $staffMember) {
                        $this->createInvitation($survey, $staffMember, $sendEmail, $includeMessage, $personalMessage);
                        $invitationsSent++;
                    }
                    break;
                    
                default:
                    return response()->json([
                        'success' => false,
                        'error' => 'Invalid recipient type'
                    ], 400);
            }
            
            Log::info('Survey invitations sent successfully', [
                'survey_id' => $survey->id,
                'invitations_sent' => $invitationsSent
            ]);
            
            return response()->json([
                'success' => true,
                'message' => "Survey sent to {$invitationsSent} recipients successfully!",
                'invitations_sent' => $invitationsSent
            ]);
            
        } catch (\Exception $e) {
            Log::error('Failed to send survey invitations: ' . $e->getMessage(), [
                'survey_id' => $survey->id,
                'error_trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'error' => 'Failed to send invitations. Please try again later.'
            ], 500);
        }
    }

    /**
     * Send survey emails (bulk email sending)
     */
    public function sendSurveyEmails(Request $request)
    {
        try {
            $surveyId = $request->input('survey_id');
            $recipients = $request->input('recipients', []);
            $customMessage = $request->input('custom_message', '');
            
            $survey = Survey::findOrFail($surveyId);
            
            $sentCount = 0;
            
            foreach ($recipients as $recipient) {
                if (isset($recipient['email']) && !empty($recipient['email'])) {
                    // Create invitation
                    $invitationData = [
                        'hotel_id' => $survey->hotel_id,
                        'survey_id' => $survey->id,
                        'token' => Str::uuid(),
                        'expires_at' => now()->addDays(7),
                        'sent_at' => now(),
                        'status' => 'sent',
                        'recipient_email' => $recipient['email'],
                        'recipient_name' => $recipient['name'] ?? $recipient['email'],
                    ];
                    
                    if (isset($recipient['type']) && $recipient['type'] === 'guest') {
                        $invitationData['guest_id'] = $recipient['id'] ?? null;
                        $invitationData['recipient_type'] = 'guest';
                    } elseif (isset($recipient['type']) && $recipient['type'] === 'staff') {
                        $invitationData['staff_id'] = $recipient['id'] ?? null;
                        $invitationData['recipient_type'] = 'staff';
                    } else {
                        $invitationData['recipient_type'] = 'custom';
                    }
                    
                    SurveyInvitation::create($invitationData);
                    
                    $sentCount++;
                }
            }
            
            return response()->json([
                'success' => true,
                'message' => "Survey emails sent to {$sentCount} recipients",
                'count' => $sentCount
            ]);
            
        } catch (\Exception $e) {
            Log::error('Error sending survey emails: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error sending emails: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Bulk activate surveys
     */
    public function bulkActivate(Request $request)
    {
        $ids = $request->input('ids', []);
        Survey::whereIn('id', $ids)->update(['status' => 'active']);
        return response()->json(['success' => true]);
    }

    /**
     * Bulk deactivate surveys
     */
    public function bulkDeactivate(Request $request)
    {
        $ids = $request->input('ids', []);
        Survey::whereIn('id', $ids)->update(['status' => 'completed']);
        return response()->json(['success' => true]);
    }

    /**
     * Bulk delete surveys
     */
    public function bulkDelete(Request $request)
    {
        $ids = $request->input('ids', []);
        Survey::whereIn('id', $ids)->delete();
        return response()->json(['success' => true]);
    }

    /**
     * Get filtered guests for invitations
     */
    private function getFilteredGuests($filters)
    {
        $query = Guest::query();
        
        if (isset($filters['guest_status']) && $filters['guest_status'] !== 'all') {
            switch ($filters['guest_status']) {
                case 'checked_in':
                    $query->where('status', 'checked_in');
                    break;
                case 'recent':
                case 'checked_out_last_week':
                    $query->where('check_out_date', '>=', now()->subWeek());
                    break;
                case 'last_month':
                    $query->where('check_out_date', '>=', now()->subMonth());
                    break;
                case 'frequent':
                    $query->where('stay_count', '>=', 3);
                    break;
                case 'first_time':
                    $query->where('stay_count', 1);
                    break;
            }
        }
        
        return $query->get();
    }

    /**
     * Get filtered staff for invitations
     */
    private function getFilteredStaff($filters)
    {
        $query = Staff::query();
        
        if (isset($filters['department']) && $filters['department'] !== 'all') {
            $query->where('department', $filters['department']);
        }
        
        return $query->get();
    }

    /**
     * Create a survey invitation
     */
    private function createInvitation(Survey $survey, $recipient, $sendEmail = true, $includeMessage = false, $personalMessage = '')
    {
        // Determine recipient type and create invitation
        $invitationData = [
            'hotel_id' => $survey->hotel_id,
            'survey_id' => $survey->id,
            'token' => Str::uuid(),
            'expires_at' => now()->addDays(7),
            'sent_at' => now(),
            'status' => 'sent'
        ];

        if ($recipient instanceof Guest) {
            $invitationData['guest_id'] = $recipient->id;
            $invitationData['recipient_type'] = 'guest';
            $invitationData['recipient_email'] = $recipient->email;
            $invitationData['recipient_name'] = ($recipient->first_name ?? '') . ' ' . ($recipient->last_name ?? '');
        } elseif ($recipient instanceof Staff) {
            $invitationData['staff_id'] = $recipient->id;
            $invitationData['recipient_type'] = 'staff';
            $invitationData['recipient_email'] = $recipient->email;
            $invitationData['recipient_name'] = ($recipient->first_name ?? '') . ' ' . ($recipient->last_name ?? '');
        } else {
            throw new \Exception('Invalid recipient type');
        }

        $invitation = SurveyInvitation::create($invitationData);

        return $invitation;
    }
}