<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\ActivationCode;
use App\Models\Subscription;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ActivationController extends Controller
{
    public function show()
    {
        return view('frontend.premium.activate');
    }

    public function redeem(Request $request)
    {
        $request->validate([
            'code' => 'required|string|max:32',
        ], [
            'code.required' => 'Aktivasyon kodu boş bırakılamaz.',
        ]);

        $rawCode = strtoupper(preg_replace('/[^A-Z0-9\-]/', '', trim($request->code)));

        $code = ActivationCode::with('plan')
            ->where('code', $rawCode)
            ->first();

        if (! $code) {
            return back()->withInput()->withErrors(['code' => 'Geçersiz aktivasyon kodu. Kodu kontrol edip tekrar deneyin.']);
        }

        if ($code->isUsed()) {
            return back()->withInput()->withErrors(['code' => 'Bu aktivasyon kodu daha önce kullanılmış.']);
        }

        if ($code->isExpired()) {
            return back()->withInput()->withErrors(['code' => 'Bu aktivasyon kodunun süresi dolmuş.']);
        }

        $user = auth()->user();
        $plan = $code->plan;

        // Mevcut premium bitiş tarihine ekle (stack), yoksa şimdiden başla
        $baseDate  = ($user->premium_expires_at && $user->premium_expires_at->isFuture())
            ? $user->premium_expires_at
            : now();
        $newExpiry = $baseDate->addDays($plan->duration_days);

        DB::transaction(function () use ($code, $user, $plan, $newExpiry) {
            $code->update([
                'used_by' => $user->id,
                'used_at' => now(),
            ]);

            Subscription::create([
                'user_id'        => $user->id,
                'plan_id'        => $plan->id,
                'status'         => 'active',
                'starts_at'      => now(),
                'expires_at'     => $newExpiry,
                'payment_method' => 'activation_code',
                'payment_ref'    => $code->code,
            ]);

            $user->update([
                'membership'          => 'premium',
                'premium_expires_at'  => $newExpiry,
            ]);
        });

        return redirect()->route('premium.plans')->with('activation_success', [
            'plan'       => $plan->name,
            'expires_at' => $newExpiry->format('d.m.Y'),
        ]);
    }
}
