<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\CustomExport;
use App\Imports\ImportEmployee;
use App\Helpers\Helper;
use App\Models\Employee;
use Illuminate\Support\Facades\File;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Validator;


class EmployeeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('Admin.employee.index', ['data' => array()]);
    }

    public function findData(Request $request)
    {
        $data = array();
        $input = $request->input();
        if(count($input) > 0){
            $data = $input;
            $data['show_table'] = 1;
            session()->flashInput($request->input());
        }
        return view('Admin.employee.index', ['data' => array()]);
    }

    public function create()
    {
        return view('Admin.employee.create_edit');
    }

     /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //dd($request);
        $validator = Validator::make($request->all(), [
            'employee_id' => 'required|unique:employees,employee_id',
            'employee_name' => 'required',
            // 'email' => 'email|unique:employees',
            // 'profile_image' => 'mimes:jpeg,jpg,png',
            // 'whatsapp_number' => 'numeric|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
            // 'mobile_number' => 'numeric|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }
        $input = $request->input();
        unset($input['_token']);
        unset($input['_method']);
        
        // if($request->hasfile('profile_image'))
        // {
        //     $image = $request->profile_image;
        //     $fileName = "AG-EMP".rand(10,99).date('dmyhisa') . '.' . $image->extension();
        //     $fileName = str_replace(" ", "-", $fileName);
        //     $destinationPath = public_path('/images/employee/');
            
        //     if (!is_dir($destinationPath)) {
        //         mkdir($destinationPath, 0777, TRUE);
        //         @chmod($destinationPath,0777);
        //     }
        //     $image->move($destinationPath, $fileName);
        //     $input['profile_image'] = $fileName;
        // }
        $input['password'] = "HDFC12345";
        $employee = Employee::create($input);
        Helper::successMsg("insert", "Employee");
        return redirect()->route('employee.index');
    }

    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = Employee::find(decrypt($id));
        //dd($data);
        return view('Admin.employee.create_edit', ['data' => $data]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //dd($request);
        $validator = Validator::make($request->all(), [
            'employee_id' => 'required|unique:employees,employee_id,'.$id,
            'employee_name' => 'required',
            // 'email' => 'email|unique:employees,id,'.$id,
            // 'profile_image' => 'mimes:jpeg,jpg,png',
            // 'whatsapp_number' => 'numeric|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
            // 'mobile_number' => 'numeric|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
            
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }
        $input = $request->input();
        unset($input['_token']);
        unset($input['_method']);
        $Employee = Employee::find($id);
        // if($request->hasfile('profile_image'))
        // {
        //     $destinationPath = public_path('/images/employee/');
        //     if(!empty($Employee->profile_image) && file_exists($destinationPath.$Employee->profile_image)){
        //         File::delete($destinationPath.$Employee->profile_image);
        //     }
        //     $image = $request->profile_image;
        //     $fileName = "AG-EMP".rand(10,99).date('dmyhisa') . '.' . $image->extension();
        //     $fileName = str_replace(" ", "-", $fileName);
            
            
        //     if (!is_dir($destinationPath)) {
        //         mkdir($destinationPath, 0777, TRUE);
        //         @chmod($destinationPath,0777);
        //     }
        //     $image->move($destinationPath, $fileName);
        //     $input['profile_image'] = $fileName;
        // }
        Employee::where("id", $id)->update($input);
        Helper::successMsg("update", "Employee");
        return redirect()->route('employee.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Employee::where("id",decrypt($id))->delete();
        Helper::successMsg("delete", "Employee");
        return redirect()->back();
    }
    public function delete($id)
    {
        Employee::where("id",decrypt($id))->delete();
        Helper::successMsg("delete", "Lead");
        return redirect()->back();
    }
    public function status(Request $request, $id)
    {
        Employee::where("id",decrypt($id))->update(array("status"=>$request->status,"updated_at"=>date("Y-m-d H:i:s")));
        Helper::successMsg("Status", "Lead");
        return redirect()->back();
    }

    public function data(Request $request)
    {
        $where = array();
        //filters
        if($request->filters != ""){
            foreach($request->filters as $k=>$v){
                (($v['name'] == 'name') && $v['value'] != "")?($where[] = ["employee_name","LIKE", "%".$v['value']."%"]):"";
            }
        }

        if(empty($where)){
            $where = array(["id", ">", 0]);
        }
        session(["whereExportFilter" => ['whereExport' => $where]]);
        // dd($where);
        $start = $request->has('start')?(int)$request->start:0;
        $perPage = $request->has('length')?(int)$request->length:10;

        $totalRecord = Employee::where($where)->count();
        $tableData = Employee::where($where)->orderBy('id', 'asc')->offset($start)->limit($perPage)->get();
        //dd($tableData);
        $datatable = DataTables::of($tableData)
            ->skipPaging()
            ->setTotalRecords($totalRecord)
            ->editColumn('selectbox', function ($val) {
                return '<input type="checkbox" name="checkedboxes[]" value="'.$val->id.'"/>';
            })
            ->addIndexColumn()
            ->addColumn('image', function ($val) {
                
                if(!empty($val->profile_image)){
                    return "<img src='".asset('images/employee/'.$val->profile_image)."' width='100px' height='100px' class='img-rounded'>";
                }
                
                return "";
            })
            
            ->addColumn('status', function ($val) {
                $encrypt = encrypt($val->id);
                $status = "";
                
                if($val->status == "0"){
                    //disable
                    $status .= '<button type="button" style="" class="btn btn-sm status_btn btn-danger btn-link" data-next_click="1" data-status_link="' . route('employee.status', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Deactive"><i class="fas fa-times" aria-hidden="true"></i></button>';
                }else{
                    $status .= '<button type="button" style="" class="btn btn-sm status_btn btn-success btn-link" data-next_click="0" data-status_link="' . route('employee.status', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Active"><i class="fas fa-check" aria-hidden="true"></i></button>';
                }
                return $status;
            })
            ->addColumn('action', function ($val) {
                $encrypt = encrypt($val->id);
                $action = "";
                
                $action .= '<a class="bt.n btn-sm btn-primary btn-link" href="' . route('employee.edit', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Edit"><i class="fas fa-pen" aria-hidden="true"></i></a>';
                $action .= '<button type="button" style="" class="btn btn-sm delete_btn btn-danger btn-link" data-delete_link="' . route('employee.delete', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Delete"><i class="fas fa-trash" aria-hidden="true"></i></button>';
                
                return $action;
            })
            ->rawColumns(['selectbox','image','status','action'])
            ->make(true);
        return $datatable;
    }

    public function export(Request $request)
    {
        $where = array(["id", ">", 0]);
        
        if(session()->has('whereExportFilter')){
            $where = session()->get('whereExportFilter')['whereExport'];
        }
        $data = Employee::where($where)->orderBy('id', 'desc')->get();
        return Excel::download(new CustomExport("Admin.employee.export", ["data"=>$data, "title"=>"Employee"]),  'employee.xlsx');
    }
    public function multiDelete(Request $request){
        $Event = $request->has('checkedboxes')?$request->checkedboxes:array();
        if(count($Event) > 0){
            Employee::whereIn("id", $Event)->delete();
            Helper::successMsg("delete", "Employee");
        }else{
            Helper::failarMsg("custom", "Not Allowed to delete Multi records!");
        }
        return redirect()->back();
    }
    // import bulk Employees
    public function importEmployee()
    {
        
        return view('Admin.employee.import');
    }
    public function importEmployee_store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'employee_data' => 'required',
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }
        if($request->hasfile('employee_data'))
        {
            $employee_data = $request->employee_data;
            $impData = Excel::import(new ImportEmployee, $employee_data->store('temp'));
            if($impData)
            {
                Helper::successMsg("insert", "Employee Bulk data");
                return redirect()->route('employee.index');
            }else{
                Helper::successMsg("custom", "Something Went wrong!");
                return redirect()->back();
            }
        }
    }
}
