<?php

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

use App\Http\Controllers\Api\V1\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use App\Models\User;
use App\Models\Course;
use App\Models\Enrollment;

class StudentController extends BaseController
{
    /**
     * Get list of students enrolled in instructor's courses.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        try {
            $instructor = Auth::user();
            
            // Get all course IDs for this instructor
            $courseIds = Course::where('instructor_id', $instructor->id)
                ->where('is_active', true)
                ->pluck('id');
            
            // Get unique students enrolled in these courses
            $studentIds = Enrollment::whereIn('course_id', $courseIds)
                ->distinct('student_id')
                ->pluck('student_id');
            
            $query = User::whereIn('id', $studentIds)
                ->where('role', 'student')
                ->withCount(['enrollments' => function($q) use ($courseIds) {
                    $q->whereIn('course_id', $courseIds);
                }]);
            
            // Search filter
            if ($request->has('search') && $request->search) {
                $search = $request->search;
                $query->where(function($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('email', 'like', "%{$search}%")
                      ->orWhere('school_id', 'like', "%{$search}%");
                });
            }
            
            // Filter by course
            if ($request->has('course_id') && $request->course_id) {
                $courseStudentIds = Enrollment::where('course_id', $request->course_id)
                    ->pluck('student_id');
                $query->whereIn('id', $courseStudentIds);
            }
            
            $students = $query->orderBy('name', 'asc')
                ->paginate($request->get('per_page', 20));
            
            $data = $students->map(function($student) {
                // Decrypt profile picture if exists
                $profilePicture = null;
                if ($student->profile_picture) {
                    try {
                        $profilePicture = Crypt::decryptString($student->profile_picture);
                    } catch (\Exception $e) {
                        $profilePicture = null;
                    }
                }
                
                return [
                    'id' => $student->id,
                    'name' => $student->name,
                    'email' => $student->email,
                    'school_id' => $student->school_id,
                    'phone' => $student->phone,
                    'profile_picture' => $profilePicture,
                    'enrollments_count' => $student->enrollments_count,
                ];
            });
            
            return $this->paginated($data, $students);
        } catch (\Exception $e) {
            Log::error('Instructor Students API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching students.', null, 500);
        }
    }
    
    /**
     * Get student details.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        try {
            $instructor = Auth::user();
            
            // Get instructor's course IDs
            $courseIds = Course::where('instructor_id', $instructor->id)
                ->where('is_active', true)
                ->pluck('id');
            
            $student = User::where('id', $id)
                ->where('role', 'student')
                ->firstOrFail();
            
            // Verify student is enrolled in instructor's courses
            $isEnrolled = Enrollment::where('student_id', $student->id)
                ->whereIn('course_id', $courseIds)
                ->exists();
            
            if (!$isEnrolled) {
                return $this->error('Student not found in your courses.', null, 404);
            }
            
            // Get enrollments for this student in instructor's courses
            $enrollments = Enrollment::where('student_id', $student->id)
                ->whereIn('course_id', $courseIds)
                ->with(['course', 'courseOffering'])
                ->get()
                ->map(function($enrollment) {
                    return [
                        'id' => $enrollment->id,
                        'course' => [
                            'id' => $enrollment->course->id ?? null,
                            'name' => $enrollment->course->name ?? 'N/A',
                            'code' => $enrollment->course->code ?? 'N/A',
                        ],
                        'course_offering' => $enrollment->courseOffering ? [
                            'id' => $enrollment->courseOffering->id,
                            'name' => $enrollment->courseOffering->name,
                        ] : null,
                        'enrolled_at' => $enrollment->created_at,
                        'status' => $enrollment->status ?? 'active',
                    ];
                });
            
            // Decrypt profile picture if exists
            $profilePicture = null;
            if ($student->profile_picture) {
                try {
                    $profilePicture = Crypt::decryptString($student->profile_picture);
                } catch (\Exception $e) {
                    $profilePicture = null;
                }
            }
            
            return $this->success([
                'id' => $student->id,
                'name' => $student->name,
                'email' => $student->email,
                'school_id' => $student->school_id,
                'phone' => $student->phone,
                'address' => $student->address,
                'profile_picture' => $profilePicture,
                'enrollments' => $enrollments,
                'created_at' => $student->created_at,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Student not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Instructor Student API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching student details.', null, 500);
        }
    }
}

