<?php

namespace App\Http\Middleware;

use App\Models\Billing;
use App\Models\User;
use App\Models\Role;
use App\Notifications\BillingCheckNotification;
use App\Notifications\AdminBillingBlockNotification;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckBilling
{
    public function handle(Request $request, Closure $next, $type)
    {
        $user = $request->user();
        
        $pendingBilling = Billing::where('user_id', $user->id)
            ->where('type', $type)
            ->where('status', 'pending')
            ->first();

        if ($pendingBilling) {
            // Send notification to user
            $user->notify(new BillingCheckNotification($pendingBilling, $type));

            // Notify admins about this blocked action
            $this->notifyAdmins($pendingBilling, $user, $type);

            // Push notification to the user
            $title = $pendingBilling->title 
                ? $pendingBilling->title 
                : 'Action Blocked: Pending ' . ucfirst($type) . ' Payment Required';
                
            $message = 'You have a pending billing that needs to be cleared before proceeding with your ' . $type . '.';
            $image = '';
            $action = '/billings';

            // Send push notification
            $user->pushMessage($title, $message, $image, $action);

            // Construct a meaningful error message
            $message = $pendingBilling->title 
                ? $pendingBilling->title. '. Kindly check your email inbox/spam folder for the billing details.'
                : 'You have a pending billing that needs to be cleared before proceeding. Kindly check your email inbox/spam folder for the billing details.';

            return response()->json([
                'status' => 'error',
                'message' => $message,
                'billing' => [
                    'id' => $pendingBilling->id,
                    'title' => $pendingBilling->title,
                    'amount' => $pendingBilling->amount,
                    'description' => $pendingBilling->description,
                    'created_at' => $pendingBilling->created_at
                ]
            ], 403);
        }

        return $next($request);
    }

    /**
     * Notify all admin users about the blocked action
     */
    private function notifyAdmins($billing, $user, $type)
    {
        // Find admin users
        $adminRoles = Role::where('role', 'admin')->get();
        
        foreach ($adminRoles as $adminRole) {
            $admin = User::find($adminRole->user_id);
            
            if ($admin) {
                // Send email notification
                $admin->notify(new AdminBillingBlockNotification($billing, $user, $type));
                
                // Send push notification to admin
                $title = 'User Action Blocked';
                $message = $user->name . ' attempted to perform a ' . $type . ' but was blocked due to a pending billing.';
                $image = '';
                $action = '/admin/billings';
                
                $admin->pushMessage($title, $message, $image, $action);
            }
        }
    }
} 