<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Subscription extends Model
{
    protected $fillable = [
        'user_id',
        'plan_id',
        'status',
        'start_date',
        'end_date',
    ];

    protected function casts(): array
    {
        return [
            'start_date' => 'date',
            'end_date' => 'date',
        ];
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function plan(): BelongsTo
    {
        return $this->belongsTo(Plan::class);
    }

    public function payments(): HasMany
    {
        return $this->hasMany(Payment::class);
    }

    protected static function boot()
    {
        parent::boot();

        static::updated(function ($subscription) {
            if ($subscription->status === 'expired' && $subscription->getOriginal('status') !== 'expired') {
                \Log::info('Subscription expired, removing pro blocks', ['subscription_id' => $subscription->id, 'user_id' => $subscription->user_id]);

                // Subscription just expired, remove pro blocks and slugs
                $proBlockTypes = ['Pricing', 'Video', 'Countdown'];

                $user = $subscription->user()->first();
                if ($user) {
                    $pages = $user->pages;

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

                        \Log::info('Removed pro blocks from page', ['page_id' => $page->id, 'removed' => $removed]);

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

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

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