<?php

namespace App\Imports;

use App\{RFAlumno,RFCarrera,RFPeriodo,RFAspirante};

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\{ToCollection, WithHeadingRow};

class AlumnosCollectionImport implements ToCollection, WithHeadingRow
{
    /**
    * @param Collection $collection
    */
    public function collection(Collection $rows)
    {
    	//dd($rows->first());
    	$cad = "";
    	$pv = $rows->first();
      //dd($pv);
    	if( !$pv->has('folio')){$cad.="<li>folio</li>"; }
      if( !$pv->has('carrera')){$cad.="<li>carrera</li>"; }
      if( !$pv->has('paterno')){$cad.="<li>paterno</li>"; }
      if( !$pv->has('materno')){$cad.="<li>materno</li>"; }
      if( !$pv->has('nombre')){$cad.="<li>nombre</li>"; }
      if( !$pv->has('curp')){$cad.="<li>curp</li>"; }
      if( !$pv->has('sexo')){$cad.="<li>sexo</li>"; }
      if( !$pv->has('telefono')){$cad.="<li>telefono</li>"; }
      if( !$pv->has('correo')){$cad.="<li>correo</li>"; }
      //if( !$pv->has('pago')){$cad.="<li>pago</li>"; }
    	
    	if ($cad!="") {
    		abort(406, "Por favor, verifica que los siguientes encabezados correspondan: <ul>".$cad."</ul>" )->header('Content-Type', 'text/plain');
    	}
      $i = 2;
    	foreach ($rows as $row) 
      {
        $asp=RFAspirante::where('id',$row['folio'])->first();
        $car=RFCarrera::where('nombre', str_replace("-","",str_replace("2017", "", $row['carrera'])) )->select('id')->first();
        $per=RFPeriodo::where('ficha', '1')->first();

        
        if ($row['sexo']=='H'||$row['sexo']=='M') {
          //if ($row['sexo']=='M') { $sex = "H"; } else { $sex = "M"; }
        	if (!$car==null) {
            if ($asp==null) {

          		RFAspirante::updateOrCreate(
                ['id'=>$row['folio'] ], //Condicion
                [                       //actualizar
                  'fk_idCarrera'=>$car->id,
                  'fk_idEstatus'=>1, //estaba en 1
                  'fk_idPeriodo'=>$per->id,
                  'semestre'=>'0',
                  'ap_paterno'=>$row['paterno'],
                  'ap_materno'=>$row['materno'],
                  'nombre'=>$row['nombre'],
                  'curp'=>$row['curp'],
                  'sexo'=>$row['sexo'],
                  'celular'=>$row['telefono'],
                  'correo'=>$row['correo']
                ]
              );
            }
        	} else {
            abort(406, "Por favor, verifica que la carrera de la linea $i corresponda con el cátalogo")->header('Content-Type', 'text/plain');
          }
        } else {
          abort(406, "Por favor, verifica que el sexo este representado con M para mujer y F para hombre en la linea $i.")->header('Content-Type', 'text/plain');
        }
      	$i++;
      }
      abort(406, "Total de registros actualizado: ".($i-2) )->header('Content-Type', 'text/plain');         
    }

}
