<?php

namespace App\Repositories;

use App\Models\Country;
use App\Models\ShoppingUser;
use Validator;
use Response;
use Excel;
use Storage;
use App\Models\Import;


class ImportRepository extends BaseRepository {


    public function __construct(){
    }

    public function upload( $form_data )
    {

        $validator = Validator::make($form_data, Import::$rules, Import::$messages);

        if ($validator->fails()) {

            return Response::json([
                'error' => true,
                'message' => $validator->messages()->first(),
                'code' => 400
            ], 400);

        }
        $file = $form_data['file'];

        $originalName = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $originalNameWithoutExt = substr($originalName, 0, strlen($originalName) - strlen($extension) - 1);

        $filename = $this->sanitize($originalNameWithoutExt);
        $allowed_filename = $filename.".".$extension;

        Storage::disk('import')->put($allowed_filename, file_get_contents($file->getRealPath()));


        return Response::json([
            'error' => false,
            'filename' => $allowed_filename,
            'filedata' => 'xls',
            'redirect' => url(route('sysadmin_import_show', ['xls', $allowed_filename])),
            'code'  => 200
        ], 200);
    }

    public function read($type, $file, $skip, $limit)
    {

        if(!Storage::disk('import')->has($file)){
            return false;
        }
        return $this->import(storage_path("app/import/").$file, $file, $skip, $limit);


    }

    protected function import($file_path, $file,  $skip, $limit){

        $salutation = array(1 => 'mr', 2 => 'ms', 3=>null);

        $ret = [
            'count' => 0,
            'not' => 0,
            'imported' => [],
            'has_imported' => [],
        ];
        /*
            * wp_order_number
               wp_order_date
               billing_company
               billing_salutation
               billing_firstname
               billing_lastname
               billing_address
               billing_address_2
               billing_zipcode
               billing_city
               billing_country_code
               billing_country
               billing_email
               billing_phone
               shipping_salutation
               shipping_company
               shipping_firstname
               shipping_lastname
               shipping_address
               shipping_address_2
               shipping_zipcode
               shipping_city
               shipping_country_code
               shipping_country
           */


        $rows = Excel::toArray(new \App\Imports\ImportCollection(), $file_path);

        foreach ($rows[0] as $row){
            $ret['count']++;
            if(isset($row['billing_email'])){
                if(ShoppingUser::where('billing_email', '=', $row['billing_email'])->count() > 0){
                    $ssuser = ShoppingUser::where('billing_email', '=', $row['billing_email'])->first();
                    if($ssuser->member_id){
                        $ret['has_imported'][] = $row['billing_email']." - ".$ssuser->member->email;
                        continue;
                    }
                }
                $row['billing_salutation'] = $salutation[$row['billing_salutation']];
                $row['billing_country_id'] = Country::getCountryIdByCodeOrOne($row['billing_country_code']);
                $row['billing_phone'] = strlen($row['billing_phone']) <= 3 ? '' : $row['billing_phone'];
                $row['same_as_billing'] = true;
                if(isset($row['shipping_salutation']) && $row['shipping_salutation'] > 0){
                    $row['shipping_salutation'] = $salutation[$row['shipping_salutation']];
                    $row['shipping_country_id'] = Country::getCountryIdByCodeOrOne($row['shipping_country_code']);
                    $row['same_as_billing'] = false;
                }
                $row['member_id'] = 3;
                $row['number'] = ShoppingUser::max('number') + 1;
                $row['has_buyed'] = true;
                $row['subscribed'] = false;
                $ret['imported'][] = $row['billing_email'];

                ShoppingUser::create($row);
            }else{
               $ret['not']++;
            }

        }
        return $ret;
    }

    public function sanitize($string, $force_lowercase = true, $anal = false)
    {
        $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
            "}", "\\", "|", ";", ":", "\"", "'", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8211;", "&#8212;",
            "â€”", "â€“", ",", "<", ".", ">", "/", "?");
        $clean = trim(str_replace($strip, "", strip_tags($string)));
        $clean = preg_replace('/\s+/', "-", $clean);
        $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;

        return ($force_lowercase) ?
            (function_exists('mb_strtolower')) ?
                mb_strtolower($clean, 'UTF-8') :
                strtolower($clean) :
            $clean;
    }

}