<?php

namespace App\Http\Controllers;

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

class LeavePackageController extends Controller
{
    public function __construct()
    {
        $this->middleware('Permissions:Leave Package Maintain')->only(['create', 'edit']);
    }


    
    public function index(Request $request)
    {
        $query = LeavePackage::query();
        $query = $this->applyCustomerWorkspaceFilter($query);
        $query->with('leaveType');
        // Apply search and is_paid filter in one query
        $query->where(function ($q) use ($request) {
            // Search functionality
            if ($request->filled('search')) {
                $searchTerm = $request->search;
                $q->where(function ($subQ) use ($searchTerm) {
                    $subQ->where('title', 'like', '%' . $searchTerm . '%')
                        ->orWhereHas('leaveType', function ($subquery) use ($searchTerm) {
                            $subquery->where('title', 'like', '%' . $searchTerm . '%');
                        });
                });
            }
            // is_paid filter
            if ($request->filled('is_paid')) {
                $isPaid = $request->is_paid;
                if ($isPaid === 'paid' || $isPaid === '1') {
                    $q->where('is_paid', 1);
                } elseif ($isPaid === 'unpaid' || $isPaid === '0') {
                    $q->where('is_paid', 0);
                } else {
                    $q->where('is_paid', $isPaid);
                }
            }
        });
    
        return $this->withCount($query,'Get Leave Package List Successfully');
    }

  

    public function create(Request $request)
    {
        $leave_types =  LeaveType::orderBy('id', 'DESC')->get();
        $employee_roles =  Role::where('del','0')->get();
        return view('LeavePackage.create',compact('leave_types','employee_roles'));
    }

   
    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_package' => [
                'required',
                'string',
                Rule::unique('leave_packages', 'title')
                    ->where(function ($query) use ($auth_id, $workspace_id) {
                        return $query->where('customer_id', $auth_id)
                                     ->where('workspace_id', $workspace_id);
                    }),
            ],
            'leave_type' => 'required',
            'leave_number' => 'required',
            'is_paid' => 'nullable',
            'color_code' => 'nullable',
            'renew_on' => 'nullable',
            'employee_roles.*' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        } else {
          
           $validatedData =  $validator->validated();
           $validatedData['is_paid'] = $validatedData['is_paid'] ? 1 : 0;
           LeavePackage::create([
            'title' =>$validatedData['leave_package'],
            'leave_type_id' => $validatedData['leave_type'],
            'leave_number' => $validatedData['leave_number'],
            'color_code' => $validatedData['color_code'],
            'renew_on' => $validatedData['renew_on'],
            'employee_roles' => implode(",",$validatedData['employee_roles']),
            'customer_id' => $auth_id,
            'workspace_id' => $workspace_id,
            'is_paid' => $validatedData['is_paid'],
           
        ]);
        $data = LeavePackage::where('customer_id',$auth_id)->where('workspace_id',$workspace_id)->orderBy('created_at', 'desc')->get();
        return $this->success($data, 'Leave Package Saved Successfully');
        } 
    }

    public function show(LeavePackage $leavePackage)
    {
        //
    }

    public function leavePackageEdit($id)
    {
       
        $leavePackage = leavePackage::where('id',$id)->first();
        if (!$leavePackage) {
            return $this->message('The Leave Package with the specified ID does not exist.',404); 
        }
       
        $userTable = $this->getUserTable();
        if ($userTable == "customer" && ($leavePackage->workspace_id != auth()->user()->current_workspace_id || $leavePackage->customer_id != auth()->user()->id)) 
        {
            return $this->message('You do not have access to this Leave Package', 403);
        }
        if ($userTable == "emp" && ($leavePackage->customer_id != auth()->user()->customer_id || $leavePackage->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this Leave Package', 403);
        }
        return $this->success($leavePackage, 'Leave Package Successfully List');
    }

   
    public function update(Request $request, $id)
    {
        $leavePackage = LeavePackage::find($id);
        if (!$leavePackage) {
            return $this->message('The Leave Package with the specified ID does not exist.', 404);
        }

        $userTable = $this->getUserTable();
        if ($userTable == "customer" && ($leavePackage->workspace_id != auth()->user()->current_workspace_id || $leavePackage->customer_id != auth()->user()->id)) {
            return $this->message('You do not have access to this Leave Package', 403);
        }
        if ($userTable == "emp" && ($leavePackage->customer_id != auth()->user()->customer_id || $leavePackage->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this Leave Package', 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;
        }

        $validator = Validator::make($request->all(), [
            'leave_package' => [
                'required',
                'string',
                Rule::unique('leave_packages', 'title')
                    ->where(function ($query) use ($auth_id, $workspace_id) {
                        return $query->where('customer_id', $auth_id)
                                    ->where('workspace_id', $workspace_id);
                    })
                    ->ignore($id), // Ignore the current record
            ],
            'leave_type' => 'required',
            'leave_number' => 'required',
            'is_paid' => 'nullable',
            'color_code' => 'nullable',
            'renew_on' => 'nullable',
            'employee_roles.*' => 'required'
        ]);
    
        if ($validator->fails()) {
          return $this->handleValidationFailure($validator);
        } else {
          
            $leavePackage = leavePackage::find($id);
            $userTable = $this->getUserTable();
            if (!$leavePackage) {
                return $this->message('The Leave Package  with the specified ID does not exist.',404); 
            }
            $userTable = $this->getUserTable();
            if ($userTable == "customer" && ($leavePackage->workspace_id != auth()->user()->current_workspace_id || $leavePackage->customer_id != auth()->user()->id)) 
            {
                return $this->message('You do not have access to this Leave Package', 403);
            }
            if ($userTable == "emp" && ($leavePackage->customer_id != auth()->user()->customer_id || $leavePackage->workspace_id != auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this Leave Package', 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();
            $validatedData['is_paid'] = $validatedData['is_paid'] ? 1 : 0;
            $leavePackage->update([
                'title' =>$validatedData['leave_package'],
                'leave_type_id' => $validatedData['leave_type'],
                'leave_number' => $validatedData['leave_number'],
                'color_code' => $validatedData['color_code'],
                'renew_on' => $validatedData['renew_on'],
                'employee_roles' => implode(",",$validatedData['employee_roles']),
                'customer_id' => $auth_id,
                'workspace_id' => $workspace_id,
                'is_paid' => $validatedData['is_paid'],
            ]);
    
            $data = leavePackage::where('id',$id)->get();
            return response()->json([
                'message' => 'Leave Package Updated Successfully',
                'data' => $data
            ], 200);
        }
    }

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