<?php

namespace App\Http\Controllers\Inventory;

use App\Group;
use App\Product;
use App\ProductUnit;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class FileUploadController extends Controller
{
    public function index(){
        return view('inventory.excel');
    }

    public function store(Request $request){

        $fileName = substr(md5(time()),0,6).'.'.$request->file('excel')->getClientOriginalExtension();
        $request->file('excel')->move(base_path('public/upload/'),$fileName);
        $path = asset('upload/'.$fileName);
        $file_lines = file($path);
        $row  = count($file_lines);


        $tr='';

        for ($sl=0;$sl<=$row;$sl++){
            $print = $row-$sl;
            if($print !=0){
                $slice = ($sl !=0 ? $sl : 1);

                $x = explode(',', $file_lines[$slice]);
                $product['name'] = $x[0];
                $product['item_code'] = $x[1];

                /* Create new Group Or Get Created Group ID*/
                $group = Group::updateOrCreate(['name'=>$x[2]]);

                $unit = ProductUnit::updateOrCreate(['name'=>$x[3]]);

                $product['group_id'] = $group->id;
                $product['product_unit_id'] = $unit->id;

                /* already exit or not */

                $exit = Product::where('name',$x[0])->where('item_code',$x[1])->where('group_id',$group->id)->where('product_unit_id',$unit->id)->get()->count();

                if ($exit>0){
                    echo "<h3 style='background: #DD5145;color: #fff; padding: 5px 10px; margin-bottom: 5px;'>Sl No : ".$sl." -- Name : ".$product['name'].'-- Item Code :'.$x[1]." -- Group Name : ".$x[2]." -- Unit Name : ".$x[3]."</h3>";
                }
                else{
                    if (!empty($x[0] && !empty($x[1]))){
                        Product::create($product);
                        echo "<h3 style='background: #129C56;color: #fff; padding: 5px 10px; margin-bottom: 5px;'>Sl No : ".$sl." -- Name : ".$product['name'].'-- Item Code :'.$x[1]." -- Group Name : ".$x[2]." -- Unit Name : ".$x[3]."</h3>";
                    }else{
                        echo '<h3 style="background: yellowgreen;color: #fff3cd;">Name : '.$x[0].' -- Item Code : '.$x[1].'</h3>';
                    }

                }
            }
        }

        echo '<h1>'.$row.'</h1>';
    }
}
