<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class UpdateExpiredSubscriptions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'subscriptions:update-expired {--user= : Process only for a specific user ID}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update status of expired subscriptions to expired';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $userId = $this->option('user');

        if ($userId) {
            // Process only for specific user
            $this->processUser($userId);
            return;
        }

        $expiredCount = \App\Models\Subscription::where('status', 'active')
            ->where('end_date', '<', now())
            ->update(['status' => 'expired']);

        $this->info("Updated {$expiredCount} expired subscriptions.");

        // Process users with no active subscriptions (including newly expired)
        $usersWithNoActiveSubs = \App\Models\User::whereDoesntHave('subscriptions', function ($query) {
            $query->where('status', 'active');
        })->pluck('id');

        foreach ($usersWithNoActiveSubs as $uid) {
            $this->processUser($uid);
        }
    }

    private function processUser($userId)
    {
        $proBlockTypes = ['Pricing', 'Video', 'Countdown'];
        $totalBlocksRemoved = 0;
        $totalPagesUpdated = 0;

        // Get pages for this user
        $pages = \App\Models\Page::where('user_id', $userId)->get();

        foreach ($pages as $page) {
            // Remove pro blocks
            $removedBlocks = \App\Models\Block::where('page_id', $page->id)
                ->whereIn('type', $proBlockTypes)
                ->delete();

            $totalBlocksRemoved += $removedBlocks;

            if ($removedBlocks > 0) {
                // Reorder remaining blocks
                $remainingBlocks = \App\Models\Block::where('page_id', $page->id)
                    ->orderBy('order')
                    ->get();

                foreach ($remainingBlocks as $index => $block) {
                    $block->update(['order' => $index]);
                }

                $totalPagesUpdated++;
            }

            // Remove slug (pro feature)
            $page->update(['slug' => null]);
        }

        $this->info("Removed {$totalBlocksRemoved} pro blocks from {$totalPagesUpdated} pages for user {$userId}.");
    }
}
