<?php
/**
 * Created by PhpStorm.
 * User: sunil
 * Date: 10/26/18
 * Time: 4:50 PM
 */

namespace App;

use App\Imports\RBLNachImports;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class Mailer
{
    private $connection;
    private $subject;

    public function __construct(Nach $nach){
        $this->nach = $nach;
        $this->connection();
    }

    public function connection(){
        $this->connection = imap_open(
            '{imap.gmail.com:993/imap/ssl}',
            'sunil@creditfair.in',
            'Jayshree958',
            '0',
            '3',
            []
        );
    }

    public function subject($subject){
        $this->subject = 'SUBJECT "'.$subject.'"';
        return $this;
    }

    public function getOutput(){

        $emails = imap_search($this->connection,$this->subject);
        $attributes = [];

        if($emails) {

            rsort($emails);

            foreach($emails as $email_number) {

                $structure = imap_fetchstructure($this->connection,$email_number);
                $overview = imap_fetch_overview($this->connection,$email_number,0);
                $filePaths = $this->saveAttachment($structure, $email_number);
                $attributes[] = [
                    'subject' => $overview[0]->subject,
                    'from' => $overview[0]->from,
                    'attachments' => $filePaths,
                ];


            }
        }


        imap_close($this->connection);
        $this->updateRegisteredMandates($attributes);
        return $attributes;
    }

    public function updateRegisteredMandates($attributes){
        $import = (new RBLNachImports(new Request()));
        foreach($attributes as $attribute) {
            foreach ($attribute['attachments'] as $file){
                $data = $import->toArray($file, 'local', $this->getExtension($file));
                $import->model($data);
            }
        }
    }

    public function getExtension($file){
        $extension = ucfirst(strtolower(explode('.',$file)[1]));
        switch ($extension){
            case \Maatwebsite\Excel\Excel::XLSX:
                return \Maatwebsite\Excel\Excel::XLSX;
                break;
            case \Maatwebsite\Excel\Excel::XLS:
                return \Maatwebsite\Excel\Excel::XLS;
                break;
            default:
                return \Maatwebsite\Excel\Excel::XLSX;
                break;
        }
    }

    public function saveAttachment($structure, $email_number){
        $attachments = array();
        if(isset($structure->parts) && count($structure->parts)) {
            for($i = 0; $i < count($structure->parts); $i++) {
                $attachments[$i] = array(
                    'is_attachment' => false,
                    'filename' => '',
                    'name' => '',
                    'attachment' => '');

                if($structure->parts[$i]->ifdparameters) {
                    foreach($structure->parts[$i]->dparameters as $object) {
                        if(strtolower($object->attribute) == 'filename') {
                            if ($this->strposa($object->value, ['.xlsx','.xls']) === false) {
                                return true;
                            }
                            $attachments[$i]['filename'] = $object->value;
                            $attachments[$i]['is_attachment'] = true;
                        }
                    }
                }

                if($structure->parts[$i]->ifparameters) {
                    foreach($structure->parts[$i]->parameters as $object) {
                        if(strtolower($object->attribute) == 'name') {
                            $attachments[$i]['is_attachment'] = true;
                            $attachments[$i]['name'] = $object->value;
                        }
                    }
                }

                if($attachments[$i]['is_attachment']) {
                    $attachments[$i]['attachment'] = imap_fetchbody($this->connection, $email_number, $i+1);
                    if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
                        $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                    }
                    elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
                        $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                    }
                }
            }
        }

        $filePaths = [];
        if(count($attachments)!=0){
            foreach($attachments as $at){
                if($at['is_attachment']==1){
                    $filePath = 'nach/'.strtolower(str_replace("\\", '', $this->nach->nach()['name'])).'/'.time().'_'.$at['filename'];
                    file_put_contents(storage_path().'/app/'.$filePath, $at['attachment']);
                    $filePaths[] = $filePath;
                }
            }
        }

        return $filePaths;
    }

    public function strposa($haystack, $needles=array(), $offset=0) {
        $chr = array();
        foreach($needles as $needle) {
            $res = strpos($haystack, $needle, $offset);
            if ($res !== false) $chr[$needle] = $res;
        }
        if(empty($chr)) return false;
        return min($chr);
    }
}