<?php

namespace App\Services;

use App\Models\Notification;
use App\Models\User;

class NotificationService
{
    /**
     * Send notification when a requisition is created
     */
    public static function sendRequisitionCreatedNotification($requisitionNotificationData, $redirectConfig)
    {

        Notification::create([
            'type' => 'requisition_created',
            'redirect' => $redirectConfig->route,
            'user_id' => auth()->user()->id,
            'from_warehouse_id' => $redirectConfig->warehouseId,
            'data' => $requisitionNotificationData
        ]);
    }

    /**
     * Send notification when requisition products are shifted
     */
    public static function sendRequisitionShiftedNotification($requisition)
    {
        // Notify the shop that created the requisition
        if ($requisition->user) {
            Notification::create([
                'type' => 'requisition_shifted',
                'user_id' => $requisition->user_id,
                'data' => [
                    'title' => 'Requisition Products Shifted',
                    'message' => "Your requisition #{$requisition->invoice_no} products have been shifted and are on the way",
                    'requisition_id' => $requisition->id,
                    'requisition_invoice' => $requisition->invoice_no
                ]
            ]);
        }

        // Also notify other shop users if they exist
        if ($requisition->user && $requisition->user->shop_id) {
            $shopUsers = User::where('shop_id', $requisition->user->shop_id)
                ->where('id', '!=', $requisition->user_id)
                ->get();

            foreach ($shopUsers as $user) {
                Notification::create([
                    'type' => 'requisition_shifted',
                    'user_id' => $user->id,
                    'data' => [
                        'title' => 'Requisition Products Shifted',
                        'message' => "Requisition #{$requisition->invoice_no} products have been shifted to your shop",
                        'requisition_id' => $requisition->id,
                        'requisition_invoice' => $requisition->invoice_no
                    ]
                ]);
            }
        }
    }

    /**
     * Send notification when requisition is approved
     */
    public static function sendRequisitionApprovedNotification($requisition)
    {
        if ($requisition->user) {
            Notification::create([
                'type' => 'requisition_approved',
                'user_id' => $requisition->user_id,
                'data' => [
                    'title' => 'Requisition Approved',
                    'message' => "Your requisition #{$requisition->invoice_no} has been approved",
                    'requisition_id' => $requisition->id,
                    'requisition_invoice' => $requisition->invoice_no
                ]
            ]);
        }
    }

    /**
     * Send notification when requisition is rejected
     */
    public static function sendRequisitionRejectedNotification($requisition, $reason = null)
    {
        if ($requisition->user) {
            $message = "Your requisition #{$requisition->invoice_no} has been rejected";
            if ($reason) {
                $message .= ". Reason: {$reason}";
            }

            Notification::create([
                'type' => 'requisition_rejected',
                'user_id' => $requisition->user_id,
                'data' => [
                    'title' => 'Requisition Rejected',
                    'message' => $message,
                    'requisition_id' => $requisition->id,
                    'requisition_invoice' => $requisition->invoice_no,
                    'reason' => $reason
                ]
            ]);
        }
    }

    /**
     * Get unread notifications count for a user
     */
    public static function getUnreadCount($user)
    {
        return Notification::where('from_warehouse_id', $user->shop_id)->unread()->count();
    }

    /**
     * Get notifications for a user
     */
    public static function getUserNotifications($user, $limit = 20)
    {
        return Notification::where('from_warehouse_id', $user->shop_id)
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();
    }

    /**
     * Mark notification as read
     */
    public static function markAsRead($notificationId)
    {
        $notification = Notification::find($notificationId);
        if ($notification) {
            $notification->markAsRead();
        }
    }

    /**
     * Mark all notifications as read for a user
     */
    public static function markAllAsRead($userId)
    {
        Notification::where('user_id', $userId)
            ->unread()
            ->update(['read_at' => now()]);
    }

    /**
     * Send notification when approval is requested
     */
    public static function sendApprovalRequestNotification($user, $approval, $moduleName, $referenceId, $isReassignment = false)
    {
        $requester = $approval->requester;
        $message = $isReassignment 
            ? "An approval request for {$moduleName} #{$referenceId} has been reassigned to you"
            : "You have a pending approval request for {$moduleName} #{$referenceId}";

        Notification::create([
            'type' => 'approval_requested',
            'user_id' => $user->id,
            'from_warehouse_id' => $user->shop_id ?? null,
            'data' => [
                'title' => 'Approval Request',
                'message' => $message,
                'module_name' => $moduleName,
                'reference_id' => $referenceId,
                'approval_id' => $approval->id,
                'requested_by' => $requester->name ?? 'Unknown',
                'requested_by_id' => $requester->id ?? null,
            ]
        ]);
    }

    /**
     * Send notification when approval is completed (approved/rejected)
     */
    public static function sendApprovalCompletedNotification($user, $approval, $moduleName, $referenceId, $status, $comment = null)
    {
        $statusText = $status === 'approved' ? 'approved' : 'rejected';
        $message = "Your {$moduleName} #{$referenceId} has been {$statusText}";
        if ($comment) {
            $message .= ". Comment: {$comment}";
        }

        Notification::create([
            'type' => "approval_{$statusText}",
            'user_id' => $user->id,
            'from_warehouse_id' => $user->shop_id ?? null,
            'data' => [
                'title' => ucfirst($statusText) . ' Approval',
                'message' => $message,
                'module_name' => $moduleName,
                'reference_id' => $referenceId,
                'approval_id' => $approval->id,
                'status' => $status,
                'comment' => $comment,
            ]
        ]);
    }

    /**
     * Send notification for approval action (approve/reject by approver)
     */
    public static function sendApprovalActionNotification($user, $approval, $moduleName, $referenceId, $action, $comment = null)
    {
        $actionText = $action === 'approved' ? 'approved' : 'rejected';
        $message = "{$moduleName} #{$referenceId} has been {$actionText}";
        if ($comment) {
            $message .= ". Comment: {$comment}";
        }

        Notification::create([
            'type' => "approval_action_{$actionText}",
            'user_id' => $user->id,
            'from_warehouse_id' => $user->shop_id ?? null,
            'data' => [
                'title' => 'Approval Action',
                'message' => $message,
                'module_name' => $moduleName,
                'reference_id' => $referenceId,
                'approval_id' => $approval->id,
                'action' => $action,
                'comment' => $comment,
            ]
        ]);
    }

    /**
     * Send notification when a comment is added to approval
     */
    public static function sendApprovalCommentNotification($user, $approval, $moduleName, $referenceId, $comment)
    {
        $commenter = auth()->user();
        $message = "{$commenter->name} added a comment on {$moduleName} #{$referenceId}";

        Notification::create([
            'type' => 'approval_comment',
            'user_id' => $user->id,
            'from_warehouse_id' => $user->shop_id ?? null,
            'data' => [
                'title' => 'Approval Comment',
                'message' => $message,
                'module_name' => $moduleName,
                'reference_id' => $referenceId,
                'approval_id' => $approval->id,
                'comment' => $comment,
                'commenter' => $commenter->name ?? 'Unknown',
                'commenter_id' => $commenter->id ?? null,
            ]
        ]);
    }
}
