<?php

namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use App\Models\Student;
use Log;

class StudentImport implements ToCollection, WithHeadingRow, WithChunkReading
{    

    public function  __construct($grade_id = null, $section_id=null, $campus_id)
    {
        $this->grade_id= $grade_id;
        $this->section_id= $section_id;
        $this->campus_id= $campus_id;
    }

    /**
     * collection
     *
     * @param  mixed $rows
     * @return void
     */
    public function collection(Collection $rows)
    {
        foreach ($rows as $row){
            $names = self::_split_name($row['first_name']);
            
            Log::debug("DOB", [$row['roll_number']]);

            $student = new Student();
            $student->number = $row['roll_number'] ?? '';
            $student->first_name = $names[0] ?? '';
            $student->last_name = $names[1] ?? '';
            $student->code  = self::_get_student_code();
            $student->address = $row['address'];
            $student->email = $row['row'] ?? '';   
            $student->gender = strtolower($row['gender']) == 'female' ? 'FEMALE' : 'MALE';
            $student->cnic = $row['b_form'];  
            $student->campus_id = $this->campus_id;
            $student->section_id = $this->section_id;
            $student->grade_id = $this->grade_id;
            $student->guardian_name = $row['father_name'];        
            $contacts = [];
            if(isset($row['primary_contact']) && $row['primary_contact'] != null){
                $contacts['primary'] = "+92-".ltrim(str_replace("-", "", $row['primary_contact']), "0");
            }
            if(isset($row['secondary_contact']) && $row['secondary_contact'] != null){
                $contacts['secondary'] = "+92-".ltrim(str_replace("-", "", $row['secondary_contact']), "0");
            }
            $student->contacts = $contacts;    
            if(isset($row['admission_date']) && $row['admission_date'] != null ){
                $student->admission_date = date('Y-m-d', strtotime(self::_excel_date($row['admission_date'])));
            }
            if(isset($row['admission_date']) && $row['date_of_birth'] != null ){
                $student->dob = date('Y-m-d', strtotime(self::_excel_date($row['date_of_birth'])));                
            }

            $fees = [];
            if(isset($row['admission_fee'])){
                $fees[] = [
                    'type' => 'Admission Fee',
                    'amount' => floatval($row['admission_fee'] ?? "0")
                ];
            }
            if(isset($row['tuition_fee'])){
                $fees[] = [
                    'type' => 'Tuition Fee',
                    'amount' => floatval($row['tuition_fee'] ?? "0")
                ];
            }
            if(isset($row['annual_charges'])){
                $fees[] = [
                    'type' => 'Annual Charges',
                    'amount' => floatval($row['annual_charges'] ?? "0")
                ];
            }
            $student->fees = $fees;        

            $student->save();
            
            


        }
    }

    public function chunkSize(): int
    {
        return 500;
    }
    
    /**
     * _split_name
     *
     * @param  mixed $name
     * @return void
     */
    public function _split_name($name) {
        $name = trim($name);
        $last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
        $first_name = trim( preg_replace('#'.preg_quote($last_name,'#').'#', '', $name ) );
        return array($first_name, $last_name);
    }

    public  function _get_student_code(){
                
        $id_prefix = 'AHE-'.date('y');
        $old_id = Student::where('code', 'like', '%'.$id_prefix.'%')->orderBy('id', 'DESC')->limit(1)->first();
        if($old_id){
            $previous_id = substr($old_id->code, -4);
            $new_id = ++$previous_id;      
            $new_id = sprintf("%04d", $new_id);
        }else{
            $new_id = "0001";      
        } 

        return $id_prefix.$new_id;
        
    }  

    public function _excel_date($excel_time) {

        $new_date =  \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($excel_time)->format('Y-m-d');
        return $new_date;
    }
}
