<?php
// app/Console/Kernel.php

namespace App\Console;

use Illuminate\Foundation\Console\Kernel as Kernel;

class Kernel extends Kernel
{
    
    protected function schedule(Schedule $schedule)
{
    
    // Reset plan limits monthly
    $schedule->call(function () {
        PlanLimit::where('reset_date', '<=', now())
            ->update([
                'remaining_job_posts' => DB::raw('(SELECT job_post_limit FROM subscription_plans 
                    INNER JOIN employer_subscriptions ON subscription_plans.id = employer_subscriptions.plan_id
                    WHERE employer_subscriptions.employer_id = plan_limits.employer_id 
                    AND employer_subscriptions.status = "active")'),
                'remaining_ai_contacts' => DB::raw('(SELECT ai_contact_limit FROM subscription_plans 
                    INNER JOIN employer_subscriptions ON subscription_plans.id = employer_subscriptions.plan_id
                    WHERE employer_subscriptions.employer_id = plan_limits.employer_id 
                    AND employer_subscriptions.status = "active")'),
                'reset_date' => now()->addMonth()
            ]);
    })->monthly();
     
     // Award monthly bonus on the last day of each month at 23:59
    $schedule->command('mothership:award-bonus')->monthlyOn(now()->daysInMonth, '23:59');
}
    
    // Send subscription renewal reminders
    $schedule->call(function () {
        $subscriptions = EmployerSubscription::where('status', 'active')
            ->where('current_period_end', '<=', now()->addDays(7))
            ->where('current_period_end', '>', now())
            ->get();
            
        foreach ($subscriptions as $subscription) {
            // Send reminder email
            $subscription->employer->user->notify(new SubscriptionRenewalReminder($subscription));
        }
    })->daily();
// Add to schedule method
$schedule->call(function () {
    $jobs = \App\Models\Job::where('is_active', true)
        ->where('created_at', '>=', now()->subDays(7)) // Recent jobs
        ->get();
    
    $matchingService = new \App\Services\PssMatchingService();
    
    foreach ($jobs as $job) {
        $matchingService->findMatchesForJob($job);
    }
})->daily();
// Check for expiring PAYG jobs daily
    $schedule->call(function () {
        $jobs = \App\Models\Job::where('is_payg', true)
            ->where('payg_expires_at', '>', now())
            ->where('payg_expires_at', '<=', now()->addDays(3))
            ->where('payg_renewal_count', '<', 3)
            ->whereNull('payg_auto_renew') // Don't notify if auto-renew is enabled
            ->with('employer.user')
            ->get();
        
        foreach ($jobs as $job) {
            $daysLeft = now()->diffInDays($job->payg_expires_at);
            
            // Send notification to employer
            $job->employer->user->notify(new \App\Notifications\PaygJobExpiringSoon($job, $daysLeft));
            
            // Log notification
            activity()
                ->performedOn($job)
                ->withProperties(['days_left' => $daysLeft])
                ->log('payg_expiry_notification_sent');
        }
    })->dailyAt('09:00');
    
    // Process auto-renewals daily
    $schedule->call(function () {
        $jobs = \App\Models\Job::where('is_payg', true)
            ->where('payg_auto_renew', true)
            ->where('payg_expires_at', '<=', now()->addDays(1))
            ->where('payg_renewal_count', '<', 3)
            ->with('employer.user')
            ->get();
        
        foreach ($jobs as $job) {
            try {
                // Process auto-renewal payment
                $this->processAutoRenewal($job);
            } catch (\Exception $e) {
                // Notify employer of failed auto-renewal
                $job->employer->user->notify(new \App\Notifications\PaygAutoRenewFailed($job, $e->getMessage()));
            }
        }
    })->dailyAt('08:00');
}

private function processAutoRenewal($job)
{
    // Implement Stripe auto-renewal logic here
    // This would charge the employer's card and renew the job
}
protected $routeMiddleware = [
    // ... existing middleware
    'employer.exists' => \App\Http\Middleware\EnsureEmployerExists::class,
];
protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Illuminate\Http\Middleware\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array<string, array<int, class-string|string>>
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's middleware aliases.
     *
     * Aliases may be used to conveniently assign middleware to routes and groups.
     *
     * @var array<string, class-string|string>
     */
    protected $middlewareAliases = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'check.user.type' => \App\Http\Middleware\CheckUserType::class,
    ];
    
    // app/Http/Kernel.php
protected $routeMiddleware = [
    // ... existing middleware
    'subscription.check' => \App\Http\Middleware\CheckSubscription::class,
];
protected $routeMiddleware = [
    // ... existing middleware
    'employer.exists' => \App\Http\Middleware\EnsureEmployerExists::class,
     'pss.access' => \App\Http\Middleware\CheckPssAccess::class,
];
}