<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Foundation\Bus\DispatchesJobs;

use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\ItemStock;
use App\Models\StockHistory;
use App\ExpiryInventory;
use App\Maintenance\TextFile;
use App\ItemZeroStockDetails;
use App\Models\EndingInventory;
use Carbon\Carbon;
use DB;
use Log;

use App\Jobs\RecordEndingInventory;
use App\Jobs\DeleteExistingEndingInventory;

class ItemStockController extends Controller
{
    use DispatchesJobs;
    public function stocksstorebranch(Request $request)
    {
    	$data['selection'] = ItemStock::getCompaniesBranch($request);

        return \Response::json($data,200);
    }
    
       public function stocksstorecategory(Request $request)
    {
        try {
            $data['selection'] = ItemStock::getCompaniesBranchCategory($request);
            return \Response::json($data,200);
        }
        catch(Exception $e){
            return $e->getMessage();
        }
      
    }
    
    

    public function uploadInventory(Request $request)
    {
        $result = [];

        set_time_limit(0);

        if(!( is_array( $request->file('data') ) )) {
            $type = 'ENDING_INVENTORY';

            $result = $this->uploadInventoryCore($request->file('data'), $type);

        } else {
            foreach ($request->allFiles()['data'] as $file){
                $fileName = $file->getClientOriginalName();

                $type = 'ENDING_INVENTORY';

                $result[] = [
                    "File" => $fileName,
                    "Result" => $this->uploadInventoryCore($file, $type)
                ];
            }
        }

        return response()->json($result);
    }

    public function uploadInventoryCore($file, $type)
    {
        set_time_limit(0);
        //set_memory_limit(-1);
        ini_set('memory_limit',-1);
        
        $fileName = strtolower($file->getClientOriginalName());

        if (strlen($fileName) != 20) {
            return [
                'msg' => 'Invalid File Name Character Length, Must Follow format(0001000120001010.txt)',
                'status' => 1
            ];
        }

        $companyCode = substr($fileName, 0, 4);
        $branchCode = substr($fileName, 4, 4);

        $year = substr($fileName, 8, 4);
        $month = substr($fileName, 12, 2);
        $day = substr($fileName, 14, 2);
        $date = Carbon::parse($year . '-' . $month . '-' . $day)->toDateString();

        //$uploadsRoot = '/uploads/inventory/' . $companyCode . '/' . $branchCode . '/' . $year . '/' . $month;
        $uploadsRoot =  '/upload_ending_inventory/';
        $destinationPath = storage_path() . $uploadsRoot;

        if (!\File::exists($destinationPath)) {
            mkdir($destinationPath, 0755, true);
        }

        $isInventoryAlreadyExists = TextFile::where('unique_code', $type . $companyCode . $branchCode . $date)->first();

        $exists = !empty($isInventoryAlreadyExists);

        if ($exists == 1) {
            Log::info($exists);
            $resendPath = $destinationPath . 'resends';
            $uploadsRoot = $uploadsRoot . 'resends';
            $file->move($resendPath,"/" .$fileName);

            $filePath = $resendPath . "/" . $fileName;
            $uploadsRoot = $uploadsRoot . '/' . $fileName;
            $isInventoryAlreadyExists->resend_attempts += 1;
            $isInventoryAlreadyExists->last_resend_attempt_date = Carbon::now()->toDateTimeString();
            $isInventoryAlreadyExists->path = $filePath;
            $isInventoryAlreadyExists->uploads_root = $uploadsRoot;
            $isInventoryAlreadyExists->intended = false;
            $isInventoryAlreadyExists->intended_status = null;
            $isInventoryAlreadyExists->save();

            $params = [
                'type' => $type,
                'company_code' => $companyCode,
                'branch_code' => $branchCode,
                'date' => $date,
                'unique_code' => $type . $companyCode . $branchCode . $date
            ];

            // $jobExists = DB::table('jobs')
            //     ->where("payload","LIKE","%". $type . $companyCode . $branchCode . $date ."%")
            //     ->first();
            
            //  $deleteEndingInventory = EndingInventory::where('date', $date)
            // ->where('company_code', $companyCode)
            // ->where('branch_code', $companyCode.$branchCode)
            // ->delete();
            // // $dispatchDeleteEndingInventory = new DeleteExistingEndingInventory($params);
            // // $this->dispatch($dispatchDeleteEndingInventory);
            // // sleep(100);
           
            
            //if($deleteEndingInventory){
             //   $this->dispatchEndingInventory($params, strtolower($type));
            //}

            $resendLog = "ENDING INVENTORY RESENDED : " .
            "ENDING INVENTORY OF : " . $date . " | " .
            $companyCode .
            ' | ' . $branchCode .
            ' | RESENDED BY : ' . Carbon::now()->toDateTimeString();

            Log::info($resendLog);

            return [
                'msg' => $fileName . ' : Ending Inventory Already Exists',
                'status' => 1
            ];
        } else {
            Log::info($exists);
            try {
                $uploadInventoryTextFile = $file->move($destinationPath, $fileName);
                $filePath = $destinationPath . "/" . $fileName;
                $uploadsRoot = $uploadsRoot . "/" . $fileName;

                $textfile = new TextFile();
                $textfile->unique_code = $type . $companyCode . $branchCode . $date;
                $textfile->path = $filePath;
                $textfile->uploads_root = $uploadsRoot;
                $textfile->type = $type;
                $textfile->company_code = $companyCode;
                $textfile->branch_code = $branchCode;
                $textfile->file_name = $fileName;
                $textfile->date = $date;
                $textfile->save();

                $params = [
                    'type' => $type,
                    'company_code' => $companyCode,
                    'branch_code' => $branchCode,
                    'date' => $date,
                    'unique_code' => $type . $companyCode . $branchCode . $date
                ];

                $this->dispatchEndingInventory($params, strtolower($type));

                return array('msg' => 'file uploaded', 'status' => 0);

            } catch (Exception $e) {

                return array('msg' => 'file uploaded error', 'status' => 1);
            }
        }
    }

    public function dispatchEndingInventory($params, $queue = 'default')
    {
        $dispatchStatus = "ENDING INVENTORY DISPATCH SUCCESSFUL : " .
            "ENDING INVENTORY OF : " . $params['date'] . " | " .
            $params['company_code'] .
            ' | ' . $params['branch_code'] .
            ' | DISPATCHED BY : ' . Carbon::now()->toDateTimeString();

        Log::info($dispatchStatus);

       // $dispatchEndingInventory = (new RecordEndingInventory($params))->onQueue($queue);

        //$this->dispatch($dispatchEndingInventory);
       // $this->dispatchNow($dispatchEndingInventory);
    }
    
    public function uploadExpiryInventoryCore($file, $type){
        try{
            
            set_time_limit(0);

            $fileName = strtolower($file->getClientOriginalName());
    
            // if (strlen($fileName) != 20) {
            //     return [
            //         'msg' => 'Invalid File Name Character Length, Must Follow format(0001000120001010.txt)',
            //         'status' => 1
            //     ];
            // }
    
            $companyCode = substr($fileName, 0, 4);
            $branchCode = substr($fileName, 4, 4);
    
            $year = substr($fileName, 8, 4);
            $month = substr($fileName, 12, 2);
            $day = substr($fileName, 14, 2);
            $date = Carbon::parse($year . '-' . $month . '-' . $day)->toDateString();
    
            $uploadsRoot = '/uploads/expiry_inventory/' . $companyCode . '/' . $branchCode . '/' . $year . '/' . $month;
            $destinationPath = storage_path() . $uploadsRoot;
            
            if (!\File::exists($destinationPath)) {
                mkdir($destinationPath, 0755, true);
            }
            
            $isExpiryInventory = TextFile::where('unique_code', $type . $companyCode . $branchCode . $date)->first();
            $exists = !empty($isExpiryInventory);
            
            //dd( $isExpiryInventory); die;
        
                if ($exists) {
                    $resendPath = $destinationPath . '/resends';
                    $uploadsRoot = $uploadsRoot . '/resends';
                    $file->move($resendPath, $fileName);
        
                    $filePath = $resendPath . "/" . $fileName;
                    $uploadsRoot = $uploadsRoot . '/' . $fileName;
                    $isExpiryInventory->resend_attempts += 1;
                    $isExpiryInventory->last_resend_attempt_date = Carbon::now()->toDateTimeString();
                    $isExpiryInventory->path = $filePath;
                    $isExpiryInventory->uploads_root = $uploadsRoot;
                    $isExpiryInventory->intended = false;
                    $isExpiryInventory->intended_status = null;
                    $isExpiryInventory->save();
        
                    $params = [
                        'type' => $type,
                        'company_code' => $companyCode,
                        'branch_code' => $branchCode,
                        'date' => $date,
                        'unique_code' => $type . $companyCode . $branchCode . $date
                    ];
        
                    $deleteexisting = ExpiryInventory::where('textfilename',$fileName)->delete();
                    
                    $this->saveExpiryInventory($filePath,$params,$fileName);
                    
                    return [
                        'msg' => $fileName . ' : Ending Inventory Already Exists',
                        'status' => 1
                    ];
                } else {
                    try {
                        $uploadInventoryTextFile = $file->move($destinationPath, $fileName);
                        $filePath = $destinationPath . "/" . $fileName;
                        $uploadsRoot = $uploadsRoot . "/" . $fileName;
        
                        $textfile = new TextFile();
                        $textfile->unique_code = $type . $companyCode . $branchCode . $date;
                        $textfile->path = $filePath;
                        $textfile->uploads_root = $uploadsRoot;
                        $textfile->type = $type;
                        $textfile->company_code = $companyCode;
                        $textfile->branch_code = $branchCode;
                        $textfile->file_name = $fileName;
                        $textfile->date = $date;
                        $textfile->save();
        
                        $params = [
                            'type' => $type,
                            'company_code' => $companyCode,
                            'branch_code' => $branchCode,
                            'date' => $date,
                            'unique_code' => $type . $companyCode . $branchCode . $date
                        ];
                        
                        $this->saveExpiryInventory($filePath,$params,$fileName);
        
                        return array('msg' => 'file uploaded', 'status' => 0);
        
                    } catch (Exception $e) {
        
                        return array('msg' => 'file uploaded error', 'status' => 1);
                    }
                }
                
        }
        catch(Exception $e){
             return array('msg' => 'file uploaded error:'.$e->getMessage(), 'status' => 1);
        }
    }
    
