<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\EmpCompanyDetails;

class PresenceController extends Controller
{
    /**
     * Get the appropriate presence channel name for the authenticated user
     */
    public function getPresenceChannel()
    {
        $user = Auth::user();
        $userTable = $this->getUserTable($user);
        
        if ($userTable === 'emp') {
            return "presence-emp.{$user->id}";
        } else {
            return "presence-user.{$user->id}";
        }
    }

    /**
     * Get workspace presence channel for the authenticated user
     */
    public function getWorkspacePresenceChannel()
    {
        $user = Auth::user();
        $userTable = $this->getUserTable($user);
        
        $workspaceId = $this->getWorkspaceId($user, $userTable);
        
        return "presence-workspace.{$workspaceId}";
    }

    /**
     * Get user info for presence channel
     */
    public function getPresenceData()
    {
        $user = Auth::user();
        $userTable = $this->getUserTable($user);
        
        $userInfo = [
            'id' => $user->id,
            'type' => $userTable,
            'name' => $this->getUserName($user, $userTable),
            'email' => $user->email,
            'avatar' => $this->getUserAvatar($user, $userTable),
            'last_seen' => now()->toISOString()
        ];

        return response()->json([
            'success' => true,
            'data' => $userInfo
        ]);
    }

    /**
     * Get all presence channels the user should subscribe to
     */
    public function getPresenceChannels()
    {
        $user = Auth::user();
        $userTable = $this->getUserTable($user);
        
        $channels = [
            'personal' => $this->getPresenceChannel(),
            'workspace' => $this->getWorkspacePresenceChannel()
        ];

        return response()->json([
            'success' => true,
            'channels' => $channels
        ]);
    }

    /**
     * Determine user table type
     */
    public function getUserTable($user = null)
    {
        if (!$user) {
            $user = Auth::user();
        }
        if ($user instanceof User) {
            return 'user';
        }
        if ($user instanceof EmpCompanyDetails) {
            return 'emp';
        }
        return 'user';
    }

    /**
     * Get workspace ID for the user
     */
    private function getWorkspaceId($user, $userTable)
    {
        if ($userTable === 'emp') {
            return $user->workspace_id ?? 1;
        } else {
            return $user->current_workspace_id ?? 1;
        }
    }

    /**
     * Get user display name
     */
    private function getUserName($user, $userTable)
    {
        if ($userTable === 'emp' && $user instanceof EmpCompanyDetails) {
            if ($user->relationLoaded('empPersonalDetails') && $user->empPersonalDetails) {
                $details = $user->empPersonalDetails;
                $fullName = trim(($details->first_name ?? '') . ' ' . ($details->middle_name ?? '') . ' ' . ($details->last_name ?? ''));
                if (!empty(trim($fullName))) {
                    return $fullName;
                }
            }
            
            // Fallback: extract name from email
            $email = $user->employee_email ?? 'Unknown User';
            if ($email !== 'Unknown User' && strpos($email, '@') !== false) {
                $emailPart = explode('@', $email)[0];
                return ucwords(str_replace(['.', '_', '-'], ' ', $emailPart));
            }
            
            return $email;
        } else {
            return $user->name ?? $user->email ?? 'Unknown User';
        }
    }

    /**
     * Get user avatar
     */
    private function getUserAvatar($user, $userTable)
    {
        if ($userTable === 'emp' && $user instanceof EmpCompanyDetails) {
            if ($user->relationLoaded('tierEmpPersonalDetail') && $user->tierEmpPersonalDetail) {
                return $user->tierEmpPersonalDetail->image ?? '/img/profile.jpeg';
            }
            return '/img/profile.jpeg';
        } else {
            return $user->image ?? '/img/profile.jpeg';
        }
    }
}
