<?php

class StudentTableSeeder extends Seeder {

    public function run()
    {
        // Set term
        $term = "B91";

        // 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);

        // Open file
        $file_path = 'http://136.145.180.72/tools/proceso_files/';
        $file_name = 'webmatri_vivienda_b83-b91.dat';

        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, 5000, ";"))
            {
                // Skip iterations from previous semesters
                if(trim($data[8]) != $term)
                {
                    continue;
                }

                // Add read count
                $read++;

                try
                {
                    // Get row info
                    $number = str_pad(trim($data[1]), 9, '000000000', STR_PAD_LEFT);
                    $name = trim(ucwords(strtoupper($data[2])));
                    $email = trim($data[15]).'@upr.edu';
                    $school_code = trim($data[5]);
                    $conc_code = 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,
                                    'school_code' => $school_code,
                                    'conc_code' => $conc_code,
                                    'updated_at' => date("Y-m-d H:i:s"),
                                )
                            );
                        $this->command->info($read.' - Updated '.$number.': '.$name.' ['.$school_code.' '.$conc_code.']');
                        $updated++;

                    }

                    // Otherwise, add student and add to added
                    else
                    {
                        Student::create(array(
                            'number' => $number,
                            'name' => $name,
                            'email' => $email,
                            '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.');
        }
    }

}