<?php

namespace App\Imports;

use Maatwebsite\Excel\Concerns\ToModel;
use App\Models\Student;
use App\Models\StudentRegister;
use App\Models\TeacherClass;
use App\Models\StudentClass;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Mail\Message;
use Exception;

class StudentsImport implements ToModel
{
    private $current = 0;
    private $insertedData;
    private $emailsSent;
    private $teacherId;
    private $teacherClassIds;
    private $studentsResponse;

    public function __construct(&$insertedData, $teacherId, $teacherClassIds)
    {
        $this->insertedData = &$insertedData;
        $this->emailsSent = [];
        $this->teacherId = $teacherId;
        $this->teacherClassIds = $teacherClassIds;
        $this->studentsResponse = [];
    }

    public function model(array $row)
    {
        $this->current++;

        if ($this->current > 1) { // Skip header row
            try {

                // Check if student exists in the `students` table
                $student = Student::where('email', $row[3])->first();
                $studentId = $student ? $student->id : null;
                $isNewStudent = false;
                $plainPassword = null;

                // Agar student `Student` table main nahi hai, to naya student create karein
                if (!$student) {
                    $username = $this->generateRandomUsername($row[0]);
                    $plainPassword = $this->generateRandomPassword(); // Generate a plain text password
                    $hashedPassword = Hash::make($plainPassword); // Hash the password

                    $student = Student::create([
                        'first_name' => $row[0],
                        'last_name' => $row[1],
                        'email' => $row[3],
                        'username' => $username,
                        'password' => $hashedPassword, // Store the hashed password in the database
                    ]);

                    $studentId = $student->id;
                    $isNewStudent = true; // Mark this as a newly added student
                }

                // Check if the student already exists in `student_registers`
                $studentRegister = StudentRegister::where('student_id', $studentId)
                    ->where('email', $row[3])
                    ->first();

                // Sirf unhe register karein agar `StudentRegister` table main pehle se nahi hai
                if (!$studentRegister) {
                    
                    // Get teacher class details
                    $teacherClass = TeacherClass::whereIn('id', $this->teacherClassIds)
                        ->where('teacher_id', $this->teacherId)
                        ->first();
    
                    if (!$teacherClass) {
                        return null;
                    }

                    $classId = $teacherClass->class_id;
                    $section = $teacherClass->section;
                    $subject_id = $teacherClass->subject_id;
                
                
                    $studentRegister = StudentRegister::create([
                        'student_id' => $studentId,
                        'first_name' => $row[0],
                        'last_name' => $row[1],
                        'teacher_id' => $this->teacherId,
                        'class_id' => $classId,
                        'upn' => $row[2],
                        'email' => $row[3],
                    ]);

                    $this->insertedData[] = $studentRegister;
                }

                // Email bhejna sirf tab hai jab student bilkul naya `Student` table mein add ho raha hai
                if ($isNewStudent && $plainPassword) {
                    $this->sendEmail($student->email, $plainPassword, $student->username);
                }

                // Add or update student classes based on `teacher_class_id`
                foreach ($this->teacherClassIds as $teacherClassId) {
                    
                    // Fetch specific TeacherClass for this teacher_class_id
                    $teacherClass = TeacherClass::where('id', $teacherClassId)
                        ->where('teacher_id', $this->teacherId)
                        ->first();
    
                    if (!$teacherClass) {
                        continue; // Skip if teacher class not found
                    }
    
                    $classId = $teacherClass->class_id;
                    $section = $teacherClass->section;
                    $subject_id = $teacherClass->subject_id;
                
                
                    $existingClass = StudentClass::where([
                        'student_register_id' => $studentRegister->id,
                        'class_id' => $classId,
                        'teacher_class_id' => $teacherClassId,
                        'teacher_id' => $this->teacherId,
                    ])->first();

                    if (!$existingClass) {
                        StudentClass::create([
                            'student_id' => $studentId,
                            'student_register_id' => $studentRegister->id,
                            'teacher_id' => $this->teacherId,
                            'class_id' => $classId,
                            'section' => $section,
                            'subject_id' => $subject_id,
                            'teacher_class_id' => $teacherClassId,
                        ]);
                    }
                }

                // Add student data to response
                $this->studentsResponse[] = [
                    'first_name' => $row[0],
                    'last_name' => $row[1],
                    'email' => $row[3],
                    'status' => $isNewStudent ? 'Newly Added in Student Table' : 'Already Exists'
                ];
            } catch (Exception $e) {
                return null;
            }
        }
    }

    private function sendEmail($email, $plainPassword, $username)
    {
        if ($email && !in_array($email, $this->emailsSent)) {
            $link = env('APP_LINK');
            Mail::send('students', ['email' => $email, 'password' => $plainPassword, 'username' => $username, 'link' => $link], function (Message $message) use ($email) {
                $message->subject('Account Details');
                $message->to($email);
                $message->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'));
            });

            $this->emailsSent[] = $email;
        }
    }

    private function generateRandomUsername($firstName)
    {
        // Clean first name to remove spaces and special characters (optional)
        $cleanedFirstName = preg_replace('/[^a-zA-Z0-9]/', '', $firstName);

        // Ensure the first name part is not empty
        $cleanedFirstName = $cleanedFirstName ?: 'User';

        // Generate username using the cleaned first name with a random 4-digit number
        return $cleanedFirstName . rand(1000, 9999);
    }

    private function generateRandomPassword()
    {
        return substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789!@#$%&*'), 0, 8);
    }

    public function getResponseData()
    {
        return $this->studentsResponse;
    }
}