<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\IndividualAdAnalyticsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use PDF;
use Excel;
use Illuminate\Support\Facades\Storage;
use App\Models\Ad;
use App\Models\User;
use App\Models\Notification as NotificationModel;
use App\Models\UserAppeal;

class IndividualAdAnalyticsController extends Controller
{
    protected $individualAdAnalyticsService;

    public function __construct(IndividualAdAnalyticsService $individualAdAnalyticsService)
    {
        $this->individualAdAnalyticsService = $individualAdAnalyticsService;
    }

    /**
     * Get performance metrics for a specific ad
     */
    public function getPerformanceMetrics(Request $request, $adId)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $data['data']['performance_metrics'],
                'message' => 'Performance metrics retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving performance metrics: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving performance metrics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get geographic analytics for a specific ad
     */
    public function getGeographicAnalytics(Request $request, $adId)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $data['data']['geographic_analytics'],
                'message' => 'Geographic analytics retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving geographic analytics: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving geographic analytics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get temporal analytics for a specific ad
     */
    public function getTemporalAnalytics(Request $request, $adId)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $data['data']['temporal_analytics'],
                'message' => 'Temporal analytics retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving temporal analytics: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving temporal analytics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user interaction analytics for a specific ad
     */
    public function getUserInteractionAnalytics(Request $request, $adId)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $data['data']['user_interaction_analytics'],
                'message' => 'User interaction analytics retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving user interaction analytics: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving user interaction analytics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get chat analytics for a specific ad
     */
    public function getChatAnalytics(Request $request, $adId)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $data['data']['chat_analytics'],
                'message' => 'Chat analytics retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving chat analytics: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving chat analytics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get engagement analytics for a specific ad
     */
    public function getEngagementAnalytics(Request $request, $adId)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $data['data']['engagement_analytics'],
                'message' => 'Engagement analytics retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving engagement analytics: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving engagement analytics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get revenue analytics for a specific ad
     */
    public function getRevenueAnalytics(Request $request, $adId)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $data['data']['revenue_analytics'],
                'message' => 'Revenue analytics retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving revenue analytics: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving revenue analytics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Download analytics report in PDF format
     */
    public function downloadPdf($adId, Request $request)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            $pdf = PDF::loadView('admin.analytics.reports.pdf', [
                'adId' => $adId,
                'data' => $data['data'],
                'startDate' => $startDate,
                'endDate' => $endDate
            ]);

