<?php

class ProgramUserTableSeeder extends Seeder {

    public function run()
    {
        // Disable query logging to avoid memory exhaustion
        // SELECT DISTINCT `program_id` , `user_id` FROM `courses`

        DB::disableQueryLog();

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

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

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

            // Read each row
            while($data = fgetcsv($file, 5000, ","))
            {
                // Add read count
                $read++;

                try
                {
                    // Get row info
                    $program_id = trim($data[0]);
                    $user_id = trim($data[1]);

                    // Missing data trow exception
                    if(!$program_id || !$user_id){
                        throw new Exception('NON-FATAL ERROR(line '.$read.'): Missing information, read \''.implode(",", $data).'\'');
                    }

                    // If user has default 999 program, delete and insert rows

                    if(DB::table('program_user')->where('program_id', '=', 999)->where('user_id', '=', $user_id)->get()){
                        $this->command->info('Would had deleted default program if not needed verify down for new program insert or inserts: user_id = '.$user_id);
                        // Delete from table program_user default program
                        DB::table('program_user')->where('program_id', '=', 999)->where('user_id', '=', $user_id)->delete();
                        $deleted++;
                        // Insert new program_user row if it doesnt exist
                        if(!(DB::table('program_user')->where('program_id', '=', $program_id)->where('user_id', '=', $user_id)->get())){
                            DB::table('program_user')->insert(array('program_id' => $program_id, 'user_id' => $user_id));
                            $this->command->info('Insert after deleting default program for user_id = '.$user_id);
                            $added++;
                        }
                    }else{
                        // Insert new program_user row if it doesnt exist
                        if(!(DB::table('program_user')->where('program_id', '=', $program_id)->where('user_id', '=', $user_id)->get())){
                            DB::table('program_user')->insert(array('program_id' => $program_id, 'user_id' => $user_id));
                            $this->command->info('Insert new line, no default program for user_id = '.$user_id);
                            $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('- Deleted default programs from users (999): '.$deleted);
            $this->command->info('- Added (new active): '.$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 '.$filename.' could not be opened. Make sure it is located in the app/database/csv directory of this project.');
        }
    }
}
