﻿<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\Department;
use App\Models\Designation;
use App\Models\Document;
use App\Models\Employee;
use App\Models\EmployeeDocument;
use App\Mail\UserCreate;
use App\Models\Plan;
use App\Models\User;
use App\Models\Utility;
use App\Models\JobInfo;
use App\Models\BankInfo;
use App\Models\Profile;
use App\Models\EmployeeDeduction;
use App\Models\OrganisationEmployeeAllowance;
use File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use App\Models\JoiningLetter;
use App\Imports\EmployeesImport;
use App\Exports\EmployeesExport;
use App\Models\Contract;
use App\Models\ExperienceCertificate;
use App\Models\LoginDetail;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\NOC;
use App\Models\PaySlip;
use App\Models\Termination;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

//use Faker\Provider\File;

class EmployeeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        if (\Auth::user()->can('Manage Employee')) {
            if (Auth::user()->type == 'employee') {
                $employees = Employee::where('user_id', '=', Auth::user()->id)->get();
            } else {
                $user = Auth::user();
                $organisationId = $user->organisation_id;
                $employees = Employee::where("organisation_id", $organisationId)->with(['branch', 'department', 'designation', 'user'])->get();
            }

            return view('employee.index', compact('employees'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }

        // if (Auth::user()->type == 'employee') {
        //     $employees = Employee::where('user_id', '=', Auth::user()->id)->get();
        // } else {
        //     $user = Auth::user();
        //     $employees = Employee::where('organisation_id', $user->organisation_id)->with(['branch', 'department', 'designation', 'user'])->get();
        //     // $employees = Employee::where('created_by', \Auth::user()->creatorId())->with(['branch', 'department', 'designation', 'user'])->get();
        // }

        // return view('employee.index', compact('employees'));
    }

