<?php

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

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\Hash;
use Illuminate\Support\Facades\Log;
use App\Models\User;
use App\Models\Enrollment;
use App\Models\FeePayment;

class StudentController extends BaseController
{
    /**
     * Get list of students.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        try {
            $query = User::where('role', 'student')
                ->withCount('enrollments');
            
            // Search
            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}%")
                      ->orWhere('phone', 'like', "%{$search}%");
                });
            }
            
            // Filter by enrollment status
            if ($request->has('enrolled') && $request->enrolled !== '') {
                if ($request->enrolled == '1') {
                    $query->has('enrollments');
                } else {
                    $query->doesntHave('enrollments');
                }
            }
            
            $students = $query->orderBy('created_at', 'desc')
                ->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,
                    'created_at' => $student->created_at,
                ];
            });
            
            return $this->paginated($data, $students);
        } catch (\Exception $e) {
            Log::error('Admin 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 {
            $student = User::where('id', $id)
                ->where('role', 'student')
                ->with(['enrollments.course', 'enrollments.courseOffering'])
                ->firstOrFail();
            
            // Get enrollments
            $enrollments = $student->enrollments->map(function($enrollment) use ($student) {
                $courseFee = $enrollment->course->fees ?? 0;
                $paidAmount = FeePayment::where('student_id', $student->id)
                    ->where(function($q) use ($enrollment) {
                        $q->where('course_id', $enrollment->course_id);
                        if ($enrollment->course_offering_id) {
                            $q->orWhere('course_offering_id', $enrollment->course_offering_id);
                        }
                    })
                    ->sum('amount');
                
                return [
                    'id' => $enrollment->id,
                    'course' => [
                        'id' => $enrollment->course->id ?? null,
                        'name' => $enrollment->course->name ?? 'N/A',
                        'fees' => $courseFee,
                    ],
                    'course_offering' => $enrollment->courseOffering ? [
                        'id' => $enrollment->courseOffering->id,
                        'name' => $enrollment->courseOffering->name,
                    ] : null,
                    'paid_amount' => $paidAmount,
                    'balance' => $courseFee - $paidAmount,
                    'enrolled_at' => $enrollment->created_at,
                    'status' => $enrollment->status ?? 'active',
                ];
            });
            
            // Decrypt profile picture
            $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,
                'updated_at' => $student->updated_at,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Student not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Admin Student API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching student details.', null, 500);
        }
    }
    
    /**
     * Create student.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        try {
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:users',
                'school_id' => 'nullable|string|max:255|unique:users',
                'phone' => 'nullable|string|max:20',
                'address' => 'nullable|string|max:500',
                'password' => 'required|string|min:8|confirmed',
            ]);
            
            $student = User::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'school_id' => $validated['school_id'] ?? null,
                'phone' => $validated['phone'] ?? null,
                'address' => $validated['address'] ?? null,
                'password' => Hash::make($validated['password']),
                'role' => 'student',
            ]);
            
            return $this->success([
                'id' => $student->id,
                'name' => $student->name,
                'email' => $student->email,
            ], 'Student created successfully', 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->error('Validation failed', $e->errors(), 422);
        } catch (\Exception $e) {
            Log::error('Admin Student Create API error: ' . $e->getMessage());
            return $this->error('An error occurred while creating student.', null, 500);
        }
    }
    
    /**
     * Update student.
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        try {
            $student = User::where('id', $id)
                ->where('role', 'student')
                ->firstOrFail();
            
            $validated = $request->validate([
                'name' => 'sometimes|required|string|max:255',
                'email' => 'sometimes|required|string|email|max:255|unique:users,email,' . $id,
                'school_id' => 'nullable|string|max:255|unique:users,school_id,' . $id,
                'phone' => 'nullable|string|max:20',
                'address' => 'nullable|string|max:500',
                'password' => 'nullable|string|min:8|confirmed',
            ]);
            
            if (isset($validated['password'])) {
                $validated['password'] = Hash::make($validated['password']);
            } else {
                unset($validated['password']);
            }
            
            $student->update($validated);
            
            return $this->success([
                'id' => $student->id,
                'name' => $student->name,
                'email' => $student->email,
            ], 'Student updated successfully');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->error('Validation failed', $e->errors(), 422);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Student not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Admin Student Update API error: ' . $e->getMessage());
            return $this->error('An error occurred while updating student.', null, 500);
        }
    }
    
    /**
     * Delete student.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        try {
            $student = User::where('id', $id)
                ->where('role', 'student')
                ->firstOrFail();
            
            $student->delete();
            
            return $this->success(null, 'Student deleted successfully');
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Student not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Admin Student Delete API error: ' . $e->getMessage());
            return $this->error('An error occurred while deleting student.', null, 500);
        }
    }
}

