<?php

namespace App\Http\Controllers;

use App\Constants;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Imports\Employee_detailsImport;
use App\Exports\Employee_detailsExport;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\HeadingRowImport;
use Illuminate\Support\Facades\Input;
use App\EmployeeTest;
use App\Dependants;
use App\Imports;


class EmployeesController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = DB::table('main_users AS mu')
                ->join('business_units AS bu', 'bu.id', '=', 'mu.business_unit')
                ->join('departments AS dp', 'dp.id', '=', 'mu.department')
                ->join('main_users AS mu_', 'mu_.id', '=', 'mu.reporting_manager')
                ->select('mu.id', 'mu.employee_id', 'mu.first_name', 'mu.last_name', 'mu.email_address', 'bu.business_unit', 'dp.department_name', 'mu.is_active', 'mu.work_phone', 'mu.job_title', 'mu_.first_name AS reporting_manager', 'mu.personal_phone', 'mu.employee_type', 'mu.role')
                ->paginate(Constants::RESULTS_PER_PAGE);
        return View('Employees.index', compact(['users']));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $departments = DB::table('departments')->get();
        $businessunits = DB::table('business_units')->get();
        $emergency = DB::table('emergency_contacts')->get();
        $dependants = DB::table('dependants')->get();
        return view('Employees.Registration', compact(['departments','businessunits','emergency','dependants']));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    public function export()
    {
        try {
            $export=Excel::download(new Employee_detailsExport, 'Employees.xls');
            return $export;
        } catch (\Exception $e) {
            return redirect('/employees')->with('error','Something wrong happened');

        }

    }
    //importation function
    public function import(Request $request)
    {
        $import = Excel::import(new Imports, request()->file('file'));
        dd($import);
        return redirect('/employees')->with('success','File has been successfully imported');

        /*   $this->validate($request, array(
              'file'      => 'required'
          ));
          try {
              if ($request -> hasFile('file')) {
                  $extension = $request ->file ->getClientOriginalExtension();
                  if ($extension == "xlsx" || $extension == "xls" || $extension == "csv" || $extension == "xlsm" || $extension == "xlsx") {
                      $name = $request->file->getClientOriginalName();

                      $import = Excel::import(new Employee_detailsImport, request()->file('file'));
                        dd($import);
                       return redirect('/employees')->with('success','File has been successfully imported');
                  }
                  else {
                      return redirect('/employees')->with('error','File is a '.$extension.' file.!! Please upload a valid xls/csv file..!!');
                  }
              }

          }
          catch (\Maatwebsite\Excel\Validators\ValidationException $e) {

              $failures = $e->failures();
              // dd($failures);

              foreach ($failures as $failure) {
                  $failure->row(); // row that went wrong

                  $failure->attribute(); //  column index

                  $failure->errors(); // Actual error messages from Laravel validator

                   return redirect('/employees')->withErrors($failures);
              }
          }            */
        /* catch(\Exception $e){
            return redirect('/employees')->with('error','Something wrong happened');
        } */

    }
    public function personalinfo(Request $request)
    {
        $request->validate([
            'name'=>'required',
            'dateofBirth' =>'required',
            'relation'=>'required',

        ]);
        $dependant = new Dependants([
            'name' => $request->get('name'),
            'dateofBirth'=> $request->get('dateofBirth'),
            'relation'=> $request->get('relation'),

        ]);
        $dependant->save();
        return redirect('/employees/create')->with('success', 'Dependant has been added');

    }
    public function dependantedit($id){
        $dependant = Dependants::find($id);
        return redirect('/employees/create', compact('dependant'));
    }
    public function updateDependant(Request $request, $id)
    {
        $request->validate([
            'name'=>'required',
            'dateofBirth'   => 'required',
            'relation'=>'required',
        ]);

        $dependant = Dependants::find($id);
        $dependant->name = $request->get('name');
        $dependant->dateofBirth = $request->get('dateofBirth');
        $dependant->relation = $request->get('relation');
        $dependant->save();

        return redirect('/employees/create')->with('success', 'Dependant has been updated');
    }
    public function dependantdestroy($id)
    {
        $dependant = Dependants::find($id);
        dd($dependant);
        $dependant->delete();

        return redirect('/employees/create')->with('success', 'Dependant has been deleted successfully');
    }

}
