<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\EmployeeImage;
use App\Models\Organization;
// use App\Models\Designation;
use App\Models\RoleUserBy;
use App\Models\User;
use App\Traits\UploadAble;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class EmployeeController extends Controller
{
     //use UploadAble;

    public function index() {
        if (auth()->id() != 1) {
            $employees = Employee::orderBy('id', 'desc')->get();
            // ->whereIn('iDD', $iDDs) ---> array()
        } else {
            $employees = Employee::orderBy('id', 'desc')->get();
            // where('disposal_status', 0)->
        }
        // return $this->through('designations')->has('employees_records'); exit;
        return view('backend.employee.index', compact('employees'));
    }

    public function create(Request $request) {
        if (auth()->id() == 1) {
            $organizations = Organization::all()->where('is_main', '=', 1)->pluck('name', 'id');
        } else {
            $organizations = User::findOrfail(auth()->id())->where('is_main', '=', 1)->organizations->pluck('name', 'id');
        }
        if (auth()->id() === 1) {
            $branchs = Organization::all()->where('is_main', '=', 0)->pluck('name', 'id');
        } else {
            $branchs = User::findOrfail(auth()->id())->where('is_main', '=', 0)->organizations->pluck('name', 'id');
        }

        $employees = Employee::where('employee_name', '!=', '')->pluck('employee_name', 'id');
        // $designations = Designation::all();
        $designations = DB::table('designations')->select('name', 'id')->get();
        $departments = DB::table('departments')->select('department_name', 'department_id')->get();
        return view('backend.employee.create', compact('organizations', 'branchs', 'employees', 'designations', 'departments'));
    }

    public function store(Request $request): RedirectResponse {
        $this->validate($request, [
            'employee_name' => 'required',
            'organization_id' => 'required',
            'rec_org_id' => 'required',
            'rec_designation' => 'required',
            'rec_department' => 'required',
            'email' => 'string|email|max:255|unique:employees',
            'sex' => 'required',
            'birth_date' => 'required',
            // 'status' => 'required',
            'employee_image.*' => 'file|max:10000',
            'profile_picture' => 'image|mimes:jpeg,png,jpg,gif|max:10240' // max 10MB
        ]);

        $uploadedFile = $request->profile_picture;
        if ($uploadedFile) {
            $imageName = time().$uploadedFile->getClientOriginalName();
            $uploadedFile->move(storage_path('app/public/employee_images'), $imageName);
        } else {
            $imageName = $employee->employee_image;
        }

        $id = DB::table('employees')->insertGetId([
            'employee_name' => $request->employee_name,
            'organization_id' => $request->organization_id,
            'joining_date' => ($request->joining_date) ? Carbon::createFromFormat('d-m-Y', $request->joining_date)->format('Y-m-d') : null,
            'birth_date' => ($request->birth_date) ? Carbon::createFromFormat('d-m-Y', $request->birth_date)->format('Y-m-d') : null,
            'sex' => $request->sex,
            'employee_image' => $imageName,
            'father_name' => $request->father_name,
            'mother_name' => $request->mother_name,
            'present_address' => $request->present_address,
            'permanent_address' => $request->permanent_address,
            'email' => $request->email,
            'mobile_no' => $request->mobile_no,
            'nid_no' => $request->nid_no,
            'branch_id' => $request->rec_org_id,
            'designation_id' => $request->rec_designation,
            'department_id' => $request->rec_department,
            'added_on' => date('Y-m-d H:i:s'),
            'added_by' => Auth::user()->id
        ]);

        $rec_id = DB::table('employees_records')->insertGetId([
            'employee_id' => $id,
            'rec_date' => ($request->rec_date) ? Carbon::createFromFormat('d-m-Y', $request->rec_date)->format('Y-m-d') : null,
            'rec_type' => $request->rec_type,
            'rec_org_id' => $request->rec_org_id,
            'rec_designation' => $request->rec_designation,
            'rec_department' => $request->rec_department,
            'created_by' => Auth::user()->id,
        ]);

        if ($request->has('employee_image')) {
            foreach ($request->employee_image as $images) {
                $imageName = time().$images->getClientOriginalName();
                $images->move(storage_path('app/public/employee_images'), $imageName);// Eta OK Ace
                // $imageName = $this->uploadOne($images, 'employee_images');// Eta Server e Problem Kore
                $employee_image = new EmployeeImage();
                $employee_image->employee_id = $employee->id;
                $employee_image->image = $imageName;
                $employee_image->save();
            }
        }

        return redirect()->route('employees.index')->with(['alert-type' => 'success', 'message' => 'Employee has been inserted successfully!!']);
    }

    public function show(int $id): View {

        $employee = Employee::with('employee_images')->findOrFail($id);
        // $jobsRecord = Employee::with('employeeRecords')->with('designation')->with('department')->where('id', $id)->get();
        // echo '<pre>'; print_r($employee); //exit;
         $jobsRecord = DB::table('employees as ei')->leftJoin('employees_records as er', 'er.employee_id', '=', 'ei.id')
         ->leftJoin('organizations as org', 'org.id', '=', 'er.rec_designation')
         ->leftJoin('designations as dsg', 'dsg.id', '=', 'er.rec_designation')
         ->leftJoin('departments as dpt', 'dpt.department_id', '=', 'er.rec_department')
         ->select('er.*', 'dsg.name AS designation_name', 'dpt.department_name', 'org.name AS org_name')
        ->orderBy('er.rec_id', 'ASC')->where('ei.id', $id)
        ->get();

        return view('backend.employee.show', compact('employee', 'jobsRecord'));
    }

    public function edit(int $id): View {
        if (auth()->id() === 1) {
            $organizations = Organization::all()->where('is_main', '=', 1)->pluck('name', 'id');
        } else {
            $organizations = User::findOrfail(auth()->id())->where('is_main', '=', 1)->organizations->pluck('name', 'id');
        }

        if (auth()->id() === 1) {
            $branchs = Organization::all()->where('is_main', '=', 0)->pluck('name', 'id');
        } else {
            $branchs = User::findOrfail(auth()->id())->where('is_main', '=', 0)->organizations->pluck('name', 'id');
        }
        // $employee = Employee::findOrFail($id);
        // ->leftJoin('employees_records as er', function($join) {
        //     $join->on('ei.id', '=', 'er.employee_id')
        //          ->on('er.released_on', 'IS', NULL);
        // })
        // ->whereNull('er.released_on')

        $employee = DB::table('employees as ei')->leftJoin('employees_records as er', 'er.employee_id', '=', 'ei.id')
        ->orderBy('er.rec_id', 'DESC')->where('ei.id', $id)->first();
        $designations = DB::table('designations')->select('name', 'id')->get();
        $departments = DB::table('departments')->select('department_name', 'department_id')->get();
        return view('backend.employee.edit', compact('organizations', 'branchs', 'employee', 'designations', 'departments'));
    }

    public function update(Request $request, int $id) {
        $this->validate($request, [
            'employee_name' => 'required',
            'organization_id' => 'required',
            'rec_org_id' => 'required',
            'rec_designation' => 'required',
            'rec_department' => 'required',
            'email' => 'string|email|max:255|unique:employees,email,' . $id,
            'sex' => 'required',
            'birth_date' => 'required',
            // 'status' => 'required',
            'employee_image.*' => 'file|max:10000',
            'profile_picture' => 'image|mimes:jpeg,png,jpg,gif|max:10240' // max 10MB
        ]);

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

        $uploadedFile = $request->profile_picture;
        if ($uploadedFile) {

            $fileWithPath = $_SERVER['DOCUMENT_ROOT'].'/storage/employee_images/'.$employee->employee_image;
            if(file_exists("$fileWithPath")) {
                unlink("$fileWithPath");
            }

            $imageName = time().$uploadedFile->getClientOriginalName();
            $uploadedFile->move(storage_path('app/public/employee_images'), $imageName);
        } else {
            $imageName = $employee->employee_image;
        }

        $employee->update([
            'organization_id' => $request->organization_id,
            'employee_name' => $request->employee_name,
            'joining_date' => ($request->joining_date) ? Carbon::createFromFormat('d-m-Y', $request->joining_date)->format('Y-m-d') : null,
            'birth_date' => ($request->birth_date) ? Carbon::createFromFormat('d-m-Y', $request->birth_date)->format('Y-m-d') : null,
            'sex' => $request->sex,
            'employee_image' => $imageName,
            'father_name' => $request->father_name,
            'mother_name' => $request->mother_name,
            'present_address' => $request->present_address,
            'permanent_address' => $request->permanent_address,
            'email' => $request->email,
            'mobile_no' => $request->mobile_no,
            'nid_no' => $request->nid_no,
            // 'status' => $request->status,
            'branch_id' => $request->rec_org_id,
            'department_id' => $request->rec_department,
            'designation_id' => $request->rec_designation,
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => Auth::user()->id
        ]);

        DB::table('employees_records')
        ->where('employee_id', $id)
        ->update([
            'rec_date' => (($request->rec_date) ? Carbon::createFromFormat('d-m-Y', $request->rec_date)->format('Y-m-d') : null),
            'rec_type' => $request->rec_type,
            'rec_org_id' => $request->rec_org_id,
            'rec_designation' => $request->rec_designation,
            'rec_department' => $request->rec_department,
            'updated_by' => Auth::user()->id
        ]);

        if ($request->has('employee_image')) {
            $docData = DB::table('employee_images')->where('employee_id', $employee->id)->get();
            if ($docData) {
                foreach ($docData as $val) {
                    $fileWithPath = $_SERVER['DOCUMENT_ROOT'].'/storage/employee_images/'.$val->image;
                    if(file_exists("$fileWithPath")) {
                        unlink("$fileWithPath");
                    }
                }
                DB::table('employee_images')->where('employee_id', $employee->id)->delete();
            }

            foreach ($request->employee_image as $images) {
                $imageName = time().$images->getClientOriginalName();
                $images->move(storage_path('app/public/employee_images'), $imageName);// Eta OK Ace
                // $imageName = $this->uploadOne($images, 'employee_images');// Eta Server e Problem Kore
                $employee_image = new EmployeeImage();
                $employee_image->employee_id = $employee->id;
                $employee_image->image = $imageName;
                $employee_image->save();
            }
        }

        return redirect()->route('employees.index')->with(['alert-type' => 'success', 'message' => 'Employee has been updated successfully!!']);
    }

    public function destroy($id): RedirectResponse {
        DB::table('employees_records')->where('employee_id', $id)->delete();

        $employee = Employee::findOrFail($id);
        $fileWithPath = $_SERVER['DOCUMENT_ROOT'].'/storage/employee_images/'.$employee->employee_image;
        if(file_exists("$fileWithPath")) {
            unlink("$fileWithPath");
        }

        $employee_images = EmployeeImage::where('employee_id', $id)->get();
        if($employee_images)
        foreach ($employee_images as $c_img) {
            if ($c_img->image !== null) {
                $this->deleteOne($c_img->image);
            }
            $c_img->delete();
        }
        $employee->delete();
        return redirect()->back()->with(['alert-type' => 'success', 'message' => 'Employee successfully deleted']);
    }

    public function imageDestroy($id): RedirectResponse {
        $employee_image = EmployeeImage::findOrFail($id);
        if ($employee_image->image !== null) {
            $this->deleteOne($employee_image->image);
        }
        $employee_image->delete();
        return redirect()->back()->with(['alert-type' => 'success', 'message' => 'Image deleted successfully']);
    }
}
