<?php

namespace App\Http\Controllers;

use App\Models\LeaveType;
use DB;
use Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Http\Request;

class LeaveTypeController extends Controller
{

    public function index(Request $request)
    {
        $query = LeaveType::query();
        $query = $this->applyCustomerWorkspaceFilter($query);
        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $query->where(function ($q) use ($searchTerm) {
                $q->where('title', 'like', '%' . $searchTerm . '%')
                    ->orWhere('description', 'like', '%' . $searchTerm . '%')
                    ->orWhere('leave_hours', 'like', '%' . $searchTerm . '%');
            });
        }
        return $this->withCount($query, 'Get Leave Type List Successfully');
    }


    public function create()
    {
        //
    }


    public function store(Request $request)
    {
        $userTable = $this->getUserTable();
        $auth_id = 0;
        $workspace_id = 0;
        if ($userTable === "customer") {
            $auth_id = Auth::user()->id;
            $workspace_id = Auth::user()->current_workspace_id;
        }
        if ($userTable === "emp") {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
        }
        //  $validator = Validator::make($request->all(), [
        //     'leave_type' => 'required|string|unique:leave_types,title',
        //     'description' => 'required|string',

        // ]);
        $validator = Validator::make($request->all(), [
            'leave_type' => [
                'required',
                'string',
                Rule::unique('leave_types', 'title')
                    ->where(function ($query) use ($auth_id, $workspace_id) {
                        return $query->where('customer_id', $auth_id)
                            ->where('workspace_id', $workspace_id);
                    }),
            ],
            'description' => 'required|string',
            'leave_hours' => 'nullable|numeric',
        ]);

        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        } else {

            $validatedData =  $validator->validated();


            LeaveType::insert([
                'title' => $validatedData['leave_type'],
                'description' => $validatedData['description'],
                'leave_hours' => $validatedData['leave_hours'],
                'customer_id' => $auth_id,
                'workspace_id' => $workspace_id,
            ]);

            $data = LeaveType::where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->get();
            return $this->success($data, 'Leave Type Saved Successfully');
        }
    }


    public function show(LeaveType $leaveType)
    {
        //
    }


    public function edit($id)
    {
        $publicholiday = LeaveType::where('id', $id)->first();
        if (!$publicholiday) {
            return $this->message('The Leave Type  with the specified ID does not exist.', 404);
        }

        $userTable = $this->getUserTable();
        if ($userTable == "customer" && ($publicholiday->workspace_id != auth()->user()->current_workspace_id || $publicholiday->customer_id != auth()->user()->id)) {
            return $this->message('You do not have access to this Leave Type', 403);
        }
        if ($userTable == "emp" && ($publicholiday->customer_id != auth()->user()->customer_id || $publicholiday->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this Leave Type', 403);
        }
        return $this->success($publicholiday, ' Leave Type Successfully List');
    }

    public function updatePublicHoliday(Request $request, $id)
    {
        $userTable = $this->getUserTable();
        $auth_id = 0;
        $workspace_id = 0;
        if ($userTable === "customer") {
            $auth_id = Auth::user()->id;
            $workspace_id = Auth::user()->current_workspace_id;
        }
        if ($userTable === "emp") {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
        }
        $validator = Validator::make($request->all(), [
            'leave_type' => 'required|string|unique:leave_types,title,' . $id . ',id,customer_id,' . $auth_id . ',workspace_id,' . $workspace_id,
            'description' => 'required|string',
            'leave_hours' => 'nullable|numeric',
        ]);

        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        } else {
            $publicholiday = LeaveType::find($id);
            if (!$publicholiday) {
                return $this->message('The Leave Type  with the specified ID does not exist.', 404);
            }
            $userTable = $this->getUserTable();
            if ($userTable == "customer" && ($publicholiday->workspace_id != auth()->user()->current_workspace_id || $publicholiday->customer_id != auth()->user()->id)) {
                return $this->message('You do not have access to this Leave Type', 403);
            }
            if ($userTable == "emp" && ($publicholiday->customer_id != auth()->user()->customer_id || $publicholiday->workspace_id != auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this Leave Type', 403);
            }
            $auth_id = 0;
            $workspace_id = 0;
            if ($userTable === "customer") {
                $auth_id = Auth::user()->id;
                $workspace_id = Auth::user()->current_workspace_id;
            }
            if ($userTable === "emp") {
                $auth_id = auth()->user()->customer_id;
                $workspace_id = auth()->user()->workspace_id;
            }

            $validatedData =  $validator->validated();
            $publicholiday->update([
                'title' => $validatedData['leave_type'],
                'description' => $validatedData['description'],
                'leave_hours' => $validatedData['leave_hours'],
                'customer_id' => $auth_id,
                'workspace_id' => $workspace_id,
            ]);
            $data = LeaveType::where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->get();
            return $this->success($data, 'Leave Type Updated Successfully');
        }
    }


    public function destroy($id)
    {
        $publicholiday = LeaveType::where('id', $id)->first();
        if (!$publicholiday) {
            return $this->message('The Leave Type with the specified ID does not exist.', 404);
        }
        $userTable = $this->getUserTable();
        if ($userTable == "customer" && ($publicholiday->workspace_id != auth()->user()->current_workspace_id || $publicholiday->customer_id != auth()->user()->id)) {
            return $this->message('You do not have access to this Leave Type', 403);
        }
        if ($userTable == "emp" && ($publicholiday->customer_id != auth()->user()->customer_id || $publicholiday->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this Leave Type', 403);
        }
        LeaveType::where('id', $id)->delete();
        return $this->message('Leave Type Deleted Successfully', 200);
    }
    public function leavetypedesc($id)
    {
        $data = LeaveType::findOrFail($id);
        return response()->json([
            'data'   => $data
        ], 200);
    }
}