    public function uploadExpiryInventory(Request $request){
        
        $result = [];

        set_time_limit(0);

        if(!( is_array( $request->file('data') ) )) {
            $type = 'EXPIRY_INVENTORY';
            $result = $this->uploadExpiryInventoryCore($request->file('data'), $type);
        } else {
            foreach ($request->allFiles()['data'] as $file){
                $fileName = $file->getClientOriginalName();

                $type = 'EXPIRY_INVENTORY';

                $result[] = [
                    "File" => $fileName,
                    "Result" => $this->uploadExpiryInventoryCore($file, $type)
                ];
            }
        }

        return response()->json($result);
        
    }
    
    public function saveExpiryInventory($path,$params,$fileName){
        
        $row_data = [];
        $reader = ReaderFactory::create(Type::CSV);
        $reader->setFieldDelimiter('|');
        $reader->open($path);
        
        foreach ($reader->getSheetIterator() as $sheet) {
            foreach ($sheet->getRowIterator() as $row) {
                
                 $row_data [] = [
                        'compcode'=>trim($params['company_code']),
                        'Gcompany'=>trim($row[1]),
                        'pnlocation'=>trim($params['company_code'].$params['branch_code']),
                        'lclocation'=>trim($row[3]),
                        'lddate'=>Carbon::parse(trim($row[4]))->toDateString(),
                        'barcode'=>trim($row[5]),
                        'desc'=>trim($row[6]),
                        'qty'=>trim($row[7]),
                        'lcexpirydate'=>Carbon::parse(trim($row[8]))->toDateString(),
                        'textfilename'=>$fileName,
                        'created_at'=>Carbon::now()->toDayDateTimeString(),
                        'updated_at'=>Carbon::now()->toDayDateTimeString()
                    ];
            }
        }
        
        //dd($row_data);die;
        
        $expinventory = ExpiryInventory::insert($row_data);
    }
    
    public function uploadItemZeroStock(Request $request){
        
        $result = [];
        set_time_limit(0);

        if(!( is_array( $request->file('data') ) )) {
            $type = 'ITEM_ZERO_STOCK';

            $result = $this->uploadZeroStockCore($request->file('data'), $type);

        } else {
            foreach ($request->allFiles()['data'] as $file){
                $fileName = $file->getClientOriginalName();

                $type = 'ITEM_ZERO_STOCK';

                $result[] = [
                    "File" => $fileName,
                    "Result" => $this->uploadZeroStockCore($file, $type)
                ];
            }
        }

        return response()->json($result);
    }
    
