<?php

class DatabaseSeeder extends Seeder {

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Eloquent::unguard();

        // IMPORTANT: Do not change order without understanding DB structure and each class first
         $this->call('UserTableSSNDecrypter'); // Decrypt employees' SSNs
         $this->call('UserTableSeeder'); // Update existing employees and add new employees
         $this->call('CourseTableSeeder'); // Add/update courses
         $this->call('UserTableSSNEncrypter'); // Encrypt employees' SSNs
         $this->call('StudentTableSeeder'); // Add/update students
         $this->call('CourseStudentTableSeeder'); // Add/update course-student enrollment (matrĂ­cula)

        // Step 2 :New seeders to add programs to programs_user table
           // $this->call('ProgramUserTableSeeder'); // Adds new lines to programs_users table using programs_users.csv file (Refer to OLAS guide for usage)
    }

    /**
     * Seeds a table by reading from a csv file
     *
     * Example: $this->insertFromCSV('courses', 'courses.csv');
     *
     * @param string    $table          Name of the table to be seeded
     * @param string    $filename       Name and extension of the file
     *
     * @var resource    $file           Pointer to CSV file to get imported
     * @var array       $columns        Array with column names for the table
     * @var int         $rowIndex       Index of row number
     * @var array       $dbArray        Array to be inserted into the database
     * @var int         $columnIndex    Index of column number
     *
     * @return void
     */
    public function insertFromCSV($table, $filename)
    {
        // Disable foreign key checks before truncating
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        // Truncate table
        DB::table($table)->truncate();

        // Enable foreign key checks
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        // Get columns
        $file = fopen('app/database/csv/'.$filename, 'r');
        $columns = fgetcsv($file, 5000, ",");

        /** Initialize row index to 0 */
        $rowIndex = 0;

        /** Initialize empty array */
        $dbArray=array();

        /** Read each row */
        while($data = fgetcsv($file, 5000, ","))
        {
            /** Initialize column index */
            $columnIndex = 0;

            /** For each column within a row, assign column name and value */
            foreach($data as $value)
            {
                $dbArray[$rowIndex][$columns[$columnIndex]] = $value;
                $columnIndex++;
            }
            $rowIndex++;
        }

        DB::table($table)->insert($dbArray);
    }
}