<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Location;
use App\LocationProduct;
use App\CategoryMaster;
use App\Product;
use App\ProductStandard;
use App\ProductGrade;
use App\GradeMaster;
use App\StandardMaster;
use App\SubLocation;
use ZipArchive;
use App\ProductUnit;
use App\Office;
use App\HsnCode;
use Auth;
use App\Customer;
use App\CustomerProduct;

class LocationMasterController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }
    
	public function index()
	{	
		$location = Location::all();
		if(Auth::user()->location_id != null)
		{
			$location = Location::where('id','=',Auth::user()->location_id)->get();
		}

		return view('location/index',compact('location'));
	}

	public function store(Request $request)
	{
		if($request->get('loc_id') != ''){

			$exist = Location::where('location','=',strtoupper(trim($request->get('location'))))
							 ->where('id','!=',$request->get('loc_id'))
							 ->count();
			
			if($exist != 0){
				return redirect()->route('location.master')->with(['exist' => true]);
			}

			$update = Location::where('id','=',$request->get('loc_id'))
							  ->update([
										 'location'  => strtoupper(trim($request->get('location'))),
										 'is_active' => ($request->get('active')) ? 'Y' : 'N'
									 ]);
			return redirect()->route('location.master')->with(['update' => true]);
		}
		else{
			$exist = Location::where('location','=',strtoupper(trim($request->get('location'))))->count();
			
			if($exist != 0){
				return redirect()->route('location.master')->with(['exist' => true]);
			}

			$insert = Location::create([
										  'location'  => strtoupper(trim($request->get('location'))),
										  'is_active' => ($request->get('active')) ? 'Y' : 'N'
									 ]);
			return redirect()->route('location.master')->with(['message' => true]);
		}
	}

	public function edit(Request $request)
	{
		$id 	  = $request->get('option');
		$location = Location::find($id);

		return $location;
	}


	public function mapProduct($id)
	{
		$categories = CategoryMaster::orderBy('category')->get();
		$products   = NULL;
		$location_id = $id;
		$locationProducts = LocationProduct::where('location_id','=',$location_id)->pluck('product_id')->toArray();
		$selctCat  = NULL;
		return view('location/map_product',compact('categories','products','location_id','locationProducts','selctCat'));
	}

	public function mapShow(Request $request)
	{
		$locationProducts  = LocationProduct::where('location_id','=',$request->get('location_id'))
                                    ->pluck('product_id')->toArray(); 
        $location_id = $request->get('location_id');  
        $categories = CategoryMaster::orderBy('category')->get();
        $products   = Product::where('category_id','=',$request->get('category'))
                             ->orderBy('name')->get();
        foreach($products as $prd){
        	$stnds[$prd->id] = ProductStandard::where('product_id','=',$prd->id)->get();
        	// $grades[$prd->id] = ProductGrade::where('product_id','=',$prd->id)->get();
        }
        $selctCat   = $request->get('category');
        $loc_prd_obj = new LocationProduct();
		return view('location/map_product',compact('categories','products','location_id','locationProducts','selctCat','stnds','loc_prd_obj'));
	}

	public function locationAddProduct(Request $request)
	{
		$product = LocationProduct::create(array('location_id'  => $request->get('option'),
       	                                        'product_id'   => $request->get('option1')));

		return $product;
	}

	public function locationDeleteProduct(Request $request)
	{
		$product = LocationProduct::where('location_id','=',$request->get('option'))
	                             ->where('product_id','=',$request->get('option1'))->delete();
       	return $product;	
	}

	public function productinLocation($id)
	{
		$products = LocationProduct::where('location_id','=',$id)->get();
		$location = Location::find($id)->location;
		
		return view('location/location_products',compact('location','products'));
	}
	
	public function getStandrd(Request $request)
	{
		$stnds = ProductStandard::join('standard_master','standard_master.id','=','product_standard.standard_id')
						->join('grade_master','grade_master.id','=','product_standard.grade_id')
						->where('product_standard.product_id','=',$request->get('prd'))
						->where('standard_master.is_active','=','Y')
						->where('grade_master.is_active','=','Y')
						->selectRaw('standard_master.id as sid, grade_master.id as gid, standard_master.standard, grade_master.grade,product_standard.id')
						->get();
		

		$prd = Product::find($request->get('prd'))->name;

		$exist = LocationProduct::where('location_id','=',$request->get('location_id'))
								->where('product_id','=',$request->get('prd'))
								->selectRaw('grade_id,standard_id')
								->get();

		$data = array($stnds,$prd,$exist);
		return $data;
	}

	public function getLocGrades(Request $request)
	{

		$exist = LocationProduct::join('grade_master','grade_master.id','=','location_products.grade_id')
						->join('standard_master','standard_master.id','=','location_products.standard_id')
						->where('location_products.location_id','=',$request->get('location_id'))
						->where('location_products.product_id','=',$request->get('product'))
						->selectRaw('standard_master.standard,grade_master.grade')->get();
						$data='';
		foreach ($exist as $value) {
			$data.= $value->standard.'-'.$value->grade.';';
		}
		// $grades = GradeMaster::whereIN('id',$exist)->pluck('grade')->toArray();
		// $rev = array_reverse($grades);
		return $data;
	}

	public function addGrade(Request $request)
	{
		$product_id = $request->get('product');
		$location_id = $request->get('location_id');
		$p_std = $request->get('p_std');
		$product_stand = ProductStandard::find($p_std);
		$insert = LocationProduct::create([
											'location_id' => $location_id,
											'product_id' => $product_id,
											'grade_id' => $product_stand->grade_id,
											'standard_id' => $product_stand->standard_id,
										]);
		return $location_id;
	}

	public function updateGrade(Request $request)
	{
		$product_id = $request->get('product');
		$location_id = $request->get('location_id');
		$p_std = $request->get('p_std');
		$product_stand = ProductStandard::find($p_std);
        
        $sup_pdt_id = LocationProduct::where('location_id','=',$location_id)
					                 ->where('product_id','=',$product_id)
									->where('grade_id','=',$product_stand->grade_id)
									->where('standard_id','=',$product_stand->standard_id)->first();
								
		$update = LocationProduct::where('location_id','=',$location_id)
					->where('product_id','=',$product_id)
					->where('grade_id','=',$product_stand->grade_id)
					->where('standard_id','=',$product_stand->standard_id)
					->delete();
		return $location_id;
	}

	public function subLoactions($location_id)
	{
		$location = Location::find($location_id);
		$sub_locations = SubLocation::where('location_id','=',$location_id)->get();
		return view('location/sub_lcoations',compact('sub_locations','location'));
	}

	public function subLocationInsert(Request $request,$location_id)
	{
		if($request->get('loc_id') != ''){

			$exist = SubLocation::where('sub_location','=',strtoupper(trim($request->get('sub_lcoation'))))
							 ->where('id','!=',$request->get('loc_id'))
							 ->count();
			
			if($exist != 0){
				return redirect()->route('sub.locations',$location_id)->with(['exist' => true]);
			}

			$update = SubLocation::where('id','=',$request->get('loc_id'))
							  ->update([
										 'sub_location'  => strtoupper(trim($request->get('sub_location'))),
										 'location_id'  => $location_id,
										 'is_active' => ($request->get('active')) ? 'Y' : 'N'
									 ]);
			return redirect()->route('sub.locations',$location_id)->with(['update' => true]);
		}
		else{
			$exist = SubLocation::where('sub_location','=',strtoupper(trim($request->get('sub_location'))))->count();
			
			if($exist != 0){
				return redirect()->route('sub.locations',$location_id)->with(['exist' => true]);
			}

			$insert = SubLocation::create([
										  'sub_location'  => strtoupper(trim($request->get('sub_location'))),
										  'location_id'  => $location_id,
										  'is_active' => ($request->get('active')) ? 'Y' : 'N'
									 ]);
			return redirect()->route('sub.locations',$location_id)->with(['message' => true]);
		}
	}

	public function editSubLocation(Request $request)
	{
		$id 	  = $request->get('option');
		$location = SubLocation::find($id);

		return $location;
	}

	public function createLocation()
	{
		return view('location/create');
	}
	public function editLocation($id)
	{
		
		$location = Location::find($id);


		return view('location/edit',compact('location'));
	}
	public function storeLocation(Request $request)
	{
		$exist = Location::where('location','=',strtoupper(trim($request->get('location'))))
							 ->count();
			
			if($exist != 0){
				return redirect()->route('location.master')->with(['exist' => true]);
			}


		Location::create([
			'location' 		=>$request->get('location'),
			'company_name'	=>$request->get('company_name'),
			'address_one'	=>$request->get('address_one'),
			'address_two'	=>$request->get('address_two'),
			'email'			=>$request->get('email'),
			'phone_no'		=>$request->get('phone_no'),
			'vatin_no'		=>$request->get('vatin_no'),
			'prefix'		=>$request->get('prefix'),
			'is_active'		=> ($request->get('Isactive')) ? 'Y' : 'N',
			'tax_perc'		=> $request->get('tax_perc')
		]);


		return redirect()->route('location.master')->with(['message' => true]);
	}
	public function updateLocation(Request $request)
	{
		$exist = Location::where('location','=',strtoupper(trim($request->get('location'))))
							 ->where('id','!=',$request->get('loc_id'))
							 ->count();
			
			if($exist != 0){
				return redirect()->route('location.master')->with(['exist' => true]);
			}

			$update = Location::where('id','=',$request->get('loc_id'))
							  ->update([
									'location' 		=>$request->get('location'),
									'company_name'	=>$request->get('company_name'),
									'address_one'	=>$request->get('address_one'),
									'address_two'	=>$request->get('address_two'),
									'email'			=>$request->get('email'),
									'phone_no'		=>$request->get('phone_no'),
									'vatin_no'		=>$request->get('vatin_no'),
									'prefix'		=>$request->get('prefix'),
									'is_active'		=> ($request->get('Isactive')) ? 'Y' : 'N',
									'tax_perc'		=> $request->get('tax_perc')
									 ]);
			return redirect()->route('location.master')->with(['update' => true]);
	}
	public function generateZip($id)
	{
    	$location = Location::where('id','=',$id)->first()->location;
        $location_tax = Location::where('id','=',$id)->first()->tax_perc;
    	$zip = new ZipArchive;
        $file_zip = "productnew1.zip";
        $file_name = "productnew1.txt";
        $json_response = array();
        $location_id = $id;
        $locationProducts = LocationProduct::where('location_id','=',$location_id)
        									->pluck('product_id');

        $products = Product::whereIn('id',$locationProducts)
                             ->orderBy('name')->get();

        foreach ($products as $product) {
            $row_array = array();
            $row_array['product_id'] = $product['id'];
            $row_array['productname'] = $product['name'];
            $row_array['secondry_name'] = $product['secondry_name'];
            $row_array['tax'] = ($location_tax > 0)? $product['tax'] : 0.00; //$location_tax : 0.00;
            if($product['alias'] != NULL)
            {
              $row_array['productname'] = $product['name'];// .'-'. $row_product['alias']; 
            }
            $cat =  $product['id'];
            $unts = ProductUnit::join('unit_of_measurement','unit_of_measurement.id','=','product_unit.unit_id')
                        ->where('product_id','=',$cat)->get();
            $row_array['unitcount'] = $unts->count();
            $grds = ProductGrade::join('grade_master','grade_master.id','=','product_grade.grade_id')
                        ->where('product_id','=',$cat)->get();
            $row_array['gradecount'] = $grds->count();
            $row_array2 = array(); $row_array3 = array();
            $units = array();
            foreach($unts as $unit)
            {
                
                $row_array2['unit_id'] = $unit['unit_id']; 
                $row_array2['unit'] = $unit['unit']; 
                $unit_id = $unit['unit_id'];

                 array_push($units,$row_array2);                                          
                 
            }
            $row_array['units'] = $units; 
            $grades = array();            
            foreach($grds as $grade)
            {   
                 $row_array3['grade_id'] = $grade['grade_id']; 
                 $row_array3['grade'] = $grade['grade']; 

                  array_push($grades,$row_array3);  
            }
                                             
            $row_array['grades'] = $grades;
                                             
            array_push($json_response,$row_array); 
        }
        // echo json_encode($json_response);
                                       
        //             die();            
        $public_dir = public_path($location.'/');

        $save_as_string = json_encode($json_response,JSON_UNESCAPED_UNICODE);
        if(!file_exists( $public_dir )) {
        	mkdir($public_dir);	
        }
        
        if ($zip->open($public_dir . '/' . $file_zip, ZipArchive::CREATE) === TRUE)
        {
            // Add files to the zip file
            $zip->addFile($file_name, $file_name);
            
            // Add a file new.txt file to zip using the text specified
            $zip->addFromString($file_name, $save_as_string);
         
            // All files are added, so close the zip file.
            $zip->close();

        }

        
        //$location_dir = $_SERVER['HTTP_HOST'];
        $location_dir = url('').'/'.$location.'/'.$file_zip;
        Location::where('id' ,'=',$id)->update(['product_last_update' => time(),
        				         'product_link' => $location_dir
    						]);


        
		return redirect()->route('location.master');
    }

    public function generateCustomerZip($id)
    {
    	
    	$customer =Customer::find($id);
    	$customercode = $customer->customercode;
    	$zip = new ZipArchive;
        $file_zip = "productnew1.zip";
        $file_name = "productnew1.txt";
        $json_response = array();
        $location_id = $id;
        $customer_products = CustomerProduct::where('customer_id','=',$id)->pluck('product_id');

        $products = Product::whereIn('id',$customer_products)
                             ->orderBy('name')->get();

        foreach ($products as $product) {
            $row_array = array();
            $row_array['product_id'] = $product['id'];
            $row_array['productname'] = $product['name'];
            $row_array['secondry_name'] = $product['secondry_name'];
            $row_array['tax'] = $product['tax'];
            if($product['alias'] != NULL)
            {
              $row_array['productname'] = $product['name'];// .'-'. $row_product['alias']; 
            }
            $cat =  $product['id'];
            $unts = ProductUnit::join('unit_of_measurement','unit_of_measurement.id','=','product_unit.unit_id')
                        ->where('product_id','=',$cat)->get();
            $row_array['unitcount'] = $unts->count();
            $grds = ProductGrade::join('grade_master','grade_master.id','=','product_grade.grade_id')
                        ->where('product_id','=',$cat)->get();
            $row_array['gradecount'] = $grds->count();
            $row_array2 = array(); $row_array3 = array();
            $units = array();
            foreach($unts as $unit)
            {
                
                $row_array2['unit_id'] = $unit['unit_id']; 
                $row_array2['unit'] = $unit['unit']; 
                $unit_id = $unit['unit_id'];

                 array_push($units,$row_array2);                                          
                 
            }
            $row_array['units'] = $units; 
            $grades = array();            
            foreach($grds as $grade)
            {   
                 $row_array3['grade_id'] = $grade['grade_id']; 
                 $row_array3['grade'] = $grade['grade']; 

                  array_push($grades,$row_array3);  
            }
                                             
            $row_array['grades'] = $grades;
                                             
            array_push($json_response,$row_array); 
        }
        // echo json_encode($json_response);
                                       
        //             die();            
        $public_dir = public_path($customercode.'/');

        $save_as_string = json_encode($json_response,JSON_UNESCAPED_UNICODE);
        if(!file_exists( $public_dir )) {
        	mkdir($public_dir);	
        }
        
        if ($zip->open($public_dir . '/' . $file_zip, ZipArchive::CREATE) === TRUE)
        {
            // Add files to the zip file
            $zip->addFile($file_name, $file_name);
            
            // Add a file new.txt file to zip using the text specified
            $zip->addFromString($file_name, $save_as_string);
         
            // All files are added, so close the zip file.
            $zip->close();

        }

        
        //$location_dir = $_SERVER['HTTP_HOST'];
        $location_dir = url('').'/'.$customercode.'/'.$file_zip;
        Customer::where('id' ,'=',$id)->update(['product_last_update' => time(),
        				         'product_link' => $location_dir
    						]);
		return redirect()->route('customer.product.map',$id);
    }
}
