<?php

namespace App\Http\Controllers;

use App\Departments;
use App\Designations;
use App\Employees;
use App\Http\Controllers\Controller;
use App\User;
use GPBMetadata\Google\Api\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class EmployeesController extends Controller
{
      protected string $module = 'Employees';

    public function __construct()
    {
        $module = $this->module;

        $this->middleware("permission:$module list")->only(['index']);
        $this->middleware("permission:$module view")->only(['show']);
        $this->middleware("permission:$module add")->only(['create', 'store']);
        $this->middleware("permission:$module edit")->only(['edit', 'update']);
        $this->middleware("permission:$module delete")->only(['destroy']);
    }
    // public function check_role_permission()
    // {
    //     $get_role_id = auth()->user()->role_id;
    //     $noti_create_inquiry = role_permission::where('role_id', $get_role_id)->where('menu_id', 103)->first();
    //     $noti_create_quotation = role_permission::where('role_id', $get_role_id)->where('menu_id', 103)->first();
    //     if ($noti_create_inquiry) {
    //         $noti_array[] = 'self_inquiry';
    //     } elseif ($noti_create_quotation) {
    //         $noti_array[] = "create_quotation";
    //     } elseif ($noti_create_quotation) {
    //         $noti_array[] = "send_quotation_to_approval";
    //     } elseif ($noti_create_quotation) {
    //         $noti_array[] = "inquiry_remarks";
    //     } elseif ($noti_create_quotation) {
    //         $noti_array[] = "quotation_remarks";
    //     } else {
    //         $noti_array = [];
    //     }
    //     return  $noti_array;
    // }

    public function index()
    {
        $employees = Employees::with(['department', 'designation'])->get();
        return view('Employees.index', compact('employees'));
    }
    public function create()
    {
        $departments = Departments::where('status','active')->get();
        $designations = Designations::with('department')->where('status','active')->get();
        return view('Employees.create', compact('departments', 'designations'));
    }

    public function store(Request $request)
    {
        // dd($request->all());
        // $request->validate([
        //     'employee_name' => 'string|max:255',
        //     'employee_no' => 'string|max:255',
        //     'employee_email' => 'nullable|string|max:255',
        //     'employee_address' => 'nullable|string|max:255',
        //     'phone_1' => 'nullable|string|max:255',
        //     'phone_2' => 'nullable|string|max:255',
        //     'department' => 'string|max:255',
        // ]);
        // $store = new Employees();
        // $store->employee_name = $request->employee_name;
        // $store->employee_no = $request->employee_no;
        // $store->employee_email = $request->employee_email;
        // $store->employee_address = $request->employee_address;
        // $store->employee_phone1 = $request->phone_1;
        // $store->employee_phone2 = $request->phone_2;
        // $store->department_id = $request->department;
        // $store->city_id = $request->city;
        // // $store->emp_type = $request->employee_type;
        // $store->status = $request->status;
        // // $store->status = "1"; // It Means Active
        // $store->employee_created_by = Auth()->User()->id;
        // // dd($store);
        // $store->save();
        // session()->flash('success', "New Employee Added Successfully");

        // return redirect('employee');
        $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'nullable|string|max:255',
            'dob' => 'nullable|date',
            'gender' => 'nullable|string|in:male,female,other',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255|unique:users,email',
            'department_id' => 'nullable|exists:departments,id',
            'designation_id' => 'nullable|exists:Designations,id',
            'joining_date' => 'nullable|date',
            'basic_salary' => 'nullable|numeric|min:0',
            'status' => 'required|in:active,inactive,terminated'
        ]);

        try {
            DB::transaction(function () use ($request) {


                $latest = Employees::lockForUpdate()->latest('id')->first();
                $number = $latest ? $latest->id + 1 : 1;
                $employee_no = 'EMP' . str_pad($number, 5, '0', STR_PAD_LEFT);
                $getDesignation = Designations::where('id', $request->designation_id)->where('status', 'active')->first();

                Employees::create([
                    'employee_no' => $employee_no,
                    'first_name' => $request->first_name,
                    'last_name' => $request->last_name,
                    'dob' => $request->dob,
                    'gender' => $request->gender,
                    'phone' => $request->phone,
                    'email' => $request->email,
                    'department_id' => $getDesignation->department_id,
                    'designation_id' => $request->designation_id,
                    'joining_date' => $request->joining_date,
                    'basic_salary' => $request->basic_salary ?? 0,
                    'status' => $request->status,
                    'created_by' => auth()->id() ?? null,
                ]);
            });

            return redirect()->route('employees.index')->with('success', 'Employee created successfully!');
        } catch (\Exception $e) {
            return back()->withInput()->with('error', 'Something went wrong: ' . $e->getMessage());
        }
    }

    public function edit($id)
    {
        // $dec_id = \Crypt::decrypt($id);
        // $edit = Employees::where('id_employee', $dec_id)->first();
        // // dd($edit);
        // return view('employees.edit', compact('edit'));
        try {
            $dec_id = Crypt::decrypt($id);
            $edit = Employees::findOrFail($dec_id);
           $departments = Departments::where('status','active')->get();
        $designations = Designations::with('department')->where('status','active')->get();
            return view('Employees.edit', compact('edit', 'departments', 'designations'));
        } catch (\Exception $e) {
            return redirect()->route('employees.index')->with('error', 'Employee not found!');
        }
    }

    public function update(Request $request, $id)
    {
        // $request->validate([
        //     'employee_name' => 'string|max:255',
        //     'employee_no' => 'string|max:255',
        //     'employee_email' => 'nullable|string|max:255',
        //     'employee_address' => 'nullable|string|max:255',
        //     'phone_1' => 'nullable|string|max:255',
        //     'phone_2' => 'nullable|string|max:255',
        //     'department' => 'string|max:255',
        // ]);
        // $dec_id = \Crypt::decrypt($id);
        // $update = Employees::where('id_employee', $dec_id)->first();
        // $update->employee_name = $request->employee_name;
        // $update->employee_no = $request->employee_no;
        // $update->employee_email = $request->employee_email;
        // $update->employee_address = $request->employee_address;
        // $update->employee_phone1 = $request->phone_1;
        // $update->employee_phone2 = $request->phone_2;
        // $update->department_id = $request->department;
        // $update->city_id = $request->city;
        // // $update->emp_type = $request->employee_type;
        // $update->status = $request->status;
        // $update->save();
        // // dd($ update);

        // session()->flash('info', "Employee Updated Successfully");

        // return redirect('employee');
        $dec_id = \Crypt::decrypt($id);
        $employee = Employees::findOrFail($dec_id);
        $getDesignation = Designations::where('id', $request->designation_id)->where('status', 'active')->first();

        $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'nullable|string|max:255',
            'dob' => 'nullable|date',
            'gender' => 'nullable|string|in:male,female,other',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255|unique:users,email,' . $employee->user_id,
            'department_id' => 'nullable|exists:departments,id',
            'designation_id' => 'nullable|exists:Designations,id',
            'joining_date' => 'nullable|date',
            'basic_salary' => 'nullable|numeric|min:0',
            'status' => 'required|in:active,inactive,terminated',
        ]);

        try {
            DB::transaction(function () use ($request, $employee,$getDesignation) {

                // Update Employee record
                $employee->update([
                    'first_name' => $request->first_name,
                    'last_name' => $request->last_name,
                    'dob' => $request->dob,
                    'gender' => $request->gender,
                    'phone' => $request->phone,
                    'email' => $request->email,
                    'department_id' => $getDesignation->department_id,
                    'designation_id' => $request->designation_id,
                    'joining_date' => $request->joining_date,
                    'basic_salary' => $request->basic_salary ?? 0,
                    'status' => $request->status,
                    'updated_at' => now(),
                ]);
            });

            return redirect()->route('employees.index')->with('success', 'Employee updated successfully!');
        } catch (\Exception $e) {
            return back()->withInput()->with('error', 'Something went wrong: ' . $e->getMessage());
        }
    }

    public function destroy($id)
    {
        // $Employees = Employees::findOrFail($id);
        // $Employees->delete();
        // session()->flash('warning', "Employee Removed!");
        // return redirect()->back();
        try {
            $employee = Employees::findOrFail($id);
            $employee->delete();
            return redirect()->route('employees.index')->with('success', 'Employee deleted successfully!');
        } catch (\Exception $e) {
            return redirect()->route('employees.index')->with('error', 'Something went wrong: ' . $e->getMessage());
        }
    }
}
