<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use App\Models\User;
use App\Models\Sites;
use App\Models\Notification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Models\EmpCompanyDetails;
use App\Models\EmpPersonalDetails;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Services\NotificationPusherService;

class NotificationController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'employee_id' => 'required|exists:emp_company_details,id',
        ]);

        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return $this->error($error, 422);
        }

        $notifications = Notification::where('receiver_id', $request->employee_id)->get();

        foreach ($notifications as $notify) {
            // Convert PDF_LINK format to clickable links before stripping tags
            $description = $notify->short_description;
            $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
            $notify->short_description = $description;
        }

        return $this->success($notifications, 'Notification Get Successfully');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function clear_all_notifications(Request $request)
    {
        Notification::where('receiver_id', Auth::user()->id)->update(['read' => '1']);

        return $this->message('Notification Clear successfully');
    }

    public function create(Request $request)
    {
        $employees = EmpCompanyDetails::where('emp_company_details.del', 0)->join('emp_personal_details as epd', 'emp_company_details.id', 'epd.emp_id')->select('epd.id', 'epd.emp_id', 'epd.first_name', 'epd.middle_name', 'epd.last_name')->get();
        $sites = sitesList();
        $teams = DB::table('emp_teams')->get();
        return view('Notification.create', compact('employees', 'sites', 'teams'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'message' => 'required',
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return $this->error($errors);
        }
        $validatedData = $validator->validated();
        $userTable = $this->getUserTable();
        $auth_id = 0;
        $workspace_id = 0;
        if ($userTable === 'customer') {
            $auth_id = Auth::user()->id;
            $workspace_id = Auth::user()->current_workspace_id;
            $authPersonalDetails = User::where('id', Auth::user()->id)->first();
        }
        if ($userTable === 'emp') {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();
        }
        // Start transaction
        DB::beginTransaction();

        try {
            // Save notifications for employees
            if (isset($request->employee_ids) && count($request->employee_ids) > 0) {
                foreach ($request->employee_ids as $id) {
                    if ($id == 0) {
                                            $employee_ids = EmpCompanyDetails::where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->where('emp_company_details.del', 0)->join('emp_personal_details as epd', 'emp_company_details.id', 'epd.emp_id')->pluck('epd.emp_id');
                    // dd($employee_ids); // Debug statement commented out
                        foreach ($employee_ids as $emp_id) {
                            $notification = new Notification();
                            $notification->title = $request->title;
                            $notification->short_description = $request->message;
                            $notification->sender_id = Auth::user()->id;
                            $notification->receiver_id = $emp_id;
                            $notification->type = 'custom';
                            $notification->read = '0';
                            $notification->customer_id = $auth_id;
                            $notification->workspace_id = $workspace_id;
                            $notification->save();
                        }
                    } else {
                        $notification = new Notification();
                        $notification->title = $request->title;
                        $notification->short_description = $request->message;
                        $notification->sender_id = Auth::user()->id;
                        $notification->receiver_id = $id;
                        $notification->type = 'custom';
                        $notification->read = '0';
                        $notification->customer_id = $auth_id;
                        $notification->workspace_id = $workspace_id;
                        $notification->save();
                    }
                }
            }

            // Save notifications for sites
            if (isset($request->site_ids) && count($request->site_ids) > 0) {
                foreach ($request->site_ids as $id) {
                    if ($id == 0) {
                        $site_ids = Sites::where('active', 1)->where('del',0)->pluck('id');
                        foreach ($site_ids as $site_id) {
                            // For site notifications, we'll send to all employees at that site
                            $siteEmployees = EmpCompanyDetails::where('customer_id', $auth_id)
                                ->where('workspace_id', $workspace_id)
                                ->where('emp_company_details.del', 0)
                                ->join('emp_personal_details as epd', 'emp_company_details.id', 'epd.emp_id')
                                ->pluck('epd.emp_id');
                            
                            foreach ($siteEmployees as $emp_id) {
                                $this->save_notifications(
                                    $request->title,
                                    $request->message,
                                    'customer',
                                    Auth::user()->id,
                                    'emp',
                                    $emp_id,
                                    'custom',
                                    $auth_id,
                                    $workspace_id
                                );
                            }
                        }
                    } else {
                        // For specific site, send to all employees at that site
                        $siteEmployees = EmpCompanyDetails::where('customer_id', $auth_id)
                            ->where('workspace_id', $workspace_id)
                            ->where('emp_company_details.del', 0)
                            ->join('emp_personal_details as epd', 'emp_company_details.id', 'epd.emp_id')
                            ->pluck('epd.emp_id');
                        
                        foreach ($siteEmployees as $emp_id) {
                            $this->save_notifications(
                                $request->title,
                                $request->message,
                                'customer',
                                Auth::user()->id,
                                'emp',
                                $emp_id,
                                'custom',
                                $auth_id,
                                $workspace_id
                            );
                        }
                    }
                }
            }
            if (isset($request->notification_team_id) && count($request->notification_team_id) > 0) {
                // Use a collection to keep track of unique employee IDs and their team IDs
                $unique_emp_ids = collect();

                // Convert notification_team_id to a collection for easy manipulation
                $team_ids = collect($request->notification_team_id);

                // Loop through each team ID
                foreach ($team_ids as $id) {
                    if ($id == 0) {
                        // Get all unique team members when "0" is selected
                        // Here we get all employee IDs along with their team IDs
                        $emp_team_member_ids = DB::table('emp_teams_members')
                            ->where('del', '0')
                            ->get(['emp_id', 'team_id']); // Fetch both emp_id and team_id

                        // Add each emp_id with its corresponding team_id
                        foreach ($emp_team_member_ids as $member) {
                            $unique_emp_ids->push(['emp_id' => $member->emp_id, 'team_id' => $member->team_id]);
                        }
                    } else {
                        // Get unique team members for the selected team
                        $emp_team_member_ids = DB::table('emp_teams_members')
                            ->where('team_id', $id)
                            ->get(['emp_id']); // Only fetch emp_id, as team_id is known

                        // Add each emp_id with the corresponding team_id
                        foreach ($emp_team_member_ids as $member) {
                            $unique_emp_ids->push(['emp_id' => $member->emp_id, 'team_id' => $id]);
                        }
                    }
                }

                // Create notifications for each unique employee ID
                foreach ($unique_emp_ids->unique('emp_id') as $data) {
                    $this->save_notifications(
                        $request->title,
                        $request->message,
                        'customer',
                        Auth::user()->id,
                        'emp',
                        $data['emp_id'],
                        'custom',
                        $auth_id,
                        $workspace_id
                    );
                }
            }

            // Commit transaction if all records were inserted successfully
            DB::commit();
            Session::put('success', 'Notification Saved Successfull.');
            return $this->message('Notifications Saved Succefully');
        } catch (\Exception $e) {
            // Rollback transaction if there is any error
            DB::rollBack();

            return $this->error($e->getMessage(), 'Faild To Save the notification');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    function customNotification(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;
            $authPersonalDetails = User::where('id', Auth::user()->id)->first();
        }
        if ($userTable === 'emp') {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();
        }
        $query = Notification::query();

        if ($request->filled('filter')) {
            $query = $this->filter(json_decode($request->filter, true), $query);
        }

        $query->with(['sites', 'teams']);
        $start = $request->input('from', 0);
        $query->offset($start)->limit(10);
        $query->orderBy('id', 'desc');
        $query->where('customer_id', $auth_id);
        $query->where('workspace_id', $workspace_id);
        $notifications = $query->get();

        $sites = $sites = Sites::where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->where('active', 1)->where('del',0)->select('id', 'title', 'longitude', 'latitude', 'area_radius')->get();

        $data = [
            'notifications' => $notifications,
            'sites' => $sites,
        ];

        return $this->success($data, 'Tiers related data get successfully');
    }

    public function filter($filters, $query)
    {
        foreach ($filters as $filterName => $filterValue) {
            if ($filterValue != null || $filterValue != '') {
                switch ($filterName) {
                    case 'sender':
                        $filterValue = explode(' ', $filterValue);
                        if (count($filterValue) == 1) {
                            $query->where(function ($q) use ($filterValue) {
                                // For emp type: check EmpPersonalDetails
                                $q->where(function ($subq) use ($filterValue) {
                                    $subq->where('sender_type', 'emp')
                                        ->whereIn('sender_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('emp_id')
                                                ->from('emp_personal_details')
                                                ->where('first_name', 'like', '%' . $filterValue[0] . '%');
                                        });
                                })
                                // For customer/admin type: check User table
                                ->orWhere(function ($subq) use ($filterValue) {
                                    $subq->whereIn('sender_type', ['customer', 'admin'])
                                        ->whereIn('sender_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('id')
                                                ->from('users')
                                                ->where('name', 'like', '%' . $filterValue[0] . '%');
                                        });
                                });
                            });
                        }
                        if (count($filterValue) == 2) {
                            $query->where(function ($q) use ($filterValue) {
                                // For emp type: check EmpPersonalDetails
                                $q->where(function ($subq) use ($filterValue) {
                                    $subq->where('sender_type', 'emp')
                                        ->whereIn('sender_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('emp_id')
                                                ->from('emp_personal_details')
                                                ->where('first_name', 'like', '%' . $filterValue[0] . '%')
                                                ->where('last_name', 'like', '%' . $filterValue[1] . '%');
                                        });
                                })
                                // For customer/admin type: check User table (name as first_name)
                                ->orWhere(function ($subq) use ($filterValue) {
                                    $subq->whereIn('sender_type', ['customer', 'admin'])
                                        ->whereIn('sender_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('id')
                                                ->from('users')
                                                ->where('name', 'like', '%' . $filterValue[0] . '%');
                                        });
                                });
                            });
                        }
                        if (count($filterValue) == 3) {
                            $query->where(function ($q) use ($filterValue) {
                                // For emp type: check EmpPersonalDetails
                                $q->where(function ($subq) use ($filterValue) {
                                    $subq->where('sender_type', 'emp')
                                        ->whereIn('sender_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('emp_id')
                                                ->from('emp_personal_details')
                                                ->where('first_name', 'like', '%' . $filterValue[0] . '%')
                                                ->where('middle_name', 'like', '%' . $filterValue[1] . '%')
                                                ->where('last_name', 'like', '%' . $filterValue[2] . '%');
                                        });
                                })
                                // For customer/admin type: check User table (only name field available)
                                ->orWhere(function ($subq) use ($filterValue) {
                                    $subq->whereIn('sender_type', ['customer', 'admin'])
                                        ->whereIn('sender_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('id')
                                                ->from('users')
                                                ->where('name', 'like', '%' . $filterValue[0] . '%');
                                        });
                                });
                            });
                        }
                        break;
                    case 'receiver':
                        $filterValue = explode(' ', $filterValue);
                        if (count($filterValue) == 1) {
                            $query->where(function ($q) use ($filterValue) {
                                // For emp type: check EmpPersonalDetails
                                $q->where(function ($subq) use ($filterValue) {
                                    $subq->where('receiver_type', 'emp')
                                        ->whereIn('receiver_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('emp_id')
                                                ->from('emp_personal_details')
                                                ->where('first_name', 'like', '%' . $filterValue[0] . '%');
                                        });
                                })
                                // For customer/admin type: check User table
                                ->orWhere(function ($subq) use ($filterValue) {
                                    $subq->whereIn('receiver_type', ['customer', 'admin'])
                                        ->whereIn('receiver_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('id')
                                                ->from('users')
                                                ->where('name', 'like', '%' . $filterValue[0] . '%');
                                        });
                                });
                            });
                        }
                        if (count($filterValue) == 2) {
                            $query->where(function ($q) use ($filterValue) {
                                // For emp type: check EmpPersonalDetails
                                $q->where(function ($subq) use ($filterValue) {
                                    $subq->where('receiver_type', 'emp')
                                        ->whereIn('receiver_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('emp_id')
                                                ->from('emp_personal_details')
                                                ->where('first_name', 'like', '%' . $filterValue[0] . '%')
                                                ->where('last_name', 'like', '%' . $filterValue[1] . '%');
                                        });
                                })
                                // For customer/admin type: check User table (name as first_name)
                                ->orWhere(function ($subq) use ($filterValue) {
                                    $subq->whereIn('receiver_type', ['customer', 'admin'])
                                        ->whereIn('receiver_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('id')
                                                ->from('users')
                                                ->where('name', 'like', '%' . $filterValue[0] . '%');
                                        });
                                });
                            });
                        }
                        if (count($filterValue) == 3) {
                            $query->where(function ($q) use ($filterValue) {
                                // For emp type: check EmpPersonalDetails
                                $q->where(function ($subq) use ($filterValue) {
                                    $subq->where('receiver_type', 'emp')
                                        ->whereIn('receiver_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('emp_id')
                                                ->from('emp_personal_details')
                                                ->where('first_name', 'like', '%' . $filterValue[0] . '%')
                                                ->where('middle_name', 'like', '%' . $filterValue[1] . '%')
                                                ->where('last_name', 'like', '%' . $filterValue[2] . '%');
                                        });
                                })
                                // For customer/admin type: check User table (only name field available)
                                ->orWhere(function ($subq) use ($filterValue) {
                                    $subq->whereIn('receiver_type', ['customer', 'admin'])
                                        ->whereIn('receiver_id', function ($innerQuery) use ($filterValue) {
                                            $innerQuery->select('id')
                                                ->from('users')
                                                ->where('name', 'like', '%' . $filterValue[0] . '%');
                                        });
                                });
                            });
                        }
                        break;
                    case 'title':
                        $query->where('title', 'like', '%' . $filterValue . '%');
                        break;
                    case 'message':
                        $query->where('short_description', 'like', '%' . $filterValue . '%');
                        break;
                    case 'type':
                        $query->where('type', 'like', '%' . $filterValue . '%');
                        break;
                    case 'site':
                        $query->whereHas('sites', function ($subquery) use ($filterValue) {
                            $subquery->where('title', 'like', '%' . $filterValue[0] . '%');
                        });
                        break;
                    case 'team':
                        $query->whereHas('teams', function ($subquery) use ($filterValue) {
                            $subquery->where('title', 'like', '%' . $filterValue[0] . '%');
                        });
                        break;
                }
            }
        }
        return $query;
    }

    function notificationFiltersData()
    {
        $userTable = $this->getUserTable();
        $auth_id = 0;
        $workspace_id = 0;
        if ($userTable === 'customer') {
            $auth_id = Auth::user()->id;
            $workspace_id = Auth::user()->current_workspace_id;
            $authPersonalDetails = User::where('id', Auth::user()->id)->first();
        }
        if ($userTable === 'emp') {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();
        }
        $sites = Sites::where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->where('active', 1)->where('del',0)->select('id', 'title', 'longitude', 'latitude', 'area_radius')->get();
        $employees = EmpCompanyDetails::where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->where('emp_company_details.del', 0)->join('emp_personal_details as epd', 'emp_company_details.id', 'epd.emp_id')->select('epd.id', 'epd.emp_id', 'epd.first_name', 'epd.middle_name', 'epd.last_name')->get();
        $data['sites'] = $sites;
        $employees = $employees;
        return $this->success($employees, 'Get Notification Successfully');
    }

    /**
     * Get all notifications for the authenticated employee
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEmployeeNotifications()
    {
        $userId = Auth::user()->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;
            $authPersonalDetails = User::where('id', Auth::user()->id)->first();
        }
        if ($userTable === 'emp') {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();
        }
        if($userId == config('constants.superadmin') && $userTable == 'customer'){
            $userTable = 'admin';
        }
        $notifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $userId)
            ->where('receiver_type', $userTable)
            ->where('customer_id', $auth_id)
            ->where('workspace_id', $workspace_id)
            ->orderBy('created_at', 'desc')
            ->get();
        $notifications->transform(function ($notification) {
            if (isset($notification->short_description)) {
                // Convert PDF_LINK format to clickable links before stripping tags
                $description = $notification->short_description;
                $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
                $notification->short_description = $description;
            }
            // Add time parameter from created_at timestamp using BaseModel time format
            if ($notification->created_at) {
                try {
                    $rawTimestamp = $notification->getRawOriginal('created_at');
                    if ($rawTimestamp) {
                        $carbonDate = \Carbon\Carbon::parse($rawTimestamp);
                        $userTimeFormat = $notification->getUserTimeFormat();
                        $notification->time = $carbonDate->format($userTimeFormat);
                    }
                } catch (\Exception $e) {
                    // Fallback to default format if parsing fails
                    $notification->time = $notification->created_at ? \Carbon\Carbon::parse($notification->created_at)->format('H:i') : null;
                }
            }
            return $notification;
        });
        // Push a realtime summary update to the user's Pusher channel
        try {
            $unreadCount = Notification::where('receiver_id', $userId)
                ->where('receiver_type', $userTable)
                ->where('customer_id', $auth_id)
                ->where('workspace_id', $workspace_id)
                ->where('read', '0')
                ->count();

            $latest = Notification::where('receiver_id', $userId)
                ->where('receiver_type', $userTable)
                ->where('customer_id', $auth_id)
                ->where('workspace_id', $workspace_id)
                ->orderBy('created_at', 'desc')
                ->first();

            $pusherService = new NotificationPusherService();
            $pusherService->sendNotificationToUser([
                'receiver_id' => $userId,
                'receiver_type' => $userTable,
                'title' => $latest?->title ?? 'Notifications Updated',
                'short_description' => $latest?->short_description ?? 'You have ' . $unreadCount . ' notifications',
                'unread_count' => $unreadCount,
                'latest_id' => $latest?->id,
                'latest_type' => $latest?->type,
                'created_at' => optional($latest?->created_at),
            ]);
        } catch (\Throwable $e) {
            Log::error('Failed to push employee notification summary', ['error' => $e->getMessage()]);
        }

        return $this->success($notifications, 'Notifications retrieved successfully');
    }

    /**
     * Mark a specific notification as read
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function markNotificationAsRead(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'notification_id' => 'required|exists:all_notifications,id',
        ]);
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return $this->error($error, 422);
        }
        $userId = Auth::user()->id;
        $notification = Notification::where('id', $request->notification_id)
            ->where('receiver_id', $userId)
            ->first();
            
        if (!$notification) {
            return $this->error('Notification not found or does not belong to you', 404);
        }
        if($notification->read == 1){
            return $this->success('Notification already read!','Notification already read!');
        }
        $notification->read = '1';
        $notification->save();
        return $this->message('Notification marked as read successfully');
    }

    /**
     * Mark all notifications as read for the authenticated employee
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function markAllNotificationsAsRead()
    {
        try {
            $userId = Auth::user()->id;
            
            // Fetch all unread notifications using the same pattern as markNotificationAsRead
            $notifications = Notification::where('receiver_id', $userId)
                ->where('read', '0')
                ->get();
            
            $count = 0;
            // Update each notification individually using the same pattern that works
            foreach ($notifications as $notification) {
                $notification->read = '1';
                $notification->save();
                $count++;
            }
            
            $data = "Notifications marked as read successfully";
            return $this->success($data, "Notifications marked as read successfully");
        } catch (\Exception $e) {
            Log::error('Error marking all notifications as read: ' . $e->getMessage());
            Log::error('Stack trace: ' . $e->getTraceAsString());
            return $this->error('Failed to mark notifications as read: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get overtime notifications for the authenticated employee
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOvertimeNotifications()
    {
        $userId = Auth::user()->id;
        $notifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $userId)
            ->whereIn('type', [
                config('constants.notification_types.overtime_applied'),
                config('constants.notification_types.overtime_approved'),
                config('constants.notification_types.overtime_rejected')
            ])
            ->orderBy('created_at', 'desc')
            ->get();

        $notifications->transform(function ($notification) {
            if (isset($notification->short_description)) {
                // Convert PDF_LINK format to clickable links before stripping tags
                $description = $notification->short_description;
                $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
                $notification->short_description = $description;
            }
            return $notification;
        });

        return $this->success($notifications, 'Overtime notifications retrieved successfully');
    }

    /**
     * Get unread overtime notification count for the authenticated employee
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnreadOvertimeNotificationCount()
    {
        $userId = Auth::user()->id;
        $count = Notification::where('receiver_id', $userId)
            ->where('read', '0')
            ->whereIn('type', [
                config('constants.notification_types.overtime_applied'),
                config('constants.notification_types.overtime_approved'),
                config('constants.notification_types.overtime_rejected')
            ])
            ->count();

        return $this->success(['count' => $count], 'Unread overtime notification count retrieved successfully');
    }

    /**
     * Get signature and report approval notifications for the authenticated user
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSignatureNotifications()
    {
        $userId = Auth::user()->id;
        $notifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $userId)
            ->whereIn('type', [
                config('constants.notification_types.signature_added'),
                config('constants.notification_types.report_approved')
            ])
            ->orderBy('created_at', 'desc')
            ->get();

        $notifications->transform(function ($notification) {
            if (isset($notification->short_description)) {
                // Convert PDF_LINK format to clickable links before stripping tags
                $description = $notification->short_description;
                $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
                $notification->short_description = $description;
            }
            return $notification;
        });

        return $this->success($notifications, 'Signature notifications retrieved successfully');
    }

    /**
     * Get count of unread signature notifications for the authenticated user
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnreadSignatureNotificationCount()
    {
        $userId = Auth::user()->id;
        $count = Notification::where('receiver_id', $userId)
            ->where('read', '0')
            ->whereIn('type', [
                config('constants.notification_types.signature_added'),
                config('constants.notification_types.report_approved')
            ])
            ->count();

        return $this->success(['count' => $count], 'Unread signature notification count retrieved successfully');
    }

    /**
     * Get leave request notifications for the authenticated user
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getLeaveRequestNotifications()
    {
        $userId = Auth::user()->id;
        $notifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $userId)
            ->whereIn('type', [
                config('constants.notification_types.leave_request_submitted'),
                config('constants.notification_types.leave_request_pending_approval'),
                config('constants.notification_types.leave_request_notification'),
                config('constants.notification_types.leave_request_customer_notification'),
                config('constants.notification_types.leave_request_approved'),
                config('constants.notification_types.leave_request_rejected')
            ])
            ->orderBy('created_at', 'desc')
            ->get();

        $notifications->transform(function ($notification) {
            if (isset($notification->short_description)) {
                // Convert PDF_LINK format to clickable links before stripping tags
                $description = $notification->short_description;
                $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
                $notification->short_description = $description;
            }
            return $notification;
        });

        return $this->success($notifications, 'Leave request notifications retrieved successfully');
    }

    /**
     * Get count of unread leave request notifications for the authenticated user
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnreadLeaveRequestNotificationCount()
    {
        $userId = Auth::user()->id;
        $count = Notification::where('receiver_id', $userId)
            ->where('read', '0')
            ->whereIn('type', [
                config('constants.notification_types.leave_request_submitted'),
                config('constants.notification_types.leave_request_pending_approval'),
                config('constants.notification_types.leave_request_notification'),
                config('constants.notification_types.leave_request_customer_notification'),
                config('constants.notification_types.leave_request_approved'),
                config('constants.notification_types.leave_request_rejected')
            ])
            ->count();

        return $this->success(['count' => $count], 'Unread leave request notification count retrieved successfully');
    }

    /**
     * Get report PDF upload notifications for the authenticated user
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getReportPdfUploadNotifications()
    {
        $userId = Auth::user()->id;
        $notifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $userId)
            ->whereIn('type', [
                config('constants.notification_types.report_pdf_uploaded')
            ])
            ->orderBy('created_at', 'desc')
            ->get();

        $notifications->transform(function ($notification) {
            if (isset($notification->short_description)) {
                $notification->short_description = strip_tags($notification->short_description);
            }
            return $notification;
        });

        return $this->success($notifications, 'Report PDF upload notifications retrieved successfully');
    }

    /**
     * Get count of unread report PDF upload notifications for the authenticated user
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnreadReportPdfUploadNotificationCount()
    {
        $userId = Auth::user()->id;
        $count = Notification::where('receiver_id', $userId)
            ->where('read', '0')
            ->whereIn('type', [
                config('constants.notification_types.report_pdf_uploaded')
            ])
            ->count();

        return $this->success(['count' => $count], 'Unread report PDF upload notification count retrieved successfully');
    }

    /**
     * Get all notifications for the authenticated customer
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCustomerNotifications()
    {
        $customerId = Auth::user()->id;
        
        // Verify user is a customer
        if (Auth::user()->user_type != config('constants.user_types.customer')) {
            return $this->error('Unauthorized access. Only customers can access this endpoint.', 403);
        }

        $userTable = $this->getUserTable();
        $auth_id = 0;
        $workspace_id = 0;
        if ($userTable === 'customer') {
            $auth_id = Auth::user()->id;
            $workspace_id = Auth::user()->current_workspace_id;
            $authPersonalDetails = User::where('id', Auth::user()->id)->first();
        }
        if ($userTable === 'emp') {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();
        }
        $notifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $customerId)
            ->where('receiver_type', $userTable)
            ->where('customer_id', $auth_id)
            ->where('workspace_id', $workspace_id)
            ->orderBy('created_at', 'desc')
            ->get();
        $notifications->transform(callback: function ($notification) {
            if (isset($notification->short_description)) {
                // Convert PDF_LINK format to clickable links before stripping tags
                $description = $notification->short_description;
                $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
                $notification->short_description = $description;
            }
            return $notification;
        });
        
        return $this->success($notifications, 'Customer notifications retrieved successfully');
    }

    /**
     * Get unread notification count for the authenticated customer
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCustomerUnreadNotificationCount()
    {
        $customerId = Auth::user()->id;
        
        // Verify user is a customer
        if (Auth::user()->user_type != config('constants.user_types.customer')) {
            return $this->error('Unauthorized access. Only customers can access this endpoint.', 403);
        }
        
        $count = Notification::where('receiver_id', $customerId)
            ->where('read', '0')
            ->count();

        return $this->success(['count' => $count], 'Unread customer notification count retrieved successfully');
    }

    /**
     * Mark a specific notification as read for the authenticated customer
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function markCustomerNotificationAsRead(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'notification_id' => 'required|exists:all_notifications,id',
        ]);
        
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return $this->error($error, 422);
        }
        
        $customerId = Auth::user()->id;
        
        // Verify user is a customer
        if (Auth::user()->user_type != config('constants.user_types.customer')) {
            return $this->error('Unauthorized access. Only customers can access this endpoint.', 403);
        }
        
        $notification = Notification::where('id', $request->notification_id)
            ->where('receiver_id', $customerId)
            ->first();
            
        if (!$notification) {
            return $this->error('Notification not found or does not belong to you', 404);
        }
        
        if($notification->read == 1){
            return $this->error('Notification already read', 400);
        }
        
        $notification->read = '1';
        $notification->save();
        
        return $this->message('Notification marked as read successfully');
    }

    /**
     * Mark all notifications as read for the authenticated customer
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function markAllCustomerNotificationsAsRead()
    {
        $customerId = Auth::user()->id;
        
        // Verify user is a customer
        if (Auth::user()->user_type != config('constants.user_types.customer')) {
            return $this->error('Unauthorized access. Only customers can access this endpoint.', 403);
        }
        
        $count = Notification::where('receiver_id', $customerId)
            ->where('read', '0')
            ->update(['read' => '1']);
            
        return $this->message("Notifications marked as read successfully");
    }

    /**
     * Get customer notifications by type
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCustomerNotificationsByType(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => 'required|string',
        ]);
        
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return $this->error($error, 422);
        }
        
        $customerId = Auth::user()->id;
        
        // Verify user is a customer
        if (Auth::user()->user_type != config('constants.user_types.customer')) {
            return $this->error('Unauthorized access. Only customers can access this endpoint.', 403);
        }
        
        $notifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $customerId)
            ->where('type', $request->type)
            ->orderBy('created_at', 'desc')
            ->get();
            
        $notifications->transform(function ($notification) {
            if (isset($notification->short_description)) {
                // Convert PDF_LINK format to clickable links before stripping tags
                $description = $notification->short_description;
                $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
                $notification->short_description = $description;
            }
            return $notification;
        });
        
        return $this->success($notifications, 'Customer notifications by type retrieved successfully');
    }

    /**
     * Get customer notifications with pagination
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCustomerNotificationsPaginated(Request $request)
    {
        $customerId = Auth::user()->id;
        
        // Verify user is a customer
        if (Auth::user()->user_type != config('constants.user_types.customer')) {
            return $this->error('Unauthorized access. Only customers can access this endpoint.', 403);
        }
        
        $perPage = $request->get('per_page', 15);
        $page = $request->get('page', 1);
        
        $notifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $customerId)
            ->orderBy('created_at', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);
            
        $notifications->getCollection()->transform(function ($notification) {
            if (isset($notification->short_description)) {
                // Convert PDF_LINK format to clickable links before stripping tags
                $description = $notification->short_description;
                $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
                $notification->short_description = $description;
            }
            return $notification;
        });
        
        return $this->success($notifications, 'Customer notifications retrieved successfully');
    }

    /**
     * Delete a specific notification for the authenticated customer
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteCustomerNotification(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'notification_id' => 'required|exists:all_notifications,id',
        ]);
        
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return $this->error($error, 422);
        }
        
        $customerId = Auth::user()->id;
        
        // Verify user is a customer
        if (Auth::user()->user_type != config('constants.user_types.customer')) {
            return $this->error('Unauthorized access. Only customers can access this endpoint.', 403);
        }
        
        $notification = Notification::where('id', $request->notification_id)
            ->where('receiver_id', $customerId)
            ->first();
            
        if (!$notification) {
            return $this->error('Notification not found or does not belong to you', 404);
        }
        
        $notification->delete();
        
        return $this->message('Notification deleted successfully');
    }

    /**
     * Clear all notifications for the authenticated customer
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function clearAllCustomerNotifications()
    {
        $customerId = Auth::user()->id;
        
        // Verify user is a customer
        if (Auth::user()->user_type != config('constants.user_types.customer')) {
            return $this->error('Unauthorized access. Only customers can access this endpoint.', 403);
        }
        
        $count = Notification::where('receiver_id', $customerId)->count();
        Notification::where('receiver_id', $customerId)->delete();
        
        return $this->message("$count notifications cleared successfully");
    }

    /**
     * Get all notifications for the authenticated admin
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAdminNotifications()
    {
        $adminId = Auth::user()->id;
        
        // Verify user is an admin
        if (Auth::user()->user_type != config('constants.user_types.admin')) {
            return $this->error('Unauthorized access. Only admins can access this endpoint.', 403);
        }

        $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;
        }
        if ($userTable === 'customer') {
            $userTable = 'admin';
        }
        $notifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $adminId)
            ->where('receiver_type', $userTable)
            ->orderBy('created_at', 'desc')
            ->get();
        $notifications->transform(function ($notification) {
            if (isset($notification->short_description)) {
                // Convert PDF_LINK format to clickable links before stripping tags
                $description = $notification->short_description;
                $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
                $notification->short_description = $description;
            }
            return $notification;
        });
        
        return $this->success($notifications, 'Admin notifications retrieved successfully');
    }

    /**
     * Get unread notification count for the authenticated admin
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAdminUnreadNotificationCount()
    {
        $adminId = Auth::user()->id;
        
        // Verify user is an admin
        if (Auth::user()->user_type != config('constants.user_types.admin')) {
            return $this->error('Unauthorized access. Only admins can access this endpoint.', 403);
        }
        
        $count = Notification::where('receiver_id', $adminId)
            ->where('read', '0')
            ->count();

        return $this->success(['count' => $count], 'Unread admin notification count retrieved successfully');
    }

    /**
     * Mark a specific notification as read for the authenticated admin
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function markAdminNotificationAsRead(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'notification_id' => 'required|exists:all_notifications,id',
        ]);
        
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return $this->error($error, 422);
        }
        
        $adminId = Auth::user()->id;
        
        // Verify user is an admin
        if (Auth::user()->user_type != config('constants.user_types.admin')) {
            return $this->error('Unauthorized access. Only admins can access this endpoint.', 403);
        }
        
        $notification = Notification::where('id', $request->notification_id)
            ->where('receiver_id', $adminId)
            ->first();
            
        if (!$notification) {
            return $this->error('Notification not found or does not belong to you', 404);
        }
        
        if($notification->read == 1){
            return $this->error('Notification already read', 400);
        }
        
        $notification->read = '1';
        $notification->save();
        
        return $this->message('Notification marked as read successfully');
    }

    /**
     * Mark all notifications as read for the authenticated admin
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function markAllAdminNotificationsAsRead()
    {
        $adminId = Auth::user()->id;
        
        // Verify user is an admin
        if (Auth::user()->user_type != config('constants.user_types.admin')) {
            return $this->error('Unauthorized access. Only admins can access this endpoint.', 403);
        }
        
        $count = Notification::where('receiver_id', $adminId)
            ->where('read', '0')
            ->update(['read' => '1']);
            
        return $this->message("Notifications marked as read successfully");
    }

    /**
     * Get admin notifications by type
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAdminNotificationsByType(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => 'required|string',
        ]);
        
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return $this->error($error, 422);
        }
        
        $adminId = Auth::user()->id;
        
        // Verify user is an admin
        if (Auth::user()->user_type != config('constants.user_types.admin')) {
            return $this->error('Unauthorized access. Only admins can access this endpoint.', 403);
        }

        $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;
        }
        
        $notifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $adminId)
            ->where('receiver_type', $userTable)
            ->where('type', $request->type)
            ->where('customer_id', $auth_id)
            ->where('workspace_id', $workspace_id)
            ->orderBy('created_at', 'desc')
            ->get();
            
        $notifications->transform(function ($notification) {
            if (isset($notification->short_description)) {
                // Convert PDF_LINK format to clickable links before stripping tags
                $description = $notification->short_description;
                $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
                $notification->short_description = $description;
            }
            return $notification;
        });
        
        return $this->success($notifications, 'Admin notifications by type retrieved successfully');
    }

    /**
     * Get admin notifications with pagination
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAdminNotificationsPaginated(Request $request)
    {
        $adminId = Auth::user()->id;
        
        // Verify user is an admin
        if (Auth::user()->user_type != config('constants.user_types.admin')) {
            return $this->error('Unauthorized access. Only admins can access this endpoint.', 403);
        }

        $userTable = $this->getUserTable();
        $auth_id = 0;
        $workspace_id = 0;
        if ($userTable === 'emp') {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
        }
        
        $perPage = $request->get('per_page', 15);
        $page = $request->get('page', 1);
        
        $notifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $adminId)
            ->where('receiver_type', $userTable)
            ->where('customer_id', $auth_id)
            ->where('workspace_id', $workspace_id)
            ->orderBy('created_at', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);
            
        $notifications->getCollection()->transform(function ($notification) {
            if (isset($notification->short_description)) {
                // Convert PDF_LINK format to clickable links before stripping tags
                $description = $notification->short_description;
                $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
                $notification->short_description = $description;
            }
            return $notification;
        });
        
        return $this->success($notifications, 'Admin notifications retrieved successfully');
    }

    /**
     * Delete a specific notification for the authenticated admin
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteAdminNotification(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'notification_id' => 'required|exists:all_notifications,id',
        ]);
        
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return $this->error($error, 422);
        }
        
        $adminId = Auth::user()->id;
        
        // Verify user is an admin
        if (Auth::user()->user_type != config('constants.user_types.admin')) {
            return $this->error('Unauthorized access. Only admins can access this endpoint.', 403);
        }
        
        $notification = Notification::where('receiver_id', $adminId)
            ->where('id', $request->notification_id)
            ->first();
            
        if (!$notification) {
            return $this->error('Notification not found or does not belong to you', 404);
        }
        
        $notification->delete();
        
        return $this->message('Notification deleted successfully');
    }

    /**
     * Clear all notifications for the authenticated admin
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function clearAllAdminNotifications()
    {
        $adminId = Auth::user()->id;
        
        // Verify user is an admin
        if (Auth::user()->user_type != config('constants.user_types.admin')) {
            return $this->error('Unauthorized access. Only admins can access this endpoint.', 403);
        }
        
        $count = Notification::where('receiver_id', $adminId)->count();
        Notification::where('receiver_id', $adminId)->delete();
        
        return $this->message("$count notifications cleared successfully");
    }

    /**
     * Get admin dashboard notifications (recent and important)
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAdminDashboardNotifications()
    {
        $adminId = Auth::user()->id;
        
        // Verify user is an admin
        if (Auth::user()->user_type != config('constants.user_types.admin')) {
            return $this->error('Unauthorized access. Only admins can access this endpoint.', 403);
        }

        $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;
        }

        // Get recent unread notifications (last 10)
        $recentNotifications = Notification::with(['sites', 'teams'])
            ->where('receiver_id', $adminId)
            ->where('receiver_type', $userTable)
            ->where('customer_id', $auth_id)
            ->where('workspace_id', $workspace_id)
            ->where('read', '0')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        // Get total unread count
        $unreadCount = Notification::where('receiver_id', $adminId)
            ->where('receiver_type', $userTable)
            ->where('customer_id', $auth_id)
            ->where('workspace_id', $workspace_id)
            ->where('read', '0')
            ->count();

        $recentNotifications->transform(function ($notification) {
            if (isset($notification->short_description)) {
                // Convert PDF_LINK format to clickable links before stripping tags
                $description = $notification->short_description;
                $description = preg_replace('/\[PDF_LINK:(.*?)\]/', '<a href="$1" target="_blank" class="text-primary fw-bold">📄 View Report</a>', $description);
                $notification->short_description = $description;
            }
            return $notification;
        });

        $data = [
            'recent_notifications' => $recentNotifications,
            'unread_count' => $unreadCount,
            'total_notifications' => $unreadCount + $recentNotifications->count()
        ];
        
        return $this->success($data, 'Admin dashboard notifications retrieved successfully');
    }

    /**
     * Show admin notifications page
     *
     * @return \Illuminate\View\View
     */
    public function showAdminNotificationsPage()
    {
        // Verify user is an admin
        if (Auth::user()->user_type != config('constants.user_types.admin')) {
            abort(403, 'Unauthorized access. Only admins can access this page.');
        }

        return view('admin.notifications');
    }
}
