<?php

namespace App\Livewire\Dashboard;

use Illuminate\Support\Facades\Log;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use App\Models\ActivationKey;
use App\Models\Plan;
use Exception;
use Livewire\Component;

class Pricing extends Component
{
    public $plans;

    public $activation_key;

    public function mount(): void
    {
        $this->plans = config('app.plans');
    }

    public function choosePlan($pricing_id): void
    {
        $this->redirect(route('checkout', $pricing_id));
    }

    public function activateKey(): void
    {
        $this->validate([
            'activation_key' => 'required|alpha_num|max:30',
        ], [
            'activation_key.required' => 'You must enter an activation key.',
            'activation_key.alpha_num' => 'The activation key may only contain letters and numbers (no special characters).',
            'activation_key.max' => 'The activation key must not exceed 30 characters.',
        ]);

        $trimmedKey = trim((string) $this->activation_key);
        $activation = ActivationKey::query()->where('activation_key', $trimmedKey)
            ->where('is_activated', false)
            ->first();

        if ($activation) {
            if ($activation->price_id !== null) {
                $result = $this->addSubscription($activation->price_id);
            }
            if ($result) {
                $activation->is_activated = true;
                $activation->user_id = auth()->id();
                $activation->save();
                session()->flash('success', 'Activation key is valid and has been activated. Refresh page to see changes.');
                $this->reset('activation_key');
            } else {
                session()->flash('error', 'Something went wrong. Kindly drop a mail at contact@zemail.me to activate your subscription manually.');
            }
        } else {
            session()->flash('error', 'Invalid or already activated key.');
        }

    }

    private function addSubscription($price_id): bool
    {
        try {
            $plan = Plan::query()->where('pricing_id', $price_id)->firstOrFail();
            $user = auth()->user();
            $user->createOrGetStripeCustomer();
            $user->updateStripeCustomer([
                'address' => [
                    'postal_code' => '10001',
                    'country' => 'US',
                ],
                'name' => $user->name,
                'email' => $user->email,
            ]);
            $user->creditBalance($plan->price * 100, 'Premium Top-up for plan: '.$plan->name);
            $balance = $user->balance();
            $user->newSubscription('default', $plan->pricing_id)->create();

            $ends_at = $plan->monthly_billing == 1 ? now()->addMonth() : now()->addYear();
            $user->subscription('default')->cancelAt($ends_at);

            return true;
        } catch (Exception $e) {
            Log::error($e->getMessage());

            return false;
        }
    }

    public function render(): Factory|View
    {
        return view('livewire.dashboard.pricing');
    }
}
