<?php

namespace App\Http\Livewire;

use App\Models\Post;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use WireUi\Traits\WireUiActions;

class AcceptPrinciples extends Component
{
    use WireUiActions;

    public bool $agreed = false;

    public function mount()
    {
        // Pre-check the checkbox if user has already accepted
        $user = Auth::guard('web')->user();
        if ($user && $user->hasAcceptedPrinciples()) {
            $this->agreed = true;
        }
    }

    public function accept()
    {
        $user = Auth::guard('web')->user();

        if (!$user) {
            $this->notification()->error(
                $title = __('Error'),
                $description = __('You must be logged in to accept the principles.')
            );
            return;
        }

        if (!$this->agreed) {
            $this->notification()->warning(
                $title = __('Confirmation required'),
                $description = __('Please check the box to confirm you accept the principles.')
            );
            return;
        }

        // Get the current principles post with active translation
        $principlesPost = $this->getCurrentPrinciplesPost();

        if (!$principlesPost || !$principlesPost->translations->first()) {
            $this->notification()->error(
                $title = __('Error'),
                $description = __('Unable to find the current principles document.')
            );
            return;
        }

        $translation = $principlesPost->translations->first();

        // Save acceptance with version tracking
        $user->update([
            'principles_terms_accepted' => [
                'post_id' => $principlesPost->id,
                'post_translation_id' => $translation->id,
                'locale' => $translation->locale,
                'from' => $translation->from,
                'updated_at' => $translation->updated_at->toDateTimeString(),
                'accepted_at' => now()->toDateTimeString(),
            ]
        ]);

        $this->notification()->success(
            $title = __('Thank you'),
            $description = __('Your acceptance has been recorded.')
        );

        // Refresh the component to show the acceptance status
        $this->dispatch('$refresh');
    }

    protected function getCurrentPrinciplesPost()
    {
        $locale = app()->getLocale();

        return Post::with(['translations' => function ($query) use ($locale) {
            $query->where('locale', 'like', $locale . '%')
                ->whereDate('from', '<=', now())
                ->where(function ($query) {
                    $query->whereDate('till', '>', now())->orWhereNull('till');
                })
                ->orderBy('updated_at', 'desc')
                ->limit(1);
        }])
        ->whereHas('category', function ($query) {
            $query->where('type', 'SiteContents\Static\Principles');
        })
        ->first();
    }

    public function render()
    {
        $user = Auth::guard('web')->user();
        $hasAccepted = $user && $user->hasAcceptedPrinciples();
        $needsReaccept = $user && $user->needsToReacceptPrinciples();
        $acceptedData = $user?->principles_terms_accepted;

        return view('livewire.accept-principles', [
            'user' => $user,
            'hasAccepted' => $hasAccepted,
            'needsReaccept' => $needsReaccept,
            'acceptedData' => $acceptedData,
        ]);
    }
}