     public function uploadZeroStockCore($file, $type)
    {
        set_time_limit(0);

        $fileName = strtolower($file->getClientOriginalName());
       
        if (strlen($fileName) != 16) {
            return [
                'msg' => 'Invalid File Name Character Length, Must Follow format(000220200810.txt)',
                'status' => 1
            ];
        }

        $companyCode = substr($fileName, 0, 4);
        $branchCode = substr($fileName, 4, 4);

        $year = substr($fileName, 4, 4);
        $month = substr($fileName, 8, 2);
        $day = substr($fileName, 10, 2);
        $date = Carbon::parse($year . '-' . $month . '-' . $day)->toDateString();
        
     

        $uploadsRoot = '/uploads/itemzerostock/' . $companyCode . '/' . $year . '/' . $month;
        $destinationPath = storage_path() . $uploadsRoot;

        if (!\File::exists($destinationPath)) {
            mkdir($destinationPath, 0755, true);
        }

        $isItemAlreadyExists = TextFile::where('unique_code', $type . $companyCode  . $date)->first();

        $exists = !empty($isItemAlreadyExists);

        if ($exists) {
            $resendPath = $destinationPath . '/resends';
            $uploadsRoot = $uploadsRoot . '/resends';
            $file->move($resendPath, $fileName);

            $filePath = $resendPath . "/" . $fileName;
            $uploadsRoot = $uploadsRoot . '/' . $fileName;
            $isItemAlreadyExists->resend_attempts += 1;
            $isItemAlreadyExists->last_resend_attempt_date = Carbon::now()->toDateTimeString();
            $isItemAlreadyExists->path = $filePath;
            $isItemAlreadyExists->uploads_root = $uploadsRoot;
            $isItemAlreadyExists->intended = false;
            $isItemAlreadyExists->intended_status = null;
            $isItemAlreadyExists->save();

            $params = [
                'type' => $type,
                'company_code' => $companyCode,
                'branch_code' => '',
                'date' => $date,
                'unique_code' => $type . $companyCode  . $date
            ];
            
            //$deleteexisting = ItemZeroStockDetails::where('uniqe_file_name',$fileName)->delete();
            
            $this->saveItemZeroStock($filePath,$params,$fileName);

            return [
                'msg' => $fileName . ' : Zero Item Already Exists',
                'status' => 1
            ];
        } else {
            try {
                $uploadInventoryTextFile = $file->move($destinationPath, $fileName);
                $filePath = $destinationPath . "/" . $fileName;
                $uploadsRoot = $uploadsRoot . "/" . $fileName;

                $textfile = new TextFile();
                $textfile->unique_code = $type . $companyCode  . $date;
                $textfile->path = $filePath;
                $textfile->uploads_root = $uploadsRoot;
                $textfile->type = $type;
                $textfile->company_code = $companyCode;
                $textfile->branch_code = '';
                $textfile->file_name = $fileName;
                $textfile->date = $date;
                $textfile->save();

                $params = [
                    'type' => $type,
                    'company_code' => $companyCode,
                    'branch_code' => '',
                    'date' => $date,
                    'unique_code' => $type . $companyCode  . $date
                ];
                
                $this->saveItemZeroStock($filePath,$params,$fileName);

                return array('msg' => 'file uploaded', 'status' => 0);

            } catch (Exception $e) {

                return array('msg' => 'file uploaded error', 'status' => 1);
            }
        }
    }
    
     public function saveItemZeroStock($path,$params,$fileName){
        
        $row_data = [];
        $reader = ReaderFactory::create(Type::CSV);
        $reader->setFieldDelimiter('|');
        $reader->open($path);
        
        foreach ($reader->getSheetIterator() as $sheet) {
            foreach ($sheet->getRowIterator() as $row) {
                 
                $ccode = utf8_encode(trim($row[0]));
                $companyCode = $ccode;
                $dval = 4;
                $addz = "0";
                
                if(strlen($ccode) <= 3){
                    $companyCode = '';
                    $tempv = $dval - strlen($ccode);
                    for($i = 0; $i < $tempv; $i ++){
                       $companyCode .= $addz;
                    }
                    $companyCode = $companyCode.$ccode;
                }
                
                $bcode = utf8_encode(trim($row[2]));
                $branchCode = $bcode;
                        
                if(strlen($bcode) <= 3){
                    $branchCode = '';
                    $btempv = $dval - strlen($bcode);
                    for($i = 0; $i < $btempv; $i ++){
                       $branchCode .= $addz;
                    }
                    $branchCode = $branchCode.$bcode;
                }
                
                $exst = ItemZeroStockDetails::where('branch_code',$companyCode.$branchCode)
                ->where('barcode',utf8_encode(trim($row[5])))
                ->where('local_date',Carbon::parse(trim(utf8_encode($row[4])))->toDateString())
                ->get();
                
                if(count($exst) <= 0 || empty($exst)){
                    $row_data [] = [
                        'company_code'=>$companyCode,
                        'company_name'=>utf8_encode(trim($row[1])),
                        'branch_code'=>$companyCode.$branchCode,
                        'branch_name'=>utf8_encode(trim($row[3])),
                        'local_date'=>Carbon::parse(trim(utf8_encode($row[4])))->toDateString(),
                        'barcode'=>utf8_encode(trim($row[5])),
                        'item_description'=>utf8_encode(trim($row[6])),
                        'min'=>utf8_encode(trim($row[7])),
                        'max'=>utf8_encode(trim($row[8])),
                        'stock'=>utf8_encode(trim($row[9])),
                        'uniqe_file_name'=>$fileName,
                        'created_at'=>Carbon::now()->toDayDateTimeString(),
                        'updated_at'=>Carbon::now()->toDayDateTimeString()
                    ];
                }
                
                
            }
        }
        
        //dd($row_data);die;
        
        $itemzero = ItemZeroStockDetails::insert($row_data);
    }
}