<?php

namespace App\Http\Livewire;

use App\Models\User;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Component;
use Spatie\Activitylog\Models\Activity;

class MainPage extends Component
{
    public $lastLoginAt;
    public $user;
    public $profileType;

    public function mount()
    {
        $this->user = [
            'name' => getActiveProfile()->name,
            'firstName' => Str::words(getActiveProfile()->full_name, 1, ''),
        ];

        $profile = getActiveProfile();

        // For User profiles, skip current login to get truly previous login
        // For other profiles (Organization, Bank, etc.), show the most recent login
        $query = Activity::where('subject_id', $profile->id)
        ->where('subject_type', get_class($profile))
        ->where('event', 'login')
        ->whereNotNull('properties->old->login_at')
        ->latest('id');

        if (get_class($profile) === 'App\\Models\\User') {
            $query->skip(1);
        }

        $activityLog = $query->first();


        if (
            $activityLog &&
            isset($activityLog->properties['old']['login_at']) &&
            !empty($activityLog->properties['old']['login_at'])
        ) {
            $lastLoginAt = $activityLog->properties['old']['login_at'];
            $timestamp = strtotime($lastLoginAt);

            if ($timestamp !== false) {
                $causer = null;
                if (!empty($activityLog->causer_type) && !empty($activityLog->causer_id) && class_exists($activityLog->causer_type)) {
                    $causer = $activityLog->causer_type::find($activityLog->causer_id);
                }
                $causerName = $causer && isset($causer->name) ? $causer->name : __('unknown user');

                $showBy = !(
                    $activityLog->subject_type === $activityLog->causer_type &&
                    $activityLog->subject_id === $activityLog->causer_id
                );

                $this->lastLoginAt = Carbon::createFromTimestamp($timestamp)->diffForHumans()
                    . ($showBy ? ' ' . __('by') . ' ' . $causerName : '');
            } else {
                $this->lastLoginAt = '';
            }
        } else {
            $this->lastLoginAt = '';
        }

        $this->profileType = getActiveProfileType();
    }

    public function render()
    {
        return view('livewire.main-page');
    }
}
