<?php

namespace App\Http\Controllers\Staff;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\JoinRequest;
use App\Models\WaitingQueue;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class JoinRequestController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    
    /**
     * Display pending join requests
     */
    public function index()
    {
        $requests = JoinRequest::with(['patient', 'tenant.visitTypes'])
            ->pending()
            ->orderBy('requested_at')
            ->paginate(20);
            
        return view('staff.join-requests.index', compact('requests'));
    }
    
    /**
     * Show specific join request details
     */
    public function show(JoinRequest $joinRequest)
    {
        $joinRequest->load(['patient', 'tenant', 'respondedBy']);
        return view('staff.join-requests.show', compact('joinRequest'));
    }
    
    /**
     * Approve join request and add patient to queue
     */
    public function approve(Request $request, JoinRequest $joinRequest)
    {
        $request->validate([
            'notes' => 'nullable|string|max:500',
            'visit_type' => 'nullable|string|max:255'
        ]);
        
        if (!$joinRequest->isPending()) {
            return response()->json([
                'success' => false,
                'message' => __('This request has already been processed.')
            ], 400);
        }
        
        try {
            DB::transaction(function () use ($joinRequest, $request) {
                // Load the patient relationship if not already loaded
                if (!$joinRequest->relationLoaded('patient')) {
                    $joinRequest->load('patient');
                }
                
                // Approve the request
                $joinRequest->approve(Auth::user(), $request->notes);
                
                // Add patient to waiting queue with selected visit type
                $queueEntry = $joinRequest->patient->joinQueueAt(
                    $joinRequest->tenant_id,
                    $request->visit_type
                );
                
                // Link the join request to the queue entry (if needed)
                $joinRequest->update(['queue_entry_id' => $queueEntry->id ?? null]);
            });
            
            $message = __('Join request approved and patient added to queue.');
            if ($request->visit_type) {
                $message .= ' ' . __('Visit type: ') . $request->visit_type;
            }
            
            return response()->json([
                'success' => true,
                'message' => $message
            ]);
            
        } catch (\Exception $e) {
            \Log::error('Failed to approve join request', [
                'join_request_id' => $joinRequest->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => __('Failed to approve request: ') . $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Reject join request
     */
    public function reject(Request $request, JoinRequest $joinRequest)
    {
        $request->validate([
            'notes' => 'nullable|string|max:500'
        ]);
        
        if (!$joinRequest->isPending()) {
            return response()->json([
                'success' => false,
                'message' => __('This request has already been processed.')
            ], 400);
        }
        
        $joinRequest->reject(Auth::user(), $request->notes);
        
        return response()->json([
            'success' => true,
            'message' => __('Join request rejected.')
        ]);
    }
    
    /**
     * Get pending requests count for notifications
     */
    public function getPendingCount()
    {
        $count = JoinRequest::pending()->count();
        
        return response()->json([
            'pending_count' => $count
        ]);
    }
}
