<?php

class StudentTableSeeder extends Seeder {

    public function run()
    {
        // Set term
        $term = "C12";
		$semester_id = Semester::select('id')->where('code', $term)->first();

        // Disable query logging to avoid memory exhaustion
        DB::disableQueryLog();

        $this->command->info('Students table seeding started for term '.$term);

        // Initiates time
        $time_start = microtime(true);
/*
		//Primero entra la informacion basica eg. numero_estu, nombre, email
        // Open file
        $file_path = 'app/database/csv/';
//         $file_name = 'ARCEXTRT-20-C12-20220411-164329.TXT';
        $file_name = 'ARCEXT-20-C12-20220411-164329.TXT';

        if($file = fopen($file_path.$file_name, 'r'))
        {
            // Initialize count variables
            $read = 0;
            $added =0;
            $updated = 0;
            $error = 0;
            $warning = 0;

            // Read each row
            while($data = fgetcsv($file, 0, ";"))
            {
                // Skip iterations from previous semesters
//                 if(trim($data[8]) != $term)
//                 {
//                     continue;
//                 }

                // Add read count
                $read++;

                try
                {
                    // Get row info
                    $number = str_pad(trim($data[2]), 9, '000000000', STR_PAD_LEFT);
                    $name = trim(ucwords(strtoupper($data[4])));
                    $email = trim($data[5]).'@upr.edu';
//                     $school_code = trim($data[5]);
                    $gender = trim($data[7]);

                    // If any row is empty, raise an exception
                    if(!$number || !$name)
                    {
                        throw new Exception('NON-FATAL ERROR(line '.$read.'): Missing name or student number, read \''.implode(",", $data).'\'');
                    }

                    // If user has no email, issue warning and set default
                    if(!$email)
                    {

                        $this->command->info('WARNING(line '.$read.'): Missing email, read \''.implode(",", $data).'\'; users will not be able to send messages to students without an email');
                        $email = 'olas.rrp@upr.edu';
                        $warning++;

                    }


                    // Check if student exists
                    $student = Student::where('number', $number)->count();

                    // If s/he does, update information and add to updated
                    if($student)
                    {
                        DB::table('students')
                            ->where('number', $number)
                            ->update(
                                array(
                                    'name' => $name,
                                    'email' => $email,
                                    'gender' => $gender,
//                                     'school_code' => $school_code,
//                                     'conc_code' => $conc_code,
                                    'updated_at' => date("Y-m-d H:i:s"),
                                )
                            );
                        $this->command->info($read.' - Updated '.$number.': '.$name.' ['.$gender.']');
                        $updated++;

                    }

                    // Otherwise, add student and add to added
                    else
                    {
                        Student::create(array(
                            'number' => $number,
                            'name' => $name,
                            'email' => $email,
							'gender' => $gender,
//                             'school_code' => $school_code,
//                             'conc_code' => $conc_code,
                            'created_at' => date("Y-m-d H:i:s"),
                            'updated_at' => date("Y-m-d H:i:s")
                            )
                        );
                        $this->command->info($read.' - Added '.$number.': '.$name);
                        $added++;
                    }

                }

                // If an exception is raised, show the message and add to error
                catch(Exception $e)
                {
                    $this->command->info($e->getMessage());
                    $error++;
                };
            }

            // Stop time
            $time_end = microtime(true);

            // Display results
            $this->command->info('------------------------------------------------------------');
            $this->command->info('Results on '.date('M d, Y, h:i:s a'));
            $this->command->info('- Runtime: '.(round($time_end - $time_start, 3)).' seconds');
            $this->command->info('- Read: '.$read);
            $this->command->info('- Updated (active): '.$updated);
            $this->command->info('- Added (new active, all): '.$added);
            $this->command->info('- Added (new active, without email): '.$warning);
            $this->command->info('- Not updated (inactive): '.(Student::count() - $updated - $added));
            $this->command->info('- Not added/updated (errors or missing information): '.($error));

            // Close file
            fclose($file);
        }
        // File cannot be opened, display error and exit
        else
        {
            $this->command->info('File '.$file_name.' could not be opened. Make sure it is located in the app/database/csv directory of this project.');
        }
*/    
		//  Segundo entra la informacion de programa, grado, nivel, anho y anhade en program_student_semester
         $file_path = 'app/database/csv/';
        $file_name = 'ARCEXTRT-20-C12-20220411-164329.TXT';
//         $file_name = 'ARCEXT-20-C12-20220411-164329.TXT';

        if($file = fopen($file_path.$file_name, 'r'))
        {
            // Initialize count variables
            $read = 0;
            $added =0;
            $updated = 0;
            $error = 0;
            $warning = 0;

            // Read each row
            while($data = fgetcsv($file, 0, ";"))
            {
                // Skip iterations from previous semesters
//                 if(trim($data[8]) != $term)
//                 {
//                     continue;
//                 }
// 
                // Add read count
                $read++;

                try
                {
                    // Get row info
                    $number = str_pad(trim($data[3]), 9, '000000000', STR_PAD_LEFT);
//                     $name = trim(ucwords(strtoupper($data[4])));
//                     $email = trim($data[5]).'@upr.edu';
                    $school_code = trim($data[19]);
                    $conc_code = trim($data[21]);
                    $level = trim($data[16]);
                    $degree = trim($data[23]);
                    $year = trim($data[25]);
//                     $school_code = trim($data[5]);
//                     $conc_code = trim($data[7]);

                    // If any row is empty, raise an exception
                    if(!$number)
                    {
                        throw new Exception('NON-FATAL ERROR(line '.$read.'): Missing name or student number, read \''.implode(",", $data).'\'');
                    }

                    $program=DB::table('programs')
                            ->where('code', $conc_code)
                            ->where('degree', $degree)
                            ->select('id')
                            ->first();
//                             var_dump($program_id);
					if(!$program)$program->id=null;
                    // Check if student exists
                    $student = Student::where('number', $number)->count();

                    // If s/he does, update information and add to updated
                    if($student)
                    {
						$student_id = Student::select('id')->where('number', $number)->first();
//                     print $read."\n";
						
                        DB::table('students')
                            ->where('number', $number)
                            ->update(
                                array(
//                                     'name' => $name,
//                                     'email' => $email,
                                    'school_code' => $school_code,
                                    'conc_code' => $conc_code,
                                    'program_id' => $program->id,
                                    'degree' => $degree,
                                    'level' => $level,
                                    'year' => $year,
                                    'updated_at' => date("Y-m-d H:i:s"),
                                )
                            );
                        $this->command->info($read.' - Updated '.$number.': '.$program->id.' ['.$school_code.' '.$conc_code.']');
                        $updated++;
                        
                        DB::table('program_student_semester')->insert(
							array('student_id' => $student_id->id,
								  'program_id' => $program->id,
								  'semester_id' => $semester_id->id
								  )
						);

                    }

                    // Otherwise, add student and add to added
                    else
                    {
                        $this->command->info($read.' - Student not in system'.$number.': '.$name);
                        $warning++;
                    }

                }

                // If an exception is raised, show the message and add to error
                catch(Exception $e)
                {
                    $this->command->info($e->getMessage());
                    $error++;
                };
            }

            // Stop time
            $time_end = microtime(true);

            // Display results
            $this->command->info('------------------------------------------------------------');
            $this->command->info('Results on '.date('M d, Y, h:i:s a'));
            $this->command->info('- Runtime: '.(round($time_end - $time_start, 3)).' seconds');
            $this->command->info('- Read: '.$read);
            $this->command->info('- Updated (active): '.$updated);
            $this->command->info('- Added (new active, all): '.$added);
            $this->command->info('- Added (new active, without email): '.$warning);
            $this->command->info('- Not updated (inactive): '.(Student::count() - $updated - $added));
            $this->command->info('- Not added/updated (errors or missing information): '.($error));

            // Close file
            fclose($file);
        }
        // File cannot be opened, display error and exit
        else
        {
            $this->command->info('File '.$file_name.' could not be opened. Make sure it is located in the app/database/csv directory of this project.');
        }
    
   
    
    }

}