    public function search(Request $request)
    {
        $user        = Auth::user();
        $orgId       = $user->organisation_id;
        $search      = $request->query('q', '');
        $deptFilter  = $request->query('department_id');

        $query = Employee::where('organisation_id', $orgId)
            ->where(function ($q) use ($search) {
                $q->where('name',  'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });


        if (!$user->can('manage goals')) {
            $managerEmp = Employee::where('user_id', $user->id)->first();

            if (!$managerEmp) {
                return response()->json([]);
            }

            // departments where this employee is manager
            $managedDeptIds = Department::where('manager_id', $managerEmp->id)
                ->pluck('id');

            if ($managedDeptIds->isEmpty()) {
                return response()->json([]);
            }

            // If a dept filter is passed, intersect with manager’s departments
            if ($deptFilter) {
                $managedDeptIds = $managedDeptIds->intersect([$deptFilter]);
            }

            $query->whereIn('department_id', $managedDeptIds);
        } elseif ($deptFilter) {
            $query->where('department_id', $deptFilter);
        }

        $employees = $query->select('id', 'name')
            ->limit(15)
            ->get();

        return response()->json($employees);
    }

    public function create()
    {
        // if (\Auth::user()->can('Create Employee')) {
        //     $company_settings = Utility::settings();
        //     $documents        = Document::where('created_by', Auth::user()->creatorId())->get();
        //     $branches         = Branch::where('created_by', Auth::user()->creatorId())->get()->pluck('name', 'id');
        //     $departments      = Department::where('created_by', Auth::user()->creatorId())->get()->pluck('name', 'id');
        //     $designations     = Designation::where('created_by', Auth::user()->creatorId())->get()->pluck('name', 'id');
        //     $employees        = User::where('created_by', Auth::user()->creatorId())->get();
        //     $employeesId      = Auth::user()->employeeIdFormat($this->employeeNumber());

        //     return view('employee.create', compact('employees', 'employeesId', 'departments', 'designations', 'documents', 'branches', 'company_settings'));
        // } else {
        //     return redirect()->back()->with('error', __('Permission denied.'));
        // }


        $company_settings = Utility::settings();
        $documents        = Document::where('created_by', Auth::user()->creatorId())->get();
        $branches         = Branch::where('created_by', Auth::user()->creatorId())->get()->pluck('name', 'id');
        $departments      = Department::where('created_by', Auth::user()->creatorId())->get()->pluck('name', 'id');
        $designations     = Designation::where('created_by', Auth::user()->creatorId())->get()->pluck('name', 'id');
        $employees        = User::where('created_by', Auth::user()->creatorId())->get();
        $employeesId      = Auth::user()->employeeIdFormat($this->employeeNumber());

        return view('employee.create', compact('employees', 'employeesId', 'departments', 'designations', 'documents', 'branches', 'company_settings'));
    }

    public function store(Request $request)
    {
        if (\Auth::user()->can('Create Employee')) {

            $orgId = Auth::user()->organisation_id;
            $rules = [
                'name' => 'required|max:120',
                'dob' => 'before:' . date('Y-m-d'),
                'gender' => 'required',
                'phone' => 'required',
                'address' => 'required',
                'email' => 'required|unique:users|email|max:100',
                'password' => 'required',
                // 'branch_id' => 'required',
                // 'department_id' => 'required',
                // 'designation_id' => 'required',
                'document.*' => 'required',
            ];
            // $rules['biometric_emp_id'] = [
            //     'required',
            //     Rule::unique('employees')->where(function ($query) {
            //         return $query->where('created_by', Auth::user()->creatorId());
            //     })
            // ];

            $validator = \Validator::make(
                $request->all(),
                $rules
            );

            if ($validator->fails()) {
                $messages = $validator->getMessageBag();

                return redirect()->back()->withInput()->with('error', $messages->first());
            }


            $date = date("Y-m-d H:i:s");
            $default_language = DB::table('settings')->select('value')->where('name', 'default_language')->where('created_by', \Auth::user()->creatorId())->first();

            // new company default language
            if ($default_language == null) {
                $default_language = DB::table('settings')->select('value')->where('name', 'default_language')->first();
            }

            if ($request->hasFile('document')) {
                foreach ($request->document as $key => $document) {

                    $image_size = $request->file('document')[$key]->getSize();


                    $filenameWithExt = $request->file('document')[$key]->getClientOriginalName();
                    $filename        = pathinfo($filenameWithExt, PATHINFO_FILENAME);
                    $extension       = $request->file('document')[$key]->getClientOriginalExtension();
                    $fileNameToStore = $filename . '_' . time() . '.' . $extension;
                    $dir             = 'uploads/document/';

                    $image_path      = $dir . $fileNameToStore;

                    $path = \App\Models\Utility::upload_coustom_file($request, 'document', $fileNameToStore, $dir, $key, []);

                    if ($path['flag'] == 1) {
                        $url = $path['url'];
                    } else {
                        return redirect()->back()->with('error', __($path['msg']));
                    }
                }
            }


            $user = User::create(
                [
                    'name' => $request['name'],
                    'email' => $request['email'],
                    'password' => Hash::make($request['password']),
                    'organisation_id' => $orgId,
                    'type' => 'employee',
                    'lang' => !empty($default_language) ? $default_language->value : 'en',
                    'created_by' => \Auth::user()->creatorId(),
                    'email_verified_at' => $date,
                    'is_active' => true,
                    'is_registered' => true
                ]
            );
            $user->save();
            $user->assignRole('Employee');

            DB::beginTransaction();
            try {

                $nameParts = explode(' ', trim($request['name']), 2);
                $firstName = $nameParts[0] ?? '';
                $lastName = $nameParts[1] ?? '';


                // Create profile
                DB::table('profiles')->insert([
                    'user_id' => $user->id,
                    'first_name' => $firstName,
                    'last_name' => $lastName,
                    'gender' => $request['gender'],
                    'work_email' => $request['email'],
                    'address' => $request['address'],
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                // Create job info
                DB::table('job_info')->insert([
                    'user_id' => $user->id,
                    'hire_date' => $request['company_doj'],
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                // Create bank info
                DB::table('bank_info')->insert([
                    'user_id' => $user->id,
                    'bank_name' => $request['bank_name'],
                    'account_number' => $request['account_number'],
                    'account_name' => $request['account_holder_name'],
                    'bank_code' => $request['bank_identifier_code'],
                    'tax_id' => $request['tax_payer_id'],
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                DB::commit();
         


            if (!empty($request->document) && !is_null($request->document)) {
                $document_implode = implode(',', array_keys($request->document));
            } else {
                $document_implode = null;
            }


            $employee = Employee::create(
                [
                    'user_id' => $user->id,
                    'name' => $request['name'],
                    'dob' => $request['dob'],
                    'gender' => $request['gender'],
                    'phone' => $request['phone'],
                    'address' => $request['address'],
                    'email' => $request['email'],
                    'password' => Hash::make($request['password']),
                    'employee_id' => $this->employeeNumber(),
                    // 'biometric_emp_id' => !empty($request['biometric_emp_id']) ? $request['biometric_emp_id'] : '',
                    'branch_id' => $request['branch_id'] ?? 0,
                    'department_id' => $request['department_id'] ?? 0,
                    'designation_id' => $request['designation_id'] ?? 0,
                    'company_doj' => $request['company_doj'],
                    'documents' => $document_implode,
                    'account_holder_name' => $request['account_holder_name'],
                    'account_number' => $request['account_number'],
                    'bank_name' => $request['bank_name'],
                    'bank_identifier_code' => $request['bank_identifier_code'],
                    'branch_location' => $request['branch_location'],
                    'tax_payer_id' => $request['tax_payer_id'],
                    'created_by' => \Auth::user()->creatorId(),
                ]
            );

            if ($request->hasFile('document')) {
                foreach ($request->document as $key => $document) {

                    $image_size = $request->file('document')[$key]->getSize();

                    $filenameWithExt = $request->file('document')[$key]->getClientOriginalName();
                    $filename        = pathinfo($filenameWithExt, PATHINFO_FILENAME);
                    $extension       = $request->file('document')[$key]->getClientOriginalExtension();
                    $fileNameToStore = $filename . '_' . time() . '.' . $extension;
                    $dir             = 'uploads/document/';

                    $image_path      = $dir . $fileNameToStore;

                    $path = \App\Models\Utility::upload_coustom_file($request, 'document', $fileNameToStore, $dir, $key, []);

                    if ($path['flag'] == 1) {
                        $url = $path['url'];
                    } else {
                        return redirect()->back()->with('error', __($path['msg']));
                    }
                    $employee_document = EmployeeDocument::create(
                        [
                            'employee_id' => $employee['employee_id'],
                            'document_id' => $key,
                            'document_value' => $path['url'],
                            'created_by' => \Auth::user()->creatorId(),
                        ]
                    );
                    $employee_document->save();
                }
            }
            $setings = \App\Models\Utility::settings();
            if ($setings['new_employee'] == 1) {
                $department = Department::find($request['department_id']);
                $branch = Branch::find($request['branch_id']);
                $designation = Designation::find($request['designation_id']);
                $uArr = [
                    'employee_email' => $user->email,
                    'employee_password' => $request->password,
                    'employee_name' => $request['name'],
                    'employee_branch' => !empty($branch->name) ? $branch->name : '',
                    'employee_department' => !empty($department->name) ? $department->name : '',
                    'employee_designation' => !empty($designation->name) ? $designation->name : '',
                ];
                $resp = \App\Models\Utility::sendEmailTemplate('new_employee', [$user->id => $user->email], $uArr);

                return redirect()->route('employee.index')->with('success', __('Employee successfully created.') . ((!empty($resp) && $resp['is_success'] == false && !empty($resp['error'])) ? '<br> <span class="text-danger">' . $resp['error'] . '</span>' : '') . ((isset($result) && $result != 1) ? '<br> <span class="text-danger">' . $result . '</span>' : ''));
            }
            } catch (\Exception $e) {
                DB::rollback();
            }

            return redirect()->route('employee.index')->with('success', __('Employee successfully created.'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function edit($id)
    {
        try {
            $id = Crypt::decrypt($id);
        } catch (\Throwable $th) {
            return redirect()->back()->with('error', __('Employee Not Found.'));
        }
        // if (\Auth::user()->can('Edit Employee')) {
        //     $documents    = Document::where('created_by', \Auth::user()->creatorId())->get();
        //     $branches     = Branch::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        //     $departments  = Department::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        //     $designations = Designation::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        //     $employee     = Employee::find($id);
        //     $employeesId  = \Auth::user()->employeeIdFormat($employee->employee_id);

        //     return view('employee.edit', compact('employee', 'employeesId', 'branches', 'departments', 'designations', 'documents'));
        // } else {
        //     return redirect()->back()->with('error', __('Permission denied.'));
        // }

        $documents    = Document::where('created_by', \Auth::user()->creatorId())->get();
        $branches     = Branch::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        $departments  = Department::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        $designations = Designation::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        $employee     = Employee::find($id);
        $employeesId  = \Auth::user()->employeeIdFormat($employee->employee_id);
        $jobInfo = JobInfo::where("user_id", $employee->user_id)->first();
        $profile = Profile::where("user_id", $employee->user_id)->first();
        $bankInfo = BankInfo::where("user_id", $employee->user_id)->first();

        $allowances = OrganisationEmployeeAllowance::where('employee_id', $employee->user_id)->get();
        $deductions = EmployeeDeduction::where('employee_id', $employee->user_id)->get();
        return view('employee.edit', compact('employee', 'employeesId', 'branches', 'departments', 'designations', 'documents', 'jobInfo', 'profile', 'bankInfo', 'allowances', 'deductions'));
    }

    public function updateAllowances(Request $request, $id)
    {
        $validated = $request->validate([
            'allowancesArray' => 'required|array',
            'allowancesArray.*' => 'nullable|numeric|min:0',
        ]);
        foreach ($validated['allowancesArray'] as $allowanceId => $value) {
            OrganisationEmployeeAllowance::where('id', $allowanceId)
                ->update(['value' => $value]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Allowance updated successfully.',
        ]);
    }
    public function updateDeductions(Request $request, $id)
    {
        $validated = $request->validate([
            'deductionsArray' => 'required|array',
            'deductionsArray.*' => 'nullable|numeric|min:0',
        ]);

        foreach ($validated['deductionsArray'] as $deductionId => $value) {
            EmployeeDeduction::where('id', $deductionId)->update(['value' => $value]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Deductions updated successfully.',
        ]);
    }

    public function update(Request $request, $id)
    {
        // if (\Auth::user()->can('Edit Employee')) {

        $employee = Employee::findOrFail($id);

        $rules = [
            'name' => 'required',
            'dob' => 'required',
            'gender' => 'required',
            'phone' => 'required',
            'address' => 'required',
        ];

        // if ($request->has('biometric_emp_id') && $employee->biometric_emp_id != $request->biometric_emp_id) {
        //     $rules['biometric_emp_id'] = [
        //         'required',
        //         Rule::unique('employees')->where(function ($query) {
        //             return $query->where('created_by', Auth::user()->creatorId());
        //         })
        //     ];
        // }

        $validator = \Validator::make(
            $request->all(),
            $rules
        );

        if ($validator->fails()) {
            $messages = $validator->getMessageBag();

            return redirect()->back()->with('error', $messages->first());
        }


        if ($request->document) {

            foreach ($request->document as $key => $document) {
                $employee_document = EmployeeDocument::where('employee_id', $employee->employee_id)->where('document_id', $key)->first();
                if (!empty($document)) {

                    //storage limit
                    $dir = 'uploads/document/';
                    if (!empty($employee_document)) {
                        $file_path = $dir . $employee_document->document_value;
                    }
                    // $image_size = $request->file('document')[$key]->getSize();
                    // $result = Utility::updateStorageLimit(\Auth::user()->creatorId(), $image_size);

                    // if ($result == 1) {
                    if (!empty($$file_path)) {
                        Utility::changeStorageLimit(\Auth::user()->creatorId(), $file_path);
                    }

                    $filenameWithExt = $request->file('document')[$key]->getClientOriginalName();
                    $filename        = pathinfo($filenameWithExt, PATHINFO_FILENAME);
                    $extension       = $request->file('document')[$key]->getClientOriginalExtension();
                    $fileNameToStore = $filename . '_' . time() . '.' . $extension;
                    $dir             = 'uploads/document/';

                    $image_path      = $dir . $fileNameToStore;

                    $path = \App\Models\Utility::upload_coustom_file($request, 'document', $fileNameToStore, $dir, $key, []);
                    if (!empty($employee_document)) {
                        if ($employee_document->document_value) {
                            \File::delete(storage_path('uploads/document/' . $employee_document->document_value));
                        }
                        $employee_document->document_value = $fileNameToStore;
                        $employee_document->save();
                    } else {
                        $employee_document                 = new EmployeeDocument();
                        $employee_document->employee_id    = $employee->employee_id;
                        $employee_document->document_id    = $key;
                        $employee_document->document_value = $fileNameToStore;
                        $employee_document->save();
                    }

                    if ($path['flag'] == 1) {
                        $url = $path['url'];
                    } else {
                        return redirect()->back()->with('error', __($path['msg']));
                    }
                    //  }
                }
            }
        }

        if (!empty($request->document) && !is_null($request->document)) {
            $document_implode = implode(',', array_keys($request->document));
        } else {
            $document_implode = null;
        }

        $employee = Employee::findOrFail($id);
        $input    = $request->all();
        $input['documents'] = $document_implode;
        $employee->fill($input)->save();
        if ($request->salary) {
            return redirect()->route('setsalary.index')->with('success', 'Employee successfully updated.');
        }

        if (\Auth::user()->type != 'employee') {
            // return redirect()->route('employee.index')->with('success', 'Employee successfully updated.');
            return redirect()->route('employee.index')->with('success', __('Employee successfully updated.') . ((isset($result) && $result != 1) ? '<br> <span class="text-danger">' . $result . '</span>' : ''));
        } else {
            return redirect()->route('employee.show', \Illuminate\Support\Facades\Crypt::encrypt($employee->id))->with('success', __('Employee successfully updated.') . ((isset($result) && $result != 1) ? '<br> <span class="text-danger">' . $result . '</span>' : ''));
        }
        // } else {
        //     return redirect()->back()->with('error', __('Permission denied.'));
        // }
    }

    public function destroy($id)
    {
        if (Auth::user()->can('Delete Employee')) {
            $employee      = Employee::findOrFail($id);
            $user          = User::where('id', '=', $employee->user_id)->first();
            $emp_documents = EmployeeDocument::where('employee_id', $employee->employee_id)->get();
            $ContractEmployee = Contract::where('employee_name', '=', $employee->user_id)->get();
            $payslips = PaySlip::where('employee_id', $id)->get();
            $employee->delete();
            $user->delete();

            foreach ($ContractEmployee as $contractdelete) {
                $contractdelete->delete();
            }

            foreach ($payslips as $payslip) {
                $payslip->delete();
            }

            $dir = storage_path('uploads/document/');
            foreach ($emp_documents as $emp_document) {

                $emp_document->delete();
                // \File::delete(storage_path('uploads/document/' . $emp_document->document_value));
                if (!empty($emp_document->document_value)) {

                    $file_path = 'uploads/document/' . $emp_document->document_value;
                    $result = Utility::changeStorageLimit(\Auth::user()->creatorId(), $file_path);

                    // unlink($dir . $emp_document->document_value);
                }
            }

            return redirect()->route('employee.index')->with('success', 'Employee successfully deleted.');
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function show($id)
    {
        // if (\Auth::user()->can('Show Employee')) {
        //     try {
        //         $empId        = \Illuminate\Support\Facades\Crypt::decrypt($id);
        //     } catch (\RuntimeException $e) {
        //         return redirect()->back()->with('error', __('Employee not avaliable'));
        //     }
        //     $documents    = Document::where('created_by', \Auth::user()->creatorId())->get();
        //     $branches     = Branch::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        //     $departments  = Department::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        //     $designations = Designation::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        //     // $employee = Employee::where('id', '=', $empId)->orWhere('user_id', '=', $empId)->where('created_by', \Auth::user()->creatorId())->first();
        //     $employee     = Employee::find($empId);
        //     $employeesId  = \Auth::user()->employeeIdFormat($employee->employee_id);
        //     $empId        = Crypt::decrypt($id);

        //     //     $employee     = Employee::find($empId);
        //     // $branch= Branch::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');

        //     return view('employee.show', compact('employee', 'employeesId', 'branches', 'departments', 'designations', 'documents'));
        // } else {
        //     return redirect()->back()->with('error', __('Permission denied.'));
        // }

        try {
            $empId = \Illuminate\Support\Facades\Crypt::decrypt($id);
        } catch (\RuntimeException $e) {
            return redirect()->back()->with('error', __('Employee not avaliable'));
        }
        $documents    = Document::where('created_by', \Auth::user()->creatorId())->get();
        $branches     = Branch::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        $departments  = Department::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        $designations = Designation::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        // $employee = Employee::where('id', '=', $empId)->orWhere('user_id', '=', $empId)->where('created_by', \Auth::user()->creatorId())->first();
        $employee     = Employee::find($empId);
        $employeesId  = \Auth::user()->employeeIdFormat($employee->employee_id);
        $empId        = Crypt::decrypt($id);

        //     $employee     = Employee::find($empId);
        // $branch= Branch::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
        $jobInfo = JobInfo::where("user_id", $employee->user_id)->first();
        $profile = Profile::where("user_id", $employee->user_id)->first();
        $bankInfo = BankInfo::where("user_id", $employee->user_id)->first();

        $allowances = OrganisationEmployeeAllowance::where('employee_id', $employee->user_id)->get();
        $deductions = EmployeeDeduction::where('employee_id', $employee->user_id)->get();
        return view('employee.show', compact('employee', 'employeesId', 'branches', 'departments', 'designations', 'documents', 'jobInfo', 'profile', 'bankInfo', 'allowances', 'deductions'));
    }

    function employeeNumber()
    {
        $latest = Employee::where('created_by', '=', \Auth::user()->creatorId())->latest('id')->first();
        if (!$latest) {
            return 1;
        }

        return $latest->employee_id + 1;
    }

    public function export()
    {
        return Excel::download(new EmployeesExport, 'employees.xlsx');
    }

    // public function export()
    // {
    //     $name = 'employee_' . date('Y-m-d i:h:s');
    //     $data = Excel::download(new EmployeesExport(), $name . '.xlsx');


    //     return $data;
    // }

    public function showImportForm()
    {
        return view('employee.import-employees');
    }

    public function importEmployees(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xlsx,xls,csv',
        ]);

        if ($request->file('file')->getClientOriginalExtension() != 'xlsx') {
            return redirect()->back()->with('error', 'Invalid file type.');
        }

        // Define column mappings (these would likely come from the user or config)
        $columns = [
            'first_name' => 'first_name',
            'last_name' => 'last_name',
            'middle_name' => 'middle_name',
            'dob' => 'dob',
            'gender' => 'gender',
            'work_phone' => 'work_phone',
            'mobile_phone' => 'mobile_phone',
            'address' => 'address',
            'email' => 'email',
            'work_email' => 'work_email',
            'nationality' => 'nationality',
            'marital_status' => 'marital_status',
            'pension_percentage' => 'pension_percentage',
            'account_number' => 'account_number',
            'bank_name' => 'bank_name',
            'bank_code' => 'bank_code',
            'pfa_pin' => 'pfa_pin',
            'pfa_name' => 'pfa_name',
            'pfa_plan_id' => 'pfa_plan_id',
            'tax_id' => 'tax_id',
            'nhf_number' => 'nhf_number',
            'employee_date' => 'employee_date',
            'job_title' => 'job_title',
            'department_id' => 'department_id',
            'employee_type_id' => 'employee_type_id',
            'pay_frequency' => 'pay_frequency',
            'basic_salary_amount' => 'basic_salary_amount',
            'gross_salary_amount' => 'gross_salary_amount',
            'percentage_basic_salary_on_gross' => 'percentage_basic_salary_on_gross',
            'is_annual_pay' => 'is_annual_pay',
            'currency' => 'currency',
            'branch' => 'branch'
        ];

        // try {
            if ($request->hasFile('file') && $request->file('file')->isValid()) {
            Excel::import(new EmployeesImport($columns), $request->file('file'));
                return redirect()->route('employee.index')->with('success', 'Employees imported successfully.');
            } else {
                return redirect()->route('employee.index')->with('error', 'No valid file uploaded.');
            }
        // } catch (\Exception $e) {
        //     \Log::error('Import failed: ' . $e->getMessage());
        //     return redirect()->route('employee.index')->with('error', 'Failed to import employees: ' . $e->getMessage());
        // }
    }
    public function profile(Request $request)
    {
        if (\Auth::user()->can('Manage Employee Profile')) {
            $employees = Employee::where('created_by', \Auth::user()->creatorId())->with(['designation', 'user']);
            if (!empty($request->branch_id)) {
                $employees->where('branch_id', $request->branch_id);
            }
            if (!empty($request->department_id)) {
                $employees->where('department_id', $request->department_id);
            }
            if (!empty($request->designation_id)) {
                $employees->where('designation_id', $request->designation_id);
            }
            $employees = $employees->get();

            $brances = Branch::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');

            $departments = Department::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');

            $designations = Designation::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');

            return view('employee.profile', compact('employees', 'departments', 'designations', 'brances'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }


    public function profileShow($id)
    {
        if (\Auth::user()->can('Show Employee Profile')) {
            $empId        = Crypt::decrypt($id);
            $documents    = Document::where('created_by', \Auth::user()->creatorId())->get();
            $branches     = Branch::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
            $departments  = Department::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
            $designations = Designation::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
            $employee     = Employee::find($empId);
            if ($employee == null) {
                $employee     = Employee::where('user_id', $empId)->first();
            }

            $employeesId  = \Auth::user()->employeeIdFormat($employee->employee_id);

            return view('employee.show', compact('employee', 'employeesId', 'branches', 'departments', 'designations', 'documents'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function lastLogin(Request $request)
    {
        $users = User::where('created_by', \Auth::user()->creatorId())->get();

        $time = date_create($request->month);
        $firstDayofMOnth = (date_format($time, 'Y-m-d'));
        $lastDayofMonth =    \Carbon\Carbon::parse($request->month)->endOfMonth()->toDateString();
        $objUser = \Auth::user();

        $usersList = User::where('created_by', '=', $objUser->creatorId())
            ->whereNotIn('type', ['super admin', 'company'])->get()->pluck('name', 'id');
        $usersList->prepend('All', '');
        if ($request->month == null) {
            $userdetails = DB::table('login_details')
                ->join('users', 'login_details.user_id', '=', 'users.id')
                ->select(DB::raw('login_details.*, users.id as user_id , users.name as user_name , users.email as user_email ,users.type as user_type'))
                ->where(['login_details.created_by' => \Auth::user()->creatorId()])
                ->whereMonth('date', date('m'))->whereYear('date', date('Y'));
        } else {
            $userdetails = DB::table('login_details')
                ->join('users', 'login_details.user_id', '=', 'users.id')
                ->select(DB::raw('login_details.*, users.id as user_id , users.name as user_name , users.email as user_email ,users.type as user_type'))
                ->where(['login_details.created_by' => \Auth::user()->creatorId()]);
        }
        if (!empty($request->month)) {
            $userdetails->where('date', '>=', $firstDayofMOnth);
            $userdetails->where('date', '<=', $lastDayofMonth);
        }
        if (!empty($request->employee)) {
            $userdetails->where(['user_id'  => $request->employee]);
        }
        $userdetails = $userdetails->get();

        return view('employee.lastLogin', compact('users', 'usersList', 'userdetails'));
    }

    public function employeeJson(Request $request)
    {
        $employees = Employee::where('branch_id', $request->branch)->get()->pluck('name', 'id')->toArray();

        return response()->json($employees);
    }

    public function joiningletterPdf($id)
    {
        $users = \Auth::user();

        $currantLang = $users->currentLanguage();
        $joiningletter = JoiningLetter::where('lang', $currantLang)->where('created_by', \Auth::user()->creatorId())->first();
        $date = date('Y-m-d');
        $employees = Employee::where('id', $id)->where('created_by', \Auth::user()->creatorId())->first();
        $settings = \App\Models\Utility::settings();
        $secs = strtotime($settings['company_start_time']) - strtotime("00:00");
        $result = date("H:i", strtotime($settings['company_end_time']) - $secs);
        $obj = [
            'date' =>  \Auth::user()->dateFormat($date),
            'app_name' => env('APP_NAME'),
            'employee_name' => $employees->name,
            'address' => !empty($employees->address) ? $employees->address : '',
            'designation' => !empty($employees->designation->name) ? $employees->designation->name : '',
            'start_date' => !empty($employees->company_doj) ? $employees->company_doj : '',
            'branch' => !empty($employees->Branch->name) ? $employees->Branch->name : '',
            'start_time' => !empty($settings['company_start_time']) ? $settings['company_start_time'] : '',
            'end_time' => !empty($settings['company_end_time']) ? $settings['company_end_time'] : '',
            'total_hours' => $result,
        ];

        $joiningletter->content = JoiningLetter::replaceVariable($joiningletter->content, $obj);
        return view('employee.template.joiningletterpdf', compact('joiningletter', 'employees'));
    }
    public function joiningletterDoc($id)
    {
        $users = \Auth::user();

        $currantLang = $users->currentLanguage();
        $joiningletter = JoiningLetter::where('lang', $currantLang)->where('created_by', \Auth::user()->creatorId())->first();
        $date = date('Y-m-d');
        $employees = Employee::where('id', $id)->where('created_by', \Auth::user()->creatorId())->first();
        $settings = \App\Models\Utility::settings();
        $secs = strtotime($settings['company_start_time']) - strtotime("00:00");
        $result = date("H:i", strtotime($settings['company_end_time']) - $secs);

        $obj = [
            'date' =>  \Auth::user()->dateFormat($date),

            'app_name' => env('APP_NAME'),
            'employee_name' => $employees->name,
            'address' => !empty($employees->address) ? $employees->address : '',
            'designation' => !empty($employees->designation->name) ? $employees->designation->name : '',
            'start_date' => !empty($employees->company_doj) ? $employees->company_doj : '',
            'branch' => !empty($employees->Branch->name) ? $employees->Branch->name : '',
            'start_time' => !empty($settings['company_start_time']) ? $settings['company_start_time'] : '',
            'end_time' => !empty($settings['company_end_time']) ? $settings['company_end_time'] : '',
            'total_hours' => $result,

        ];
        $joiningletter->content = JoiningLetter::replaceVariable($joiningletter->content, $obj);
        return view('employee.template.joiningletterdocx', compact('joiningletter', 'employees'));
    }

    public function ExpCertificatePdf($id)
    {
        $currantLang = \Cookie::get('LANGUAGE');
        if (!isset($currantLang)) {
            $currantLang = 'en';
        }
        $termination = Termination::where('employee_id', $id)->where('created_by', \Auth::user()->creatorId())->first();
        $experience_certificate = ExperienceCertificate::where('lang', $currantLang)->where('created_by', \Auth::user()->creatorId())->first();
        $date = date('Y-m-d');
        $employees = Employee::where('id', $id)->where('created_by', \Auth::user()->creatorId())->first();
        $settings = \App\Models\Utility::settings();
        $secs = strtotime($settings['company_start_time']) - strtotime("00:00");
        $result = date("H:i", strtotime($settings['company_end_time']) - $secs);
        $date1 = date_create($employees->company_doj);
        $date2 = date_create($employees->termination_date);
        $diff  = date_diff($date1, $date2);
        $duration = $diff->format("%a days");

        if (!empty($termination->termination_date)) {

            $obj = [
                'date' =>  \Auth::user()->dateFormat($date),
                'app_name' => env('APP_NAME'),
                'employee_name' => $employees->name,
                'payroll' => !empty($employees->salaryType->name) ? $employees->salaryType->name : '',
                'duration' => $duration,
                'designation' => !empty($employees->designation->name) ? $employees->designation->name : '',

            ];
        } else {
            return redirect()->back()->with('error', __('Termination date is required.'));
        }


        $experience_certificate->content = ExperienceCertificate::replaceVariable($experience_certificate->content, $obj);
        return view('employee.template.ExpCertificatepdf', compact('experience_certificate', 'employees'));
    }
    public function ExpCertificateDoc($id)
    {
        $currantLang = \Cookie::get('LANGUAGE');
        if (!isset($currantLang)) {
            $currantLang = 'en';
        }
        $termination = Termination::where('employee_id', $id)->where('created_by', \Auth::user()->creatorId())->first();
        $experience_certificate = ExperienceCertificate::where('lang', $currantLang)->where('created_by', \Auth::user()->creatorId())->first();
        $date = date('Y-m-d');
        $employees = Employee::where('id', $id)->where('created_by', \Auth::user()->creatorId())->first();;
        $settings = \App\Models\Utility::settings();
        $secs = strtotime($settings['company_start_time']) - strtotime("00:00");
        $result = date("H:i", strtotime($settings['company_end_time']) - $secs);
        $date1 = date_create($employees->company_doj);
        $date2 = date_create($employees->termination_date);
        $diff  = date_diff($date1, $date2);
        $duration = $diff->format("%a days");
        if (!empty($termination->termination_date)) {
            $obj = [
                'date' =>  \Auth::user()->dateFormat($date),
                'app_name' => env('APP_NAME'),
                'employee_name' => $employees->name,
                'payroll' => !empty($employees->salaryType->name) ? $employees->salaryType->name : '',
                'duration' => $duration,
                'designation' => !empty($employees->designation->name) ? $employees->designation->name : '',

            ];
        } else {
            return redirect()->back()->with('error', __('Termination date is required.'));
        }

        $experience_certificate->content = ExperienceCertificate::replaceVariable($experience_certificate->content, $obj);
        return view('employee.template.ExpCertificatedocx', compact('experience_certificate', 'employees'));
    }
    public function NocPdf($id)
    {
        $users = \Auth::user();

        $currantLang = $users->currentLanguage();
        $noc_certificate = NOC::where('lang', $currantLang)->where('created_by', \Auth::user()->creatorId())->first();
        $date = date('Y-m-d');
        $employees = Employee::where('id', $id)->where('created_by', \Auth::user()->creatorId())->first();
        $settings = \App\Models\Utility::settings();
        $secs = strtotime($settings['company_start_time']) - strtotime("00:00");
        $result = date("H:i", strtotime($settings['company_end_time']) - $secs);


        $obj = [
            'date' =>  \Auth::user()->dateFormat($date),
            'employee_name' => $employees->name,
            'designation' => !empty($employees->designation->name) ? $employees->designation->name : '',
            'app_name' => env('APP_NAME'),
        ];

        $noc_certificate->content = NOC::replaceVariable($noc_certificate->content, $obj);
        return view('employee.template.Nocpdf', compact('noc_certificate', 'employees'));
    }
    public function NocDoc($id)
    {
        $users = \Auth::user();

        $currantLang = $users->currentLanguage();
        $noc_certificate = NOC::where('lang', $currantLang)->where('created_by', \Auth::user()->creatorId())->first();
        $date = date('Y-m-d');
        $employees = Employee::where('id', $id)->where('created_by', \Auth::user()->creatorId())->first();
        $settings = \App\Models\Utility::settings();
        $secs = strtotime($settings['company_start_time']) - strtotime("00:00");
        $result = date("H:i", strtotime($settings['company_end_time']) - $secs);


        $obj = [
            'date' =>  \Auth::user()->dateFormat($date),
            'employee_name' => $employees->name,
            'designation' => !empty($employees->designation->name) ? $employees->designation->name : '',
            'app_name' => env('APP_NAME'),
        ];

        $noc_certificate->content = NOC::replaceVariable($noc_certificate->content, $obj);
        return view('employee.template.Nocdocx', compact('noc_certificate', 'employees'));
    }

    public function getdepartment(Request $request)
    {
        if ($request->branch_id == 0) {
            $departments = Department::where('created_by', '=', \Auth::user()->creatorId())->get()->pluck('name', 'id')->toArray();
        } else {
            $departments = Department::where('created_by', '=', \Auth::user()->creatorId())->where('branch_id', $request->branch_id)->get()->pluck('name', 'id')->toArray();
        }
        return response()->json($departments);
    }

    public function json(Request $request)
    {
        if ($request->department_id == 0) {
            $designations = Designation::where('created_by', '=', \Auth::user()->creatorId())->get()->pluck('name', 'id')->toArray();
        }
        $designations = Designation::where('department_id', $request->department_id)->where('created_by', '=', \Auth::user()->creatorId())->get()->pluck('name', 'id')->toArray();

        return response()->json($designations);
    }

    public function view($id)
    {
        $users = LoginDetail::find($id);
        return view('employee.user_log', compact('users'));
    }

    public function logindestroy($id)
    {
        $employee = LoginDetail::where('user_id', $id)->delete();

        return redirect()->back()->with('success', 'Employee successfully deleted.');
    }

    public function employeePassword($id)
    {
        $eId        = \Crypt::decrypt($id);

        $user = User::find($eId);

        $employee = User::where('id', $eId)->first();

        return view('employee.reset', compact('user', 'employee'));
    }

    public function employeePasswordReset(Request $request, $id)
    {
        $validator = \Validator::make(
            $request->all(),
            [
                'password' => 'required|confirmed|same:password_confirmation',
            ]
        );

        if ($validator->fails()) {
            $messages = $validator->getMessageBag();

            return redirect()->back()->with('error', $messages->first());
        }


        $user= User::where('id', decrypt($id))->first();
        $user->forceFill([
            'password' => Hash::make($request->password),
            'is_login_enable' => 1,
        ])->save();

        return redirect()->route('employee.index')->with(
            'success',
            'Employee Password successfully updated.'
        );
    }