<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\PublicHoliday;
use Illuminate\Validation\Rule;
class LeaveController extends Controller
{
    
    public function index(Request $request)
    {
        $query = PublicHoliday::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 . '%');
            });
        }
        return $this->withCount($query,'Get Holiday List Successfully');
    }


    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(), [
            'holiday_name' => [
                'required',
                'string',
                Rule::unique('public_holidays', 'title')
                    ->where(function ($query) use ($auth_id, $workspace_id) {
                        return $query->where('customer_id', $auth_id)
                                     ->where('workspace_id', $workspace_id);
                    }),
            ],
            'description' => 'required|string',
            'start_date' => 'required|date',
            'required_hours' => 'required|numeric',
            'end_date' => 'required|date|after_or_equal:start_date',
        ]);
 
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        } else {
           $validatedData =  $validator->validated();
           PublicHoliday::insert([
            'title' =>$validatedData['holiday_name'],
            'description' => $validatedData['description'],
            'from' => $validatedData['start_date'],
            'hours' => $validatedData['required_hours'],
            'to' => $validatedData['end_date'],
            'customer_id' => $auth_id,
            'workspace_id' => $workspace_id,
        ]);
        $data = PublicHoliday::where('customer_id',$auth_id)->where('workspace_id',$workspace_id)->get();
        return $this->success($data, 'Holiday Saved Successfully');
        }      

    }

    public function edit($id)
    {
        $publicholiday = PublicHoliday::find($id);
        if (!$publicholiday) {
            return $this->message('The Public Holiday 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 Public Holiday', 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 Public Holiday', 403);
        }
        return $this->success($publicholiday, ' Public Holiday 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(), [
            'holiday_name' => 'required|string|unique:public_holidays,title,' . $id . ',id,customer_id,' . $auth_id . ',workspace_id,' . $workspace_id,
            'description' => 'required|string',
            'start_date' => 'required|date',
            'required_hours' => 'required|numeric',
            'end_date' => 'required|date|after_or_equal:start_date',
        ]);
    
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        } else {
             $publicholiday = PublicHoliday::find($id);
             if (!$publicholiday) {
                return $this->message('The Leave Type  with the specified ID does not exist.',404); 
            }
            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 Public Holiday', 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 Public Holiday', 403);
            }

           
            $validatedData =  $validator->validated();
            $publicholiday->update([
                'title' =>$validatedData['holiday_name'],
                'description' => $validatedData['description'],
                'from' => $validatedData['start_date'],
                'hours' => $validatedData['required_hours'],
                'to' => $validatedData['end_date'],
                'customer_id' => $auth_id,
                'workspace_id' => $workspace_id,
            ]);
            $data = PublicHoliday::where('customer_id',$auth_id)->where('workspace_id',$workspace_id)->get();
            return $this->success($data, 'Holiday Saved Successfully');
        }
    }
    
    public function destroy($id)
    {
        $publicholiday = PublicHoliday::where('id',$id)->first();
        if (!$publicholiday) {
            return $this->message('The Public Holiday 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 Public Holiday', 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 Public Holiday', 403);
        }
        PublicHoliday::where('id',$id)->delete();
        return $this->message('Holiday Deleted Successfully', 200);    
    }

    public function holidaydesc($id)
    {
        
        $data = PublicHoliday::findOrFail($id);
        return response()->json([
            'data'   => $data
        ],200);
    }
}
