<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Config; 
use App\a_excelupload;
use Session; 
use App\Exports\ExcelExport;
use App\Imports\ExcelImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;

class ExcelController extends Controller
{
    //
 
	public function index()
	{
		$excel = a_excelupload::all();
		return view('a_excelupload',['excel'=>$excel]);
	}
   
	public function export_excel()
	{
		return Excel::download(new ExcelExport, 'testexport.xlsx');
	}
    
    public function detectDelimiter($csvFile)
    {
    $delimiters = [";" => 0, "," => 0, "\t" => 0, "|" => 0];

    $handle = fopen($csvFile, "r");
    $firstLine = fgets($handle);
    fclose($handle); 
    foreach ($delimiters as $delimiter => &$count) {
        $count = count(str_getcsv($firstLine, $delimiter));
    }
    
    if( array_sum( $delimiters ) <= count( $delimiters ) ) 
    return "";
    else
    return array_search(max($delimiters), $delimiters);
    }

    public function withValidator($validator,$file)
    {
        if ($validator->fails()) {
   dd($file);
          } else {

        }

    }

    public function import_excel(Request $request) 
	{
		// validasi
		$validator=$this->validate($request, [
			'file' => 'required|mimes:csv,xls,xlsx,txt'
		]);
        // menangkap file excel
		$file = $request->file('file');
       // self::withValidator($validator,$file);
		    
		// membuat nama file unik
		$nama_file = rand().$file->getClientOriginalName();
        
        $delimiter ='';
        if (strpos($file->getClientOriginalName(), '.csv') !== false)
        {   
            $delimiter =self::detectDelimiter($file);
           // Config::set('excel::csv.delimiter', $delimiter);
           Config::set('excel.csv.delimiter', $delimiter);
          }    

		// upload ke folder file_excel di dalam folder public
		$file->move('file_excel',$nama_file);
 
		// import data
		Excel::import(new ExcelImport, public_path('/file_excel/'.$nama_file));
 
		// notifikasi dengan session
		Session::flash('sukses','Data Excel Berhasil Diimport!');
 
		// alihkan halaman kembali
		return redirect('/excel');
	}
}