            return $pdf->download("ad_{$adId}_analytics_report.pdf");
        } catch (\Exception $e) {
            Log::error('Error generating PDF report: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error generating PDF report',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Download analytics report in Excel format
     */
    public function downloadExcel($adId, Request $request)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            $excelData = $this->prepareExcelData($data['data']);

            return Excel::download(new \App\Exports\AdAnalyticsExport($excelData), "ad_{$adId}_analytics_report.xlsx");
        } catch (\Exception $e) {
            Log::error('Error generating Excel report: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error generating Excel report',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Download analytics report in CSV format
     */
    public function downloadCsv($adId, Request $request)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            $csvData = $this->prepareCsvData($data['data']);

            $headers = [
                'Content-type' => 'text/csv',
                'Content-Disposition' => 'attachment; filename="ad_' . $adId . '_analytics_report.csv"',
            ];

            $callback = function() use ($csvData) {
                $file = fopen('php://output', 'w');
                fputcsv($file, ['Metric', 'Value']);
                
                foreach ($csvData as $key => $value) {
                    fputcsv($file, [$key, $value]);
                }
                
                fclose($file);
            };

            return response()->stream($callback, 200, $headers);
        } catch (\Exception $e) {
            Log::error('Error generating CSV report: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error generating CSV report',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Download chat transcripts
     */
    public function downloadChatTranscripts($adId, Request $request)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            $chatData = $data['data']['chat_analytics']['chat_conversations'];
            
            $transcript = $this->generateChatTranscript($chatData);

            $headers = [
                'Content-type' => 'text/plain',
                'Content-Disposition' => 'attachment; filename="ad_' . $adId . '_chat_transcripts.txt"',
            ];

            return response()->make($transcript, 200, $headers);
        } catch (\Exception $e) {
            Log::error('Error generating chat transcripts: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error generating chat transcripts',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Download analytics report in JSON format
     */
    public function downloadJson($adId, Request $request)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            $headers = [
                'Content-type' => 'application/json',
                'Content-Disposition' => 'attachment; filename="ad_' . $adId . '_analytics_report.json"',
            ];

            return response()->json($data['data'], 200, $headers);
        } catch (\Exception $e) {
            Log::error('Error generating JSON report: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error generating JSON report',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get safety analytics for a specific ad
     */
    public function getSafetyAnalytics(Request $request, $adId)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $data['data']['safety_analytics'],
                'message' => 'Safety analytics retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving safety analytics: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving safety analytics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user profile analytics
     */
    public function getUserProfileAnalytics(Request $request, $adId)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $data['data']['user_profile_analytics'],
                'message' => 'User profile analytics retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving user profile analytics: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving user profile analytics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get reporter analytics
     */
    public function getReporterAnalytics(Request $request, $adId)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $data['data']['reporter_analytics'],
                'message' => 'Reporter analytics retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving reporter analytics: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving reporter analytics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get moderation actions
     */
    public function getModerationActions(Request $request, $adId)
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $data = $this->individualAdAnalyticsService->getAdAnalytics($adId, $startDate, $endDate);

            return response()->json([
                'success' => true,
                'data' => $data['data']['moderation_actions'],
                'message' => 'Moderation actions retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving moderation actions: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving moderation actions',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Suspend ad with reason
     */
    public function suspendAd(Request $request, $adId)
    {
        try {
            $request->validate([
                'reason' => 'required|string|max:500',
                'notify_user' => 'boolean',
            ]);

            $ad = Ad::find($adId);
            if (!$ad) {
                return response()->json([
                    'success' => false,
                    'message' => 'Ad not found'
                ], 404);
            }

            // Update ad status
            $ad->status = 'suspended';
            $ad->save();

            // Create safety action record
            \App\Models\SafetyAction::create([
                'user_id' => $ad->user_id,
                'ad_id' => $adId,
                'admin_user_id' => auth()->id(),
                'action_type' => 'suspend',
                'reason' => $request->reason,
                'status' => 'completed',
            ]);

            // Notify user if requested
            if ($request->notify_user) {
                $this->sendModerationNotification($ad->user_id, 'ad_suspended', $request->reason, $adId);
            }

            return response()->json([
                'success' => true,
                'message' => 'Ad suspended successfully',
                'ad_status' => $ad->status
            ]);
        } catch (\Exception $e) {
            Log::error('Error suspending ad: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error suspending ad',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Reject ad with reason
     */
    public function rejectAd(Request $request, $adId)
    {
        try {
            $request->validate([
                'reason' => 'required|string|max:500',
                'notify_user' => 'boolean',
            ]);

            $ad = Ad::find($adId);
            if (!$ad) {
                return response()->json([
                    'success' => false,
                    'message' => 'Ad not found'
                ], 404);
            }

            // Update ad status
            $ad->status = 'rejected';
            $ad->save();

            // Create safety action record
            \App\Models\SafetyAction::create([
                'user_id' => $ad->user_id,
                'ad_id' => $adId,
                'admin_user_id' => auth()->id(),
                'action_type' => 'reject',
                'reason' => $request->reason,
                'status' => 'completed',
            ]);

            // Notify user if requested
            if ($request->notify_user) {
                $this->sendModerationNotification($ad->user_id, 'ad_rejected', $request->reason, $adId);
            }

            return response()->json([
                'success' => true,
                'message' => 'Ad rejected successfully',
                'ad_status' => $ad->status
            ]);
        } catch (\Exception $e) {
            Log::error('Error rejecting ad: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error rejecting ad',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete ad with reason
     */
    public function deleteAd(Request $request, $adId)
    {
        try {
            $request->validate([
                'reason' => 'required|string|max:500',
                'notify_user' => 'boolean',
            ]);

            $ad = Ad::find($adId);
            if (!$ad) {
                return response()->json([
                    'success' => false,
                    'message' => 'Ad not found'
                ], 404);
            }

            // Create safety action record before deletion
            \App\Models\SafetyAction::create([
                'user_id' => $ad->user_id,
                'ad_id' => $adId,
                'admin_user_id' => auth()->id(),
                'action_type' => 'delete',
                'reason' => $request->reason,
                'status' => 'completed',
            ]);

            // Notify user if requested
            if ($request->notify_user) {
                $this->sendModerationNotification($ad->user_id, 'ad_deleted', $request->reason, $adId);
            }

            // Delete ad
            $ad->delete();

            return response()->json([
                'success' => true,
                'message' => 'Ad deleted successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error deleting ad: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error deleting ad',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Show the individual ad analytics dashboard.
     *
     * @param  int  $adId
     * @return \Illuminate\View\View
     */
    public function show($adId)
    {
        $ad = Ad::with(['user', 'category', 'subcategory', 'images'])
            ->find($adId);

        if (!$ad) {
            $ad = $this->getMockAd($adId);
        }

        return view('admin.analytics.individual_ad', compact('ad'));
    }

    /**
     * Show the enhanced individual ad analytics dashboard with safety and moderation features.
     *
     * @param  int  $adId
     * @return \Illuminate\View\View
     */
    public function showEnhanced($adId)
    {
        $ad = Ad::with(['user', 'category', 'subcategory', 'images'])
            ->find($adId);

        if (!$ad) {
            $ad = $this->getMockAd($adId);
        }

        return view('admin.analytics.individual_ad_enhanced', compact('ad', 'adId'));
    }

    /**
     * Generate a mock ad for demonstration purposes.
     *
     * @param int $adId
     * @return object
     */
    private function getMockAd($adId)
    {
        $ad = new \stdClass();
        $ad->id = $adId;
        $ad->title = 'Demo Ad ' . $adId;
        $ad->price = rand(100, 5000) + 0.99;
        $ad->currency = 'USD';
        $ad->status = 'active';
        $ad->city = 'New York';
        $ad->state = 'NY';
        $ad->country = 'USA';
        $ad->created_at = now();
        
        $ad->category = new \stdClass();
        $ad->category->name = 'Electronics';
        
        $ad->user = new \stdClass();
        $ad->user->id = 1;
        $ad->user->name = 'Demo User';
        $ad->user->email = 'demo@example.com';
        $ad->user_id = 1;
        
        // Mock images if needed (though view didn't seem to iterate them in blade, 
        // JS might use them. safer to add empty array or mock images)
        $ad->images = collect([
            (object)['url' => 'https://via.placeholder.com/800x600?text=Ad+Image+1'],
            (object)['url' => 'https://via.placeholder.com/800x600?text=Ad+Image+2'],
        ]);

        return $ad;
    }

    /**
     * Approve ad
     */
    public function approveAd(Request $request, $adId)
    {
        try {
            $ad = Ad::find($adId);
            if (!$ad) {
                return response()->json([
                    'success' => false,
                    'message' => 'Ad not found'
                ], 404);
            }

            // Update ad status
            $ad->status = 'active';
            $ad->save();

            // Create safety action record
            \App\Models\SafetyAction::create([
                'user_id' => $ad->user_id,
                'ad_id' => $adId,
                'admin_user_id' => auth()->id(),
                'action_type' => 'approve',
                'reason' => 'Admin approval',
                'status' => 'completed',
            ]);

            // Notify user
            $this->sendModerationNotification($ad->user_id, 'ad_approved', 'Your ad has been approved', $adId);

            return response()->json([
                'success' => true,
                'message' => 'Ad approved successfully',
                'ad_status' => $ad->status
            ]);
        } catch (\Exception $e) {
            Log::error('Error approving ad: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error approving ad',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Suspend user
     */
    public function suspendUser(Request $request, $userId)
    {
        try {
            $request->validate([
                'reason' => 'required|string|max:500',
                'duration_days' => 'integer|min:1|max:365',
            ]);

            $user = User::find($userId);
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'User not found'
                ], 404);
            }

            // Update user status
            $user->status = 'suspended';
            $user->suspended_until = now()->addDays($request->duration_days ?? 30);
            $user->save();

            // Create safety action record
            \App\Models\SafetyAction::create([
                'user_id' => $userId,
                'admin_user_id' => auth()->id(),
                'action_type' => 'user_suspend',
                'reason' => $request->reason,
                'status' => 'completed',
            ]);

            // Notify user
            $this->sendModerationNotification($userId, 'user_suspended', $request->reason);

            return response()->json([
                'success' => true,
                'message' => 'User suspended successfully',
                'user_status' => $user->status
            ]);
        } catch (\Exception $e) {
            Log::error('Error suspending user: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error suspending user',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Ban user
     */
    public function banUser(Request $request, $userId)
    {
        try {
            $request->validate([
                'reason' => 'required|string|max:500',
                'notify_user' => 'boolean',
                'create_appeal' => 'boolean',
            ]);

            $user = User::find($userId);
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'User not found'
                ], 404);
            }

            // Update user status
            $user->status = 'banned';
            $user->save();

            // Create safety action record
            \App\Models\SafetyAction::create([
                'user_id' => $userId,
                'admin_user_id' => auth()->id(),
                'action_type' => 'user_ban',
                'reason' => $request->reason,
                'status' => 'completed',
            ]);

            // Create appeal if requested
            if ($request->create_appeal) {
                $this->createUserAppeal($userId, 'ban_appeal', $request->reason, $request->notify_user);
            }

            // Notify user if requested
            if ($request->notify_user) {
                $this->sendModerationNotification($userId, 'user_banned', $request->reason);
            }

            return response()->json([
                'success' => true,
                'message' => 'User banned successfully',
                'user_status' => $user->status
            ]);
        } catch (\Exception $e) {
            Log::error('Error banning user: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error banning user',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Unban user
     */
    public function unbanUser(Request $request, $userId)
    {
        try {
            $request->validate([
                'reason' => 'required|string|max:500',
                'notify_user' => 'boolean',
            ]);

            $user = User::find($userId);
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'User not found'
                ], 404);
            }

            // Update user status
            $user->status = 'active';
            $user->banned_reason = null;
            $user->banned_at = null;
            $user->save();

            // Create safety action record
            \App\Models\SafetyAction::create([
                'user_id' => $userId,
                'admin_user_id' => auth()->id(),
                'action_type' => 'user_unban',
                'reason' => $request->reason,
                'status' => 'completed',
            ]);

            // Notify user if requested
            if ($request->notify_user) {
                $this->sendModerationNotification($userId, 'user_unbanned', $request->reason);
            }

            return response()->json([
                'success' => true,
                'message' => 'User unbanned successfully',
                'user_status' => $user->status
            ]);
        } catch (\Exception $e) {
            Log::error('Error unbanning user: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error unbanning user',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Create user appeal
     */
    public function createUserAppeal($userId, $appealType, $reason, $notifyUser = true)
    {
        try {
            $appeal = UserAppeal::create([
                'user_id' => $userId,
                'appeal_type' => $appealType,
                'appeal_reason' => $reason,
                'status' => 'pending',
                'is_urgent' => false,
                'appeal_data' => [
                    'original_reason' => $reason,
                    'appeal_type' => $appealType,
                    'created_by' => 'system'
                ]
            ]);

            if ($notifyUser) {
                $this->sendModerationNotification($userId, 'appeal_created', 'Your appeal has been submitted for review', null);
            }

            return $appeal;
        } catch (\Exception $e) {
            Log::error('Error creating user appeal: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Get user appeals
     */
    public function getUserAppeals(Request $request, $userId)
    {
        try {
            $appeals = UserAppeal::where('user_id', $userId)
                ->orderBy('created_at', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $appeals,
                'message' => 'User appeals retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving user appeals: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving user appeals',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Review user appeal
     */
    public function reviewUserAppeal(Request $request, $appealId)
    {
        try {
            $request->validate([
                'status' => 'required|in:approved,rejected,pending',
                'resolution_notes' => 'required|string|max:1000',
                'notify_user' => 'boolean',
            ]);

            $appeal = UserAppeal::find($appealId);
            if (!$appeal) {
                return response()->json([
                    'success' => false,
                    'message' => 'Appeal not found'
                ], 404);
            }

            // Update appeal
            $appeal->status = $request->status;
            $appeal->admin_id = auth()->id();
            $appeal->reviewed_at = now();
            $appeal->resolution_notes = $request->resolution_notes;
            $appeal->save();

            // If appeal is approved, take appropriate action
            if ($request->status === 'approved') {
                $this->handleApprovedAppeal($appeal);
            }

            // Notify user if requested
            if ($request->notify_user) {
                $this->sendModerationNotification(
                    $appeal->user_id, 
                    'appeal_reviewed', 
                    $request->resolution_notes, 
                    null
                );
            }

            return response()->json([
                'success' => true,
                'message' => 'Appeal reviewed successfully',
                'appeal_status' => $appeal->status
            ]);
        } catch (\Exception $e) {
            Log::error('Error reviewing user appeal: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error reviewing user appeal',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Handle approved appeal
     */
    private function handleApprovedAppeal($appeal)
    {
        try {
            $user = User::find($appeal->user_id);
            if (!$user) return;

            switch ($appeal->appeal_type) {
                case 'ban_appeal':
                    // Unban user
                    $user->status = 'active';
                    $user->banned_reason = null;
                    $user->banned_at = null;
                    $user->save();

                    // Create safety action record
                    \App\Models\SafetyAction::create([
                        'user_id' => $user->id,
                        'admin_user_id' => auth()->id(),
                        'action_type' => 'appeal_approved_unban',
                        'reason' => $appeal->resolution_notes,
                        'status' => 'completed',
                    ]);
                    break;

                case 'suspension_appeal':
                    // Unsuspend user
                    $user->status = 'active';
                    $user->is_suspended = false;
                    $user->suspended_until = null;
                    $user->save();

                    // Create safety action record
                    \App\Models\SafetyAction::create([
                        'user_id' => $user->id,
                        'admin_user_id' => auth()->id(),
                        'action_type' => 'appeal_approved_unsuspend',
                        'reason' => $appeal->resolution_notes,
                        'status' => 'completed',
                    ]);
                    break;
            }
        } catch (\Exception $e) {
            Log::error('Error handling approved appeal: ' . $e->getMessage());
        }
    }

    /**
     * Get user profile with all details
     */
    public function getUserProfile(Request $request, $userId)
    {
        try {
            $user = User::with([
                'safetyReports',
                'trustScores',
                'safetyActions',
                'appeals' => function($query) {
                    $query->orderBy('created_at', 'desc')->limit(10);
                }
            ])->find($userId);

            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'User not found'
                ], 404);
            }

            // Get user statistics
            $userStats = [
                'total_ads' => $user->ads()->count(),
                'total_views' => $user->ads()->sum('views'),
                'total_reports' => $user->safetyReports()->count(),
                'active_ads' => $user->ads()->where('status', 'active')->count(),
                'suspended_ads' => $user->ads()->where('status', 'suspended')->count(),
                'pending_reports' => $user->safetyReports()->where('status', 'pending')->count(),
                'resolved_reports' => $user->safetyReports()->where('status', 'resolved')->count(),
                'total_appeals' => $user->appeals()->count(),
                'approved_appeals' => $user->appeals()->where('status', 'approved')->count(),
                'rejected_appeals' => $user->appeals()->where('status', 'rejected')->count(),
            ];

            return response()->json([
                'success' => true,
                'data' => [
                    'user' => $user,
                    'stats' => $userStats
                ],
                'message' => 'User profile retrieved successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error retrieving user profile: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving user profile',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Send moderation notification to user
     */
    private function sendModerationNotification($userId, $type, $reason, $adId = null)
    {
        try {
            $user = User::find($userId);
            if (!$user) return;

            $message = $this->getNotificationMessage($type, $reason, $adId);
            
            NotificationModel::create([
                'user_id' => $userId,
                'type' => 'moderation',
                'title' => $this->getNotificationTitle($type),
                'message' => $message,
                'data' => [
                    'ad_id' => $adId,
                    'action_type' => $type,
                    'reason' => $reason,
                ],
                'is_read' => false,
            ]);

            // Send email notification if user has email
            if ($user->email) {
                // In a real implementation, you would send an email here
                // Mail::to($user->email)->send(new ModerationNotification($user, $type, $reason, $adId));
            }
        } catch (\Exception $e) {
            Log::error('Error sending moderation notification: ' . $e->getMessage());
        }
    }

    /**
     * Get notification title based on action type
     */
    private function getNotificationTitle($type)
    {
        $titles = [
            'ad_suspended' => 'Ad Suspended',
            'ad_rejected' => 'Ad Rejected',
            'ad_deleted' => 'Ad Deleted',
            'ad_approved' => 'Ad Approved',
            'user_suspended' => 'Account Suspended',
            'user_banned' => 'Account Banned',
        ];

        return $titles[$type] ?? 'Moderation Action';
    }

    /**
     * Get notification message based on action type
     */
    private function getNotificationMessage($type, $reason, $adId = null)
    {
        switch ($type) {
            case 'ad_suspended':
                return "Your ad has been suspended. Reason: {$reason}. Please contact support if you believe this is an error.";
            case 'ad_rejected':
                return "Your ad has been rejected. Reason: {$reason}. Please review our guidelines and resubmit.";
            case 'ad_deleted':
                return "Your ad has been deleted. Reason: {$reason}. Please contact support for more information.";
            case 'ad_approved':
                return "Great news! Your ad has been approved and is now live.";
            case 'user_suspended':
                return "Your account has been suspended. Reason: {$reason}. Please contact support for more information.";
            case 'user_banned':
                return "Your account has been banned. Reason: {$reason}. Please contact support for more information.";
            default:
                return "A moderation action has been taken on your account. Reason: {$reason}";
        }
    }

    /**
     * Prepare Excel data
     */
    private function prepareExcelData($data)
    {
        return [
            'ad_info' => $data['ad_info'],
            'performance_metrics' => $data['performance_metrics'],
            'geographic_analytics' => $data['geographic_analytics'],
            'temporal_analytics' => $data['temporal_analytics'],
            'engagement_analytics' => $data['engagement_analytics'],
            'chat_analytics' => $data['chat_analytics'],
        ];
    }

    /**
     * Prepare CSV data
     */
    private function prepareCsvData($data)
    {
        $csvData = [];
        
        // Performance metrics
        $csvData['Total Impressions'] = $data['performance_metrics']['impressions'];
        $csvData['Total Views'] = $data['performance_metrics']['views']['total'];
        $csvData['Unique Views'] = $data['performance_metrics']['views']['unique'];
        $csvData['Total Clicks'] = $data['performance_metrics']['clicks']['total'];
        $csvData['Unique Clicks'] = $data['performance_metrics']['clicks']['unique'];
        $csvData['CTR (%)'] = $data['performance_metrics']['ctr'];
        $csvData['Engagement Rate (%)'] = $data['performance_metrics']['engagement_rate'];

        // Engagement metrics
        $csvData['Likes'] = $data['engagement_analytics']['likes'];
        $csvData['Favorites'] = $data['engagement_analytics']['favorites'];
        $csvData['Call Clicks'] = $data['engagement_analytics']['call_clicks'];
        $csvData['WhatsApp Clicks'] = $data['engagement_analytics']['whatsapp_clicks'];

        // Chat metrics
        $csvData['Total Chats'] = $data['chat_analytics']['total_chats'];
        $csvData['Total Messages'] = $data['chat_analytics']['total_messages'];

        return $csvData;
    }

    /**
     * Generate chat transcript
     */
    private function generateChatTranscript($chatData)
    {
        $transcript = "Chat Transcripts for Ad ID: " . array_keys($chatData)[0] . "\n";
        $transcript .= "Generated on: " . now() . "\n\n";

        foreach ($chatData as $senderId => $conversation) {
            $transcript .= "Conversation with: " . $conversation['sender'] . "\n";
            $transcript .= "Total Messages: " . $conversation['total_messages'] . "\n\n";

            foreach ($conversation['messages'] as $message) {
                $transcript .= "[" . $message['timestamp'] . "] " . $message['sender_type'] . ": " . $message['message'] . "\n";
            }

            $transcript .= "\n" . str_repeat("-", 50) . "\n\n";
        }

        return $transcript;
    }

    /**
     * Get enhanced analytics data for API.
     *
     * @param int $adId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnhancedAnalyticsData($adId)
    {
        $ad = Ad::find($adId);
        
        // Mock data generation
        $mockData = [
            'success' => true,
            'data' => [
                'ad_info' => [
                    'title' => $ad ? $ad->title : 'Demo Ad ' . $adId,
                    'category' => $ad && $ad->category ? $ad->category->name : 'Electronics',
                    'price' => $ad ? $ad->price : 999.99,
                    'location' => $ad ? ($ad->city . ', ' . $ad->country) : 'New York, USA',
                    'created_at' => $ad ? $ad->created_at : now(),
                    'seller_info' => [
                        'name' => $ad && $ad->user ? $ad->user->name : 'Demo Seller',
                        'email' => $ad && $ad->user ? $ad->user->email : 'seller@example.com',
                    ]
                ],
                'safety_analytics' => [
                    'safety_score' => 95,
                    'user_trust_score' => 88,
                    'total_reports' => 0,
                    'pending_reports' => 0,
                    'risk_level' => 'LOW',
                    'current_ad_status' => $ad ? $ad->status : 'Active',
                    'report_details' => []
                ],
                'performance_metrics' => [
                    'impressions' => 1250,
                    'views' => ['total' => 850],
                    'clicks' => ['total' => 120],
                    'ctr' => 14.2
                ],
                'engagement_analytics' => [
                    'likes' => 45,
                    'favorites' => 12,
                    'call_clicks' => 8,
                    'whatsapp_clicks' => 15
                ],
                'reporter_analytics' => [
                    'reporter_details' => []
                ],
                'user_profile_analytics' => [
                    'user_info' => [
                        'name' => $ad && $ad->user ? $ad->user->name : 'Demo Seller',
                        'email' => $ad && $ad->user ? $ad->user->email : 'seller@example.com',
                        'phone' => '+1 234 567 8900',
                        'join_date' => now()->subMonths(6),
                        'last_activity' => now()
                    ],
                    'verification_status' => [
                        'email_verified' => true,
                        'phone_verified' => true,
                        'id_verified' => true,
                        'total_verifications' => 3
                    ]
                ],
                'moderation_actions' => [
                    'ad_moderation_actions' => [],
                    'user_moderation_actions' => []
                ]
            ]
        ];

        return response()->json($mockData);
    }
}
