<?php

class CourseStudentTableSeeder extends Seeder {

    public function run()
    {
        // Disable query logging to avoid memory exhaustion
        DB::disableQueryLog();

        $this->command->info('-----------------------------------------');
        $this->command->info('-----------------------------------------');
        $this->command->info('Course student table seeding started...');

        // Initiates time
        $time_start = microtime(true);

        // Open file
        if($file = fopen('app/database/csv/estudiante_curso.csv', 'r'))
        {
            // Initialize count variables
            $read = 0;
            $added =0;
            $updated = 0;
            $error = 0;
            $semester_id = NULL;

            // Read each row
            while($data = fgetcsv($file, 5000)) // se cambio delimitador para evitar problemas con nombre separados del apellido con coma
            {
                // Add read count
                $read++;

                try
                {
                    $student_number = trim($data[1]);
                    $code_number_section = trim($data[2]);
                    $term_code = trim($data[3]);

                    // If any required field is empty, raise an exception
                    if(!$code_number_section || !$student_number || !$term_code)
                    {
                        throw new Exception('WARNING (line '.($read+1).'): Missing information, read \''.implode(",", $data).'\'');
                    }

                    if(!$semester_id)
                    {
                        // Get semester
                        $semester_id = Semester::select('id')->where('code', strtoupper($term_code))->first()['id'];

                        // If semester code is not in the first line, abort script
                        if(!$semester_id)
                        {
                            $this->command->info('FATAL ERROR(line '.$read.'): The semester code (i.e. B71) is required. Please check the file. Field contents: \''.$term_code.'\'');
                            exit();
                        }
                    }

                    // Get row info
                    $course = Course::select('id')->where('code', trim(substr($code_number_section, 0, 4)))->where('number', trim(substr($code_number_section, 4, 4)))->where('section', trim(substr($code_number_section, 8, 3)))->where('semester_id', $semester_id)->first();
                    $student_id = Student::select('id')->where('number', trim($student_number))->first()['id'];

                    // If information is incorrect or not present in the database, raise an exception
                    if(!$course['id'])
                    {
                        throw new Exception('WARNING (line '.($read+1).'): Course '.$code_number_section.' not found in the database.');
                    }
                    if(!$student_id)
                    {
                        throw new Exception('WARNING (line '.($read+1).'): Student '.$student_number.' not found in the database.');
                    }

                    // If course-student combination exists, touch the timestamp
                    if(DB::table('course_student')->where('course_id', $course->id )->where('student_id', $student_id)->count())
                    {
                        $course->students()->updateExistingPivot($student_id, array('updated_at' => date("Y-m-d H:i:s", time())));
                        // $this->command->info('Touched (line '.($read+1).'): ['.$student_number.', '.$code_number_section.'].');
                        $updated++;
                    }
                    // Otherwise, add the combination
                    else
                    {
                        // Assign student to course
                        $course->students()->attach($student_id, array('semester_id' => $semester_id));
                        $this->command->info('Added (line '.($read+1).'): ['.$student_number.', '.$code_number_section.'].');
                    }

                    $added++;
                }

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

            // Delete all inactive users for current term
            DB::table('course_student')
                ->where('updated_at', '<', date('Y-m-d'))
                ->where('semester_id', $semester_id)
                ->delete();

            // 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: '.$added);
            $this->command->info('- Not added (errors or missing information): '.($error));

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

}
