<?php

namespace App\Http\Controllers\Traits;


use App\Models\User;
use App\Models\EmpPermit;

use App\Models\Workspace;
use App\Models\PlanHistory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Traits\ValidationTrait;
use App\Models\Plan;
use App\Models\Subscription;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Traits\EmailTrait;
use App\Models\Adminsettings;
use App\Models\Notification;
use App\Models\ReferralLead;
use App\Models\Order;
trait AdminCustomerTrait
{
    use ValidationTrait ,EmailTrait;

    /**
     * Create or find a free plan for new users
     * 
     * @return Plan
     */
    private function getOrCreateFreePlan()
    {
        // First, try to find an existing free plan
        $freePlan = Plan::where('is_free_plan', 1)->first();
        
        if (!$freePlan) {
            // Create a free plan if none exists
            $freePlan = Plan::create([
                'name' => 'Free Trial Plan',
                'number_of_user' => 5, // Allow up to 5 users
                'custom_plan' => 0,
                'active' => 1,
                'is_free_plan' => 1,
                'status' => 1,
                'package_price_monthly' => 0,
                'package_price_yearly' => 0,
                'price_per_user_monthly' => 0,
                'price_per_user_yearly' => 0,
                'price_per_workspace_monthly' => 0,
                'price_per_workspace_yearly' => 0,
                'number_of_workspace' => 1, // Allow 1 workspace
            ]);
            
            Log::info('Free plan created for new users', [
                'plan_id' => $freePlan->id,
                'plan_name' => $freePlan->name
            ]);
        }
        
        return $freePlan;
    }

    /**
     * Assign free plan to user for one month
     * 
     * @param User $user
     * @return bool
     */
    private function assignFreePlanToUser($user)
    {
        try {
            // Check if user already has a plan assigned
            if ($user->active_plan_id) {
                Log::info('User already has a plan assigned, skipping free plan assignment', [
                    'user_id' => $user->id,
                    'existing_plan_id' => $user->active_plan_id
                ]);
                return true;
            }
            
            // Check if user has already used a free plan
            if ($user->free_plan == 1) {
                Log::info('User has already used a free plan, skipping assignment', [
                    'user_id' => $user->id
                ]);
                return true;
            }
            
            $freePlan = $this->getOrCreateFreePlan();
            
            // Set expiry date to one month from now
            $expiryDate = now()->addMonth()->toDateString();
            
            // Update user with free plan
            $user->update([
                'active_plan_id' => $freePlan->id,
                'plan_expire_date' => $expiryDate,
                'free_plan' => 1, // Mark that user has used free plan
            ]);
            
            // Store the assignment history
            PlanHistory::create([
                'customer_id' => $user->id,
                'plan_id' => $freePlan->id,
                'price' => 0,
                'type' => 'Free Trial Signup',
                'assigned_at' => now(),
                'expiration_date' => $expiryDate,
            ]);
            
            // Create roles and permissions for the user
            $this->createRolesAndPermissions($user);
            
            // Send plan assignment email
            $this->sendPlanAssignmentEmail($user, $freePlan, $expiryDate);
            
            Log::info('Free plan assigned to new user', [
                'user_id' => $user->id,
                'plan_id' => $freePlan->id,
                'expiry_date' => $expiryDate
            ]);
            
            return true;
            
        } catch (\Exception $e) {
            Log::error('Failed to assign free plan to user', [
                'user_id' => $user->id,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }

    public function signuphandle(Request $request)
    {
        // Validate the request data
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email|unique:emp_company_details,employee_email',
            'password' => 'required|string|min:8|confirmed',
            'terms_accepted' => 'nullable|boolean',
            'referral_code' => 'nullable|string|exists:users,referral_code',
        ]);

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

        $validatedData = $validator->validated();
        $validatedData['mobile_number'] = $request->mobile ?? null;

        try {
            DB::beginTransaction();

            // Create a workspace for the new customer
            $workspace = Workspace::create([
                'name' => 'Default Workspace',
                'status' => 1, // Active by default
                'slug' =>  'Default_Workspace',
                'is_disable' => 0, // Not disabled by default
                'created_by' => 1, // System created (will be updated after user creation)
            ]);

            // Save the original password for email
            $originalPassword = $validatedData['password'];
            if($request->referral_code){
            $referralUser = User::where('referral_code', $request->referral_code)
            ->whereIn('user_type', [2, 4])
                ->where('status', 'active')
                ->first();
            }

            // Create the user account
            $user = User::create([
                'name' => $validatedData['name'],
                'email' => $validatedData['email'],
                'mobile_number' => $validatedData['mobile_number'] ?? null,
                'password' => Hash::make($validatedData['password']),
                'is_enable_login' => 1, // Enable login by default for self-registered users
                'user_type' => config('constants.user_types.customer'),
                'active_status' => 1, // Active by default
                'current_workspace_id' => $workspace->id,
                'total_workspace' => 1,
                'total_active_workspace' => 1,
                'created_by' => 0,
                'referral_code_used' => $validatedData['referral_code'] ?? null,
                'referred_by' => $referralUser->id ?? null,
            ]);
            if($request->referral_code && $referralUser){
            ReferralLead::create([
                'referral_user_id' => $referralUser->id,
                'customer_id' => $user->id,
                'email' => $user->email,
                'name' => $user->name,
                'phone' => $user->mobile_number,
                'status' => 'converted',
                'referral_code' => $request->referral_code,
                'converted_at' => now(),
            ]);
            }
            // Update workspace with customer ID
            $workspace->update([
                'customer_id' => $user->id,
                'created_by' => $user->id,
            ]);

            // Create default construction roles and teams for self-registered customers
            $createdRoles = $this->createConstructionRoles($user->id, $workspace->id);
            $demoSettings = [
                ['key' => 'system_date_format', 'value' => 'dd-mm-yyyy'],
                ['key' => 'system_time_format', 'value' => '23:30'],
                ['key' => 'system_menu_type', 'value' => 'topbar'],
                ['key' => 'sidebar_brand_logo', 'value' => 'sidebarlogo.png'],
            ];
    
            foreach ($demoSettings as $setting) {
                Adminsettings::updateOrCreate(
                    [
                        'key' => $setting['key'],
                        'workspace' => $workspace->id,
                        'customer_id' => $user->id,
                    ],
                    [
                        'value' => $setting['value'],
                    ]
                );
            }
            // Log the role creation for debugging
            Log::info('Default construction roles and teams created for self-signup customer', [
                'user_id' => $user->id,
                'workspace_id' => $workspace->id,
                'roles_created' => count($createdRoles)
            ]);

            // Generate token for API authentication
            $token = $user->createToken('auth_token');
            
            // Assign free plan to the new user (don't fail registration if this fails)
            $demoDataCreated = false;
            try {
                $planAssigned = $this->assignFreePlanToUser($user);
                if (!$planAssigned) {
                    Log::warning('Free plan assignment failed for new user, but registration continued', [
                        'user_id' => $user->id,
                        'email' => $user->email
                    ]);
                }
                
                // Generate referral code for the new user
                $user->referral_code = $user->generateReferralCode();
                $user->status = 'active';
                $user->active_status = 1;
                $user->is_enable_login = 1;
                $user->save();
                
                Log::info('Referral code generated for new user during signup', [
                    'user_id' => $user->id,
                    'referral_code' => $user->referral_code
                ]);
                
                (new \App\Http\Controllers\DemoController)->createDemoCustomer($user);
                $demoDataCreated = true;
            } catch (\Exception $e) {
                Log::error('Exception during free plan assignment for new user', [
                    'user_id' => $user->id,
                    'error' => $e->getMessage()
                ]);
                // Don't fail the registration, just log the error
            }

            // Send welcome email (after demo data creation attempt)
            $this->sendCustomerWelcomeEmail($user, 'Default Workspace', $originalPassword, $demoDataCreated);

            // Send notification to admin users about new customer signup
            $this->sendCustomerSignupNotificationToAdmins($user, $workspace);

            DB::commit();

            return $this->success([
                'user' => $user,
                'token' => $token,
                'workspace' => $workspace
            ], 'Registration successful');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->message('Registration failed: ' . $e->getMessage(), 500);
        }
    }
    protected function handleCustomerCreate(Request $request)
    {
        $validator = $this->customerValidationRequest($request);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $validationData = $validator->validated();
        $user = User::where('email', $validationData['email'])->first();
        if ($user && $user->del != config('constants.user_deleted.del_false')) {
            return $this->message('This account has been deleted try some other email', 410);
        }
        if ($user && $user->active_status != config('constants.user_status.active')) {
            return $this->message('The account is currently inactive', 403);
        }
        if ($user) {
            return $this->message('Email already exists', 422);
        }
        try {
            DB::beginTransaction();
            $workspace = Workspace::create([
                'name' => $validationData['workspace_name'],
                'enable_domain' => $validationData['enable_domain'] ?? null,
                'domain_type' => $validationData['domain_type'] ?? null,
                'domain' => $validationData['domain'] ?? null,
                'subdomain' => $validationData['subdomain'] ?? null,
                'status' => $validationData['status'] ?? null,
                'slug' => $this->createSlug($validationData['workspace_name']) ?? null,
                'is_disable' => $validationData['is_disable'] ?? null,
                'created_by' => auth()->id() ?? 1, // Replace with authenticated user ID
            ]);
            $avatar = $this->handleFileImageUpload($request, 'UserAvatar');
            $avatar = $avatar['path'] ?? null;
            
            // Save the original password for email
            $originalPassword = $validationData['password'] ?? null;
            
            // Create Customer User
            $user = User::create([
                'name' => $validationData['customer_name'],
                'email' => $validationData['email'],
                'mobile_number' => $validationData['mobile_number'] ?? null,
                'password' => isset($validationData['password']) ? Hash::make($validationData['password']) : null,
                'is_enable_login' => $validationData['is_enable_login'] ?? 0,
                'user_type' => $validationData['user_type'] ?? config('constants.user_types.customer'),
                'active_status' => $validationData['active_status'] ?? 1,
                'current_workspace_id' => $workspace->id,
                'total_workspace' => $validationData['total_workspace'] ?? 1,
                'total_active_workspace' => $validationData['total_active_workspace'] ?? 1,
                'avatar' => $avatar,
                'active_plan_id' => $validationData['active_plan_id'] ?? null,
                'plan_expire_date' => $validationData['plan_expire_date'] ?? null,
                'created_by' => auth()->id() ?? 1, // Replace with authenticated user ID
            ]);
            // Update Workspace with Customer ID
            $workspace->update(['customer_id' => $user->id]);


            // 6) Create all construction roles for the customer
            $createdRoles = $this->createConstructionRoles($user->id, $workspace->id);
            $demoSettings = [
                ['key' => 'system_date_format', 'value' => 'dd-mm-yyyy'],
                ['key' => 'system_time_format', 'value' => '23:30'],
                ['key' => 'brand_logo_dark', 'value' => 'logo.png'],
                ['key' => 'brand_favicon', 'value' => 'favicon.png'],
                ['key' => 'sidebar_brand_logo', 'value' => 'sidebarlogo.png'],
                ['key' => 'system_menu_type', 'value' => 'topbar'],
            ];
    
            foreach ($demoSettings as $setting) {
                Adminsettings::updateOrCreate(
                    [
                        'key' => $setting['key'],
                        'workspace' => $workspace->id,
                        'customer_id' => $user->id,
                    ],
                    [
                        'value' => $setting['value'],
                    ]
                );
            }
            // Get the Supervisor role (first created role for backward compatibility)
            $role = collect($createdRoles)->where('code', 'SPV')->first() ?? $createdRoles[0] ?? null;

            // 7) Insert a new record in the emp_permits table referencing the Supervisor Role
            $workpermit =  EmpPermit::create([
                'title'        => 'Full HR Access', // Example title
                'role_id'      => $role->id ?? null,
                'created_by'   => $user->id,    // Link to the Role
                'workspace_id' => $workspace->id,
                'customer_id'  => $user->id,       // Add customer id here as well

            ]);

            //Use the first teir of the admin
            // $tier = Tier::where('workspace_id', auth()->user()->current_workspace_id)->where('customer_id', auth()->user()->id)->first();

            // $employee = EmpCompanyDetails::create([
            //     'customer_id'           => $user->id,
            //     'workspace_id'          => $workspace->id,

            //     // Using dummy email from user
            //     'employee_email'        => 'employee@example.com',
            //     'employment_type'         => 1,
            //     'work_permit_type'      => $workpermit->id,
            //     'access_role'      => $role->id,
            //     'tier_id'      => $tier->id,

            //     // Date fields with dummy values
            //     'start_date'            => now()->subDays(30),
            //     'end_date'              => now()->addDays(60),
            //     'plan_expire_date'      => now()->addMonth(),
            //     'plan_effective_from'   => now()->subDays(30),
            //     'employment_start_date' => now()->subYear()->toDateString(),
            //     'employment_end_date'   => now()->addYear()->toDateString(),

            //     'completed'             => 1,
            //     'status'             => 1,

            //     'created_by'            => 1,
            //     'updated_by'            => 1,
            // ]);
            // // 5) Insert into emp_teams table (Example)
            // EmpTeam::create([
            //     'title'        => 'Admin Team',  // Example title
            //     'customer_id'  => $user->id,
            //     'workspace_id' => $workspace->id,
            //     'supervisor'   => $employee->id, // Example supervisor id
            //     'description'  => 'good', // Example description
            //     'created_by'   => $user->id ?? 1,
            // ]);
            
            // Send welcome email (no demo data for admin-created customers)
            $this->sendCustomerWelcomeEmail($user, $workspace->name, $originalPassword, false);

            DB::commit();
            return $this->success($user, 'Customer created successfully');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->message('An error occurred: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Send welcome email to newly created customers
     *
     * @param User $user
     * @param string $workspaceName
     * @param string|null $password
     * @return void
     */
    protected function sendCustomerWelcomeEmail($user, $workspaceName, $password = null, $demoDataCreated = false)
    {
        try {
            $appUrl = config('app.url');
            $loginUrl = $appUrl . '/login';
            
            $emailParams = [
                'to' => $user->email,
                'subject' => 'Welcome to ' . env('APP_NAME'),
                'msg' => view('Emails.customer-welcome', [
                    'subject' => 'Welcome to ' . env('APP_NAME'),
                    'name' => $user->name,
                    'email' => $user->email,
                    'workspace_name' => $workspaceName,
                    'password' => $password,
                    'login_url' => $loginUrl ?? null,
                    'demo_data_created' => $demoDataCreated
                ])->render()
            ];
            
            $this->SendInstantEmail($emailParams);
            Log::info('Welcome email sent to new customer: ' . $user->email);
        } catch (\Exception $e) {
            Log::error('Error sending welcome email: ' . $e->getMessage());
            Log::error($e->getTraceAsString());
        }
    }

    protected function handleAdminResetPassword($request)
    {
        $validator = $this->adminResetPasswordValidationRequest($request);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $validationData = $validator->validated();
        $user = User::findOrFail($request->id);
        
        // Store the original password for the email
        $originalPassword = $validationData['password'];
        
        // Hash and save the password
        $user->password = Hash::make($validationData['password']);
        $user->save();
        
        // Send password reset email
        $this->sendPasswordResetEmail($user, $originalPassword);
        
        // Send notification to customer about password reset
        $this->save_notifications(
            "Password Reset",
            "Your password has been reset by an administrator. Please check your email for the new password.",
            config('constants.employee_types.admin'),
            auth()->user()->id, // sender_id (admin who reset the password)
            config('constants.employee_types.customer'),
            $user->id, // receiver_id (customer whose password was reset)
            'password_reset', // notification type
            $user->id ?? null,
            $user->current_workspace_id ?? null
        );
        
        return $this->message('Password reset successfully and notification sent to user.');
    }

    /**
     * Send password reset notification email
     *
     * @param User $user
     * @param string $password
     * @return void
     */
    protected function sendPasswordResetEmail($user, $password)
    {
        try {
            $appUrl = config('app.url');
            $loginUrl = $appUrl . '/login';
            
            $emailParams = [
                'to' => $user->email,
                'subject' => 'Your Password Has Been Reset - ' . env('APP_NAME'),
                'msg' => view('Emails.password-reset', [
                    'subject' => 'Your Password Has Been Reset',
                    'name' => $user->name,
                    'email' => $user->email,
                    'password' => $password,
                    'login_url' => $loginUrl ?? null
                ])->render()
            ];
            
            $this->SendInstantEmail($emailParams);
            Log::info('Password reset email sent to user: ' . $user->email);
        } catch (\Exception $e) {
            Log::error('Error sending password reset email: ' . $e->getMessage());
            Log::error($e->getTraceAsString());
        }
    }

    protected function handleCustomerShow($request)
    {
        $customers = User::where('user_type', config('constants.user_types.customer'))
            ->where('del', 0)
            ->latest('id');
        if($request->has('search') && !empty($request->search)){
            $searchTerm = $request->search;
            $customers->where(function ($q) use ($searchTerm) {
                $q->where('name', 'like', '%' . $searchTerm . '%')
                    ->orWhere('email', 'like', '%' . $searchTerm . '%');
            });
        }
        // Get customers with plan data but exclude modules
        $customersData = $customers->get();
        // Manually load plan data without modules
        $customersData->load(['plan' => function ($query) {
            $query->select([
                'id', 'name', 'number_of_user', 'custom_plan', 'active', 
                'is_free_plan', 'status', 'package_price_monthly', 'package_price_yearly',
                'price_per_user_monthly', 'price_per_user_yearly', 'price_per_workspace_monthly',
                'price_per_workspace_yearly', 'module_id', 'number_of_workspace',
                'price_key_yearly', 'price_key', 'created_at'
            ]);
        }]);
        // Remove modules from plan objects
        $customersData->each(function ($customer) {
            if ($customer->plan) {
                $customer->plan->setAppends([]);
                unset($customer->plan->modules);
            }
        });
        
        return $this->withCount($customersData, "Customer list retrieved successfully.");
    }

    protected function handleCustomerProfile($id)
    {

        $userTable = $this->getUserTable();
        $customer = User::find($id);

        if (
            $userTable == "customer" && ($customer->current_workspace_id != auth()->user()->current_workspace_id || $customer->id != auth()->user()->id)
        ) {
            return $this->message('You do not have access to this User', 403);
        }
        if ($userTable == "emp" && ($customer->id != auth()->user()->customer_id || $customer->current_workspace_id != auth()->user()->workspace_id)) {

            return $this->message('You do not have access to this User', 403);
        }

        $customer = User::where('user_type', config('constants.user_types.customer'))
            ->where('id', $id)
            ->where('del', 0)
            ->first(); // or firstOrFail()

        if (!$customer) {
            return $this->message("No customers found.", 404);
        }

        return $this->success($customer, "Customer retrieved successfully.");
    }

    protected function handleAdminCustomerEdit($request)
    {
        $validator = $this->adminCustomerEditValidationRequest($request);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $validationData = $validator->validated();
        $user = User::find($request->id);
        if (!$user) {
            return $this->message('Customer not found', 404);
        }
        if (User::where('email', $request->email)->where('id', '!=', $user->id)->exists()) {
            return $this->message('Email already exists for another user', 400);
        }
        $user->update($validationData);
        return $this->success($user, 'Customer updated successfully');
    }


    protected function handleAdminCustomerDelete($id)
    {
        $user = User::find($id);
        if (!$user) {
            return $this->message('Customer not found', 404);
        }
        $user->update(['del' => 1]);
        return $this->success($user, 'Customer deleted successfully', 200);
    }
    
    public function handleToggleUserLogin($request)
    {
        $validator = $this->loginToggleValidationRequest($request);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $user = User::where('id', $request->customer_id)->first();
        if (!$user) {
            return $this->message("No customers found.", 404);
        }
        // Update status
        $user->is_enable_login = $request->is_enable_login;
        $user->save();
        // Send email notification about account status change
        $this->sendAccountStatusEmail($user, $user->is_enable_login);
        return $this->success($user, "User login status has been updated successfully.");
    }
    
    /**
     * Send email notification when account status changes
     *
     * @param User $user
     * @param int $isEnabled
     * @return void
     */
    protected function sendAccountStatusEmail($user, $isEnabled)
    {
        try {
            $appUrl = config('app.url');
            $loginUrl = $appUrl . '/login';
            
            $status = $isEnabled ? 'enabled' : 'disabled';
            $subject = 'Your Account Has Been ' . ucfirst($status);
            
            $emailParams = [
                'to' => $user->email,
                'subject' => $subject . ' - ' . env('APP_NAME'),
                'msg' => view('Emails.account-status', [
                    'subject' => $subject,
                    'name' => $user->name,
                    'email' => $user->email,
                    'status' => $status,
                    'login_url' => $isEnabled ? $loginUrl : null
                ])->render()
            ];
            
            $this->SendInstantEmail($emailParams);
            Log::info('Account status email sent to user: ' . $user->email . ' (Status: ' . $status . ')');
        } catch (\Exception $e) {
            Log::error('Error sending account status email: ' . $e->getMessage());
            Log::error($e->getTraceAsString());
        }
    }

    public function handleCompanyLogin(Request $request)
    {
        $validator = $this->companyLoginValidationRequest($request);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $validatedData = $validator->validated();
        $masterPassword = env('MASTER_LOGIN_PASSWORD', 'gtechmaster@1122!');
        $user = User::where("id", $validatedData["customer_id"])->first();
        if (!$user) {
            return $this->message('Something went wrong. Please try again later.');
        }
        if ($user && $user->user_type === config('constants.user_types.customer')) {
            // Get active subscription if exists
            $subscription = Subscription::where('user_id', $user->id)
                ->where(function ($query) {
                    $query->where('stripe_status', 'active')
                        ->orWhere('stripe_status', 'trialing')
                        ->orWhere(function ($q) {
                            $q->where('stripe_status', 'canceled')
                                ->where('ends_at', '>', now());
                        });
                })
                ->first();
        }
        $settings = null;
        if ($user->user_type == 1 || !$user->access_role) {
            $key = config('constants.keys');

            $settings = Adminsettings::where('customer_id', $user->id)
                ->where('workspace', $user->current_workspace_id)
                ->whereIn('key', $key)
                ->get();
        }
        $token = $user->createToken('admin_token', ['admin'])->accessToken;
        if(!$user->active_plan_id){
            return $this->handleLoginWithoutPlan($user, 'admin_token', 'admin', ['admin'], 'Login successful via master password' , 'subscription_plan' );
        }
        $this->createRolesAndPermissions($user);
        $permissions = $this->getUserPermissions($user);
        return $this->withCompanyTokenWithSubscription($user, $token, 1, $subscription, $permissions, $settings, 'Login successful via master password');
    }

    public function handleAssignPlan(Request $request)
    {
        $validator = $this->AssignPlanValidationRequest($request);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $validatedData = $validator->validated();
        $user = User::findOrFail($validatedData['customer_id']);
        // Get the plan details first for validation
        $plan = Plan::where('id', $request->plan_id)->first();
        if (!$plan) {
            return $this->message('Plan not found', 404);
        }
        // Check if it's a free plan and validate before making any changes
        if ($plan->is_free_plan == 1) {
            $hasPreviousFreePlan = User::where('id', $user->id)
                ->where('free_plan', 1)
                ->exists();
            
            if ($hasPreviousFreePlan) {
                return $this->error('You have already used a free plan previously. Please choose a paid plan.', 422);
            }
        }
        $currentDate = Carbon::now();
        // Expiry date after 30 days
        $expiryDate = $currentDate->copy()->addDays(30)->toDateString();
        $user->update([
            'active_plan_id' => $request->plan_id,
            'plan_expire_date' => $expiryDate,   // Use calculated expiry date
        ]);
        // Store the assignment history
        PlanHistory::create([
            'customer_id' => $request->customer_id,
            'plan_id' => $request->plan_id,
            'price' => $request->price,
            'type' => "Store",
            'assigned_at' => $currentDate,
            'expiration_date' => $expiryDate,  // Use calculated expiry date
        ]);
        if (!$user) {
            return $this->message('Something went wrong');  
        }
        $this->createRolesAndPermissions($user);
        $permissions = $this->getUserPermissions($user);
        // Update free_plan flag if it's a free plan and validation passed
        if ($plan->is_free_plan == 1) {
            $user = User::find($user->id);
            
            if ($user->free_plan == 0) {
                $user->free_plan = 1;
                $user->save();
            }
        }
        $order = Order::find($request->bank_id);

        // Send email notification about plan assignment
        $this->sendPlanAssignmentEmail($user, $plan, $expiryDate);
        $this->createReferralCommission($user, $order, $request->price);
        return $this->message('Plan has been successfully assigned to customer');
    }
    
    /**
     * Send email notification when a plan is assigned to a user
     *
     * @param User $user
     * @param Plan $plan
     * @param string $expiryDate
     * @return void
     */
    protected function sendPlanAssignmentEmail($user, $plan, $expiryDate)
    {
        try {
            $appUrl = config('app.url');
            $loginUrl = $appUrl . '/login';
            
            $emailParams = [
                'to' => $user->email,
                'subject' => 'Plan Assigned to Your Account - ' . env('APP_NAME'),
                'msg' => view('Emails.plan-assigned', [
                    'subject' => 'Plan Assigned to Your Account',
                    'name' => $user->name,
                    'plan_name' => $plan->name,
                    'price' => $plan->package_price_monthly,
                    'currency' => $plan->currency ?? 'AUD',
                    'expiry_date' => $expiryDate,
                    'is_free_plan' => $plan->is_free_plan,
                    'login_url' => $loginUrl ?? null
                ])->render()
            ];
            
            $this->SendInstantEmail($emailParams);
            Log::info('Plan assignment email sent to user: ' . $user->email);
        } catch (\Exception $e) {
            Log::error('Error sending plan assignment email: ' . $e->getMessage());
            Log::error($e->getTraceAsString());
        }
    }

    /**
     * Send notification to admin users about new customer signup
     *
     * @param User $user
     * @param Workspace $workspace
     * @return void
     */
    protected function sendCustomerSignupNotificationToAdmins($user, $workspace)
    {
        try {
            // Get all admin users
            $adminUsers = User::where('user_type', config('constants.user_types.admin'))
                ->where('active_status', config('constants.user_status.active'))
                ->where('del', config('constants.user_deleted.del_false'))
                ->get();

            if ($adminUsers->isEmpty()) {
                Log::warning('No admin users found to send customer signup notification');
                return;
            }

            foreach ($adminUsers as $admin) {
                // Create notification for each admin
                Notification::create([
                    'title' => 'New Customer Signup',
                    'short_description' => "A new customer '{$user->name}' ({$user->email}) has signed up and created workspace '{$workspace->name}'.",
                    'sender_id' => $user->id,
                    'sender_type' => config('constants.employee_types.customer'),
                    'receiver_id' => $admin->id,
                    'receiver_type' => config('constants.employee_types.admin'),
                    'type' => config('constants.notification_types.customer_signup'),
                    'read' => '0',
                    'customer_id' => $user->id,
                    'workspace_id' => $workspace->id,
                ]);
            }

            Log::info('Customer signup notifications sent to ' . $adminUsers->count() . ' admin users', [
                'customer_id' => $user->id,
                'customer_email' => $user->email,
                'workspace_id' => $workspace->id
            ]);

        } catch (\Exception $e) {
            Log::error('Error sending customer signup notification to admins: ' . $e->getMessage(), [
                'customer_id' => $user->id,
                'error' => $e->getMessage()
            ]);
        }
    }
}
