<?php

namespace Tobuli\Importers\Task\Readers;

use Maatwebsite\Excel\Facades\Excel;
use Tobuli\Importers\Readers\XlsReader;
use Validator;

class TaskXlsReader extends XlsReader
{
    public function isValidFormat($file)
    {
        if (!parent::isValidFormat($file)) {
            return false;
        }

        $headerRow = null;
        $rules = [
            'title' => 'required',
            'user_id' => 'required_without:email',
            'email' => 'required_without:user_id',
            'device_id' => 'required_without:imei',
            'imei' => 'required_without:device_id',
            'priority' => 'required',
            'pickup_address_lat' => 'required',
            'pickup_address_lng' => 'required',
            'pickup_time_from' => 'required',
            'pickup_time_to' => 'required',
            'delivery_address_lat' => 'required',
            'delivery_address_lng' => 'required',
            'delivery_time_from' => 'required',
            'delivery_time_to' => 'required',
        ];

        try {
            Excel::load($file, function($reader) use (&$headerRow) {
                $headerRow = $reader->first()->keys()->toArray();
            });
        } catch(\PHPExcel_Reader_Exception $e) {
            return false;
        }

        if (!$headerRow) {
            return false;
        }

        if (!is_array($headerRow) || !array_filter($headerRow)) {
            return false;
        }

        $validator = Validator::make(array_flip($headerRow), $rules);

        if ($validator->fails()) {
            return false;
        }

        return true;
    }
}
