<?php

namespace App\Classes\Modules\Bookings\Services;

use App\Classes\Exceptions\MalformedRequestException;
use App\Models\File;
use Exception;
use Illuminate\Support\Facades\Storage;

class Convert1688PurchaseOrderToProductList
{
    /**
     * @param File $file
     * @return array
     * @throws MalformedRequestException
     */
    public function execute(File $file): array
    {
        $parser = new \Smalot\PdfParser\Parser();
        $productList = [];
        $shipping = 0;
        $discount = 0;

        try {
            $pdf = $parser->parseFile(Storage::disk('documents')->path($file->file->file_info->original->file));
        } catch (Exception $exception) {
            throw new MalformedRequestException('Invalid file format.');
        }

        $text = $pdf->getText();
        if(str_contains($text, '订单详情单')) throw new MalformedRequestException('Can\'t process non english documents');

        $tables = explode('Amount (yuan)', $text);
        $footer = end($tables);
        $footer = preg_split('(Shipping|运费)', $footer);
        if(array_key_exists(1, $footer)){
            $footer = preg_split('/[\t\n]/', $footer[1]);
            $shipping = (float) filter_var( $footer[0], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
            $discount = array_filter($footer, function($var) { return preg_match("/(Discount|优惠)/", $var); });
            $discount = (float) filter_var(reset($discount), FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
        }


        array_shift($tables);

        foreach ($tables as $table){
            $products = preg_split('/(yuan\/|yuan \/|元\/|元 \/)/', str_replace("\r\n","",$table));

            array_pop($products);
            foreach ($products as $product){
                $product = preg_split('/[\t]/',$product);

                $adjuster = (count($product) - 7);
                $descriptionIndex = 3 + $adjuster;

                $quantity = (int) str_replace("\n","",$product[$descriptionIndex + 2]);
                $unitPrice = (float) str_replace("\n","",$product[$descriptionIndex + 3]);

                $productList[] = [
                    'stockCode' => '',
                    'description' => str_replace("\n","",$product[$descriptionIndex]),
                    'quantity' =>  $quantity,
                    'unit_price' =>  $unitPrice,
                    'total' =>  (float) str_replace("\n","",$product[$descriptionIndex + 3])
                ];
            }
        }

        if($shipping > 0) {
            $productList[] = [
                'stockCode' => '',
                'description' => 'Shipping Fee',
                'quantity' =>  1,
                'unit_price' =>  $shipping,
                'total' => $shipping
            ];
        }

        if($discount > 0) {
            $productList[] = [
                'stockCode' => '',
                'description' => 'Discount',
                'quantity' =>  1,
                'unit_price' =>  $discount * -1,
                'total' => $discount * -1
            ];
        }

        return $productList;
    }
}
