<?php

namespace App\Http\Controllers\Api\V1\Admin;

use App\Http\Controllers\Api\V1\BaseController;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class InstructorController extends BaseController
{
    /**
     * Display a listing of instructors.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $query = User::where('role', 'instructor');
        
        // Search functionality
        if ($request->has('search')) {
            $search = $request->get('search');
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }
        
        // Filter by status (active/inactive based on email verification)
        if ($request->has('status')) {
            if ($request->get('status') === 'active') {
                $query->whereNotNull('email_verified_at');
            } elseif ($request->get('status') === 'inactive') {
                $query->whereNull('email_verified_at');
            }
        }
        
        // Sort functionality
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);
        
        // Pagination
        $perPage = $request->get('per_page', 15);
        $instructors = $query->paginate($perPage);
        
        return $this->paginated($instructors->items(), $instructors);
    }
    
    /**
     * Store a newly created instructor.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:500',
            'school_id' => 'nullable|string|max:100',
            'send_welcome_email' => 'boolean'
        ]);
        
        if ($validator->fails()) {
            return $this->error('Validation failed.', $validator->errors(), 422);
        }
        
        try {
            $instructor = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'role' => 'instructor',
                'phone' => $request->phone,
                'address' => $request->address,
                'school_id' => $request->school_id,
                'email_verified_at' => now(), // Auto-verify instructor accounts
            ]);
            
            // Create API token for the instructor
            $token = $instructor->createToken('instructor_api_token')->plainTextToken;
            
            // Send welcome email if requested
            if ($request->get('send_welcome_email', false)) {
                try {
                    \Mail::to($instructor->email)->send(new \App\Mail\InstructorWelcomeMail($instructor, $request->password));
                } catch (\Exception $e) {
                    \Log::error('Failed to send welcome email to instructor: ' . $e->getMessage());
                }
            }
            
            $responseData = [
                'instructor' => $instructor->fresh(),
                'api_token' => $token
            ];
            
            return $this->success($responseData, 'Instructor created successfully.', 201);
            
        } catch (\Exception $e) {
            return $this->error('Failed to create instructor: ' . $e->getMessage(), null, 500);
        }
    }
    
    /**
     * Display the specified instructor.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $instructor = User::where('role', 'instructor')->find($id);
        
        if (!$instructor) {
            return $this->error('Instructor not found.', null, 404);
        }
        
        // Load additional instructor data
        $instructor->load(['notifications']);
        
        // Get instructor statistics (with error handling)
        try {
            $stats = [
                'total_courses' => $instructor->courses()->count(),
                'active_courses' => $instructor->courses()->where('status', 'active')->count(),
                'total_students' => $this->getTotalStudentsForInstructor($instructor),
                'total_assignments' => $this->getTotalAssignmentsForInstructor($instructor),
                'total_videos' => $this->getTotalVideosForInstructor($instructor),
            ];
        } catch (\Exception $e) {
            // If courses table doesn't exist or has issues, provide basic stats
            $stats = [
                'total_courses' => 0,
                'active_courses' => 0,
                'total_students' => 0,
                'total_assignments' => 0,
                'total_videos' => 0,
                'error' => 'Statistics unavailable: ' . $e->getMessage()
            ];
        }
        
        $responseData = [
            'instructor' => $instructor,
            'statistics' => $stats
        ];
        
        return $this->success($responseData, 'Instructor retrieved successfully.');
    }
    
    /**
     * Update the specified instructor.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $instructor = User::where('role', 'instructor')->find($id);
        
        if (!$instructor) {
            return $this->error('Instructor not found.', null, 404);
        }
        
        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|required|string|max:255',
            'email' => [
                'sometimes',
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique('users')->ignore($instructor->id)
            ],
            'password' => 'sometimes|required|string|min:8|confirmed',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:500',
            'school_id' => 'nullable|string|max:100',
            'status' => 'sometimes|in:active,inactive'
        ]);
        
        if ($validator->fails()) {
            return $this->error('Validation failed.', $validator->errors(), 422);
        }
        
        try {
            $updateData = $request->only(['name', 'email', 'phone', 'address', 'school_id']);
            
            // Handle password update
            if ($request->has('password')) {
                $updateData['password'] = Hash::make($request->password);
            }
            
            // Handle status update
            if ($request->has('status')) {
                if ($request->get('status') === 'active') {
                    $updateData['email_verified_at'] = now();
                } else {
                    $updateData['email_verified_at'] = null;
                }
            }
            
            $instructor->update($updateData);
            
            return $this->success($instructor->fresh(), 'Instructor updated successfully.');
            
        } catch (\Exception $e) {
            return $this->error('Failed to update instructor: ' . $e->getMessage(), null, 500);
        }
    }
    
    /**
     * Remove the specified instructor.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $instructor = User::where('role', 'instructor')->find($id);
        
        if (!$instructor) {
            return $this->error('Instructor not found.', null, 404);
        }
        
        try {
            // Check if instructor has associated data
            $courseCount = $instructor->courses()->count();
            
            if ($courseCount > 0) {
                return $this->error('Cannot delete instructor with associated courses. Please reassign or delete courses first.', null, 400);
            }
            
            // Revoke all API tokens
            $instructor->tokens()->delete();
            
            // Delete the instructor
            $instructor->delete();
            
            return $this->success(null, 'Instructor deleted successfully.');
            
        } catch (\Exception $e) {
            return $this->error('Failed to delete instructor: ' . $e->getMessage(), null, 500);
        }
    }
    
    /**
     * Get total students for an instructor (across all courses)
     */
    private function getTotalStudentsForInstructor($instructor)
    {
        return \DB::table('enrollments')
            ->join('courses', 'enrollments.course_id', '=', 'courses.id')
            ->where('courses.instructor_id', $instructor->id)
            ->distinct('enrollments.student_id')
            ->count('enrollments.student_id');
    }
    
    /**
     * Get total assignments for an instructor
     */
    private function getTotalAssignmentsForInstructor($instructor)
    {
        // This would need to be implemented based on your assignments table structure
        // For now, returning a placeholder
        return 0;
    }
    
    /**
     * Get total videos for an instructor
     */
    private function getTotalVideosForInstructor($instructor)
    {
        return \DB::table('class_session_videos')
            ->join('courses', 'class_session_videos.course_id', '=', 'courses.id')
            ->where('courses.instructor_id', $instructor->id)
            ->count();
    }
    
    /**
     * Bulk actions for instructors
     */
    public function bulkAction(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'action' => 'required|in:activate,deactivate,delete',
            'instructor_ids' => 'required|array',
            'instructor_ids.*' => 'exists:users,id'
        ]);
        
        if ($validator->fails()) {
            return $this->error('Validation failed.', $validator->errors(), 422);
        }
        
        try {
            $action = $request->get('action');
            $instructorIds = $request->get('instructor_ids');
            $affectedCount = 0;
            
            switch ($action) {
                case 'activate':
                    $affectedCount = User::where('role', 'instructor')
                        ->whereIn('id', $instructorIds)
                        ->whereNull('email_verified_at')
                        ->update(['email_verified_at' => now()]);
                    $message = "{$affectedCount} instructors activated successfully.";
                    break;
                    
                case 'deactivate':
                    $affectedCount = User::where('role', 'instructor')
                        ->whereIn('id', $instructorIds)
                        ->update(['email_verified_at' => null]);
                    $message = "{$affectedCount} instructors deactivated successfully.";
                    break;
                    
                case 'delete':
                    // Check for associated courses before deletion
                    $instructorsWithCourses = User::where('role', 'instructor')
                        ->whereIn('id', $instructorIds)
                        ->whereHas('courses')
                        ->pluck('id');
                    
                    if ($instructorsWithCourses->isNotEmpty()) {
                        return $this->error('Cannot delete instructors with associated courses.', null, 400);
                    }
                    
                    $affectedCount = User::where('role', 'instructor')
                        ->whereIn('id', $instructorIds)
                        ->delete();
                    $message = "{$affectedCount} instructors deleted successfully.";
                    break;
            }
            
            return $this->success(['affected_count' => $affectedCount], $message);
            
        } catch (\Exception $e) {
            return $this->error('Failed to perform bulk action: ' . $e->getMessage(), null, 500);
        }
    }
}
