<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Pusher\Pusher;
use Illuminate\Support\Facades\Log;

class PusherController extends Controller
{
    public function authenticate(Request $request)
    {
        $pusher = new Pusher(
            config('broadcasting.connections.pusher.key'),
            config('broadcasting.connections.pusher.secret'),
            config('broadcasting.connections.pusher.app_id'),
            config('broadcasting.connections.pusher.options')
        );

        $socketId = $request->input('socket_id');
        $channelName = $request->input('channel_name');

        // Get authenticated user - try both guards
        $user = auth('api')->user() ?? auth()->user();

        if (!$user) {
            return response()->json(['message' => 'Unauthenticated'], 401);
        }

        // For private channels, authorize access
        if (strpos($channelName, 'private-chat.') === 0) {
            $conversationId = str_replace('private-chat.', '', $channelName);
            $conversation = \App\Models\Conversation::find($conversationId);

            if (!$conversation) {
                return response()->json(['error' => 'Conversation not found'], 404);
            }
            $getUserTable = $this->getUserTable()=='customer' ? 'user' : 'emp';
            // Check if user is participant
            $authType = $getUserTable;
            $authId = $user->id;

            $isP1 = $conversation->participant1_id == $authId && $conversation->participant1_type === $authType;
            $isP2 = $conversation->participant2_id == $authId && $conversation->participant2_type === $authType;

            if (!$isP1 && !$isP2) {
                return response()->json(['error' => 'Access denied'], 403);
            }
        }
        // For personal notification channels, authorize access
        elseif (strpos($channelName, 'private-user.') === 0) {
            $userId = str_replace('private-user.', '', $channelName);
            $authId = $user->id;

            if ((int) $authId !== (int) $userId) {
                return response()->json(['error' => 'Access denied'], 403);
            }
        }
        elseif (strpos($channelName, 'private-emp.') === 0) {
            $empId = str_replace('private-emp.', '', $channelName);
            $authId = $user->id;

            // Check if user is an employee and matches the emp ID
            if (!($user instanceof \App\Models\EmpCompanyDetails)) {
                return response()->json(['error' => 'Access denied'], 403);
            }

            if ((int) $authId !== (int) $empId) {
                return response()->json(['error' => 'Access denied'], 403);
            }
        }

        // For presence channels, include user info
        if (strpos($channelName, 'presence-') === 0) {
            $presenceData = $this->getPresenceData($user, $channelName);
            $auth = $pusher->authorizePresenceChannel($channelName, $socketId, $user->id, $presenceData);
        } else {
            $auth = $pusher->authorizeChannel($channelName, $socketId);
        }

        return response($auth);
    }

    /**
     * Get presence data for the user
     */
    private function getPresenceData($user, $channelName)
    {
        $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 $userInfo;
    }


    private function getUserName($user, $userTable)
    {
        if ($userTable === 'emp' && $user instanceof \App\Models\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 \App\Models\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';
        }
    }
}
