<?php

namespace App\Http\Controllers;

use App\Models\Appointment;
use App\Models\Patient;
use App\Models\MedicalHistory;
use App\Models\Branch;
use App\Models\Doctor;
use App\Models\DoctorAvailability;
use App\Notifications\AppointmentRequestNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class PharmacistController extends Controller
{
    public function dashboard()
    {
        $pharmacist = Auth::user()->pharmacist;
        $user = Auth::user();
        
        $stats = [
            'appointments' => Appointment::where('pharmacist_id', $pharmacist->id)->count(),
            'pending_appointments' => Appointment::where('pharmacist_id', $pharmacist->id)->where('status', 'pending')->count(),
            'patients' => Patient::count(),
        ];

        $recentAppointments = Appointment::where('pharmacist_id', $pharmacist->id)
            ->with(['patient', 'doctor'])
            ->latest()
            ->take(10)
            ->get();

        $notifications = $user->unreadNotifications()->latest()->take(10)->get();

        return view('pharmacist.dashboard', compact('stats', 'recentAppointments', 'notifications'));
    }

    public function createAppointment()
    {
        $branches = Branch::where('is_active', true)->get();
        $doctors = Doctor::where('is_verified', true)->where('is_active', true)->get();
        $patients = Patient::orderBy('first_name')->orderBy('last_name')->get();
        return view('pharmacist.create-appointment', compact('branches', 'doctors', 'patients'));
    }

    public function storeAppointment(Request $request)
    {
        $pharmacist = Auth::user()->pharmacist;

        $validated = $request->validate([
            'branch_id' => 'required|exists:branches,id',
            'patient_id' => 'nullable|exists:patients,id',
            'title' => 'nullable|string',
            'first_name' => 'nullable|string|required_without:patient_id',
            'last_name' => 'nullable|string|required_without:patient_id',
            'date_of_birth' => 'nullable|date',
            'gender' => 'nullable|in:Male,Female,Other',
            'identity_number' => 'nullable|string',
            'phone_area_code' => 'nullable|string',
            'phone_number' => 'nullable|string|required_without:patient_id',
            'email' => 'nullable|email',
            'payment_mode' => 'required|in:Cash Payment,Medical Aid Payment',
            'medical_aid_provider' => 'nullable|string|required_if:payment_mode,Medical Aid Payment',
            'membership_status' => 'nullable|string|required_if:payment_mode,Medical Aid Payment',
            'medical_aid_number' => 'nullable|string|required_if:payment_mode,Medical Aid Payment',
            'main_member' => 'nullable|string',
            'doctor_id' => 'nullable|exists:doctors,id',
            'consultation_type' => 'required|string',
            'appointment_type' => 'required|in:immediate,scheduled',
            'appointment_date' => 'nullable|date',
            'diagnosis_allergies' => 'nullable|string',
            'medicines_taken' => 'nullable|string',
            'still_using' => 'nullable|boolean',
            'additional_notes' => 'nullable|string',
            'resp_pattern' => 'nullable|string',
            'spo2' => 'nullable|numeric',
            'temperature' => 'nullable|numeric',
            'blood_pressure' => 'nullable|string',
            'pulse_rate' => 'nullable|integer',
            'rbs' => 'nullable|numeric',
            'blood_glucose' => 'nullable|numeric',
            'bmi' => 'nullable|numeric',
            'additional_medical_notes' => 'nullable|string',
            'pharmacist_signature' => 'required|string',
            'client_signature' => 'required|string',
        ]);

        // Get or create patient
        if (!empty($validated['patient_id'])) {
            $patient = Patient::findOrFail($validated['patient_id']);
        } else {
            $patient = Patient::firstOrCreate(
                ['identity_number' => $validated['identity_number'] ?? Str::random(10)],
                [
                    'patient_id' => 'PAT' . str_pad(Patient::count() + 1, 8, '0', STR_PAD_LEFT),
                    'title' => $validated['title'],
                    'first_name' => $validated['first_name'],
                    'last_name' => $validated['last_name'],
                    'date_of_birth' => $validated['date_of_birth'],
                    'gender' => $validated['gender'],
                    'phone_area_code' => $validated['phone_area_code'],
                    'phone_number' => $validated['phone_number'],
                    'email' => $validated['email'],
                    'payment_mode' => $validated['payment_mode'],
                    'medical_aid_number' => $validated['medical_aid_number'] ?? null,
                    'main_member' => $validated['membership_status'] ?? $validated['main_member'] ?? null,
                ]
            );
        }

        // Create medical history if provided
        if (!empty($validated['diagnosis_allergies']) || !empty($validated['medicines_taken'])) {
            MedicalHistory::create([
                'patient_id' => $patient->id,
                'diagnosis_allergies' => $validated['diagnosis_allergies'],
                'medicines_taken' => $validated['medicines_taken'],
                'still_using' => $validated['still_using'] ?? false,
                'additional_notes' => $validated['additional_notes'],
            ]);
        }

        // Generate video call room ID for Jitsi Meet
        // Note: Google Meet links must be created through Google Calendar API
        // We use Jitsi Meet as the primary video call solution (works without API setup)
        $videoCallRoomId = null;
        $googleMeetLink = null;
        
        if ($validated['appointment_type'] === 'immediate' || $validated['appointment_type'] === 'scheduled') {
            // Generate unique room ID for Jitsi Meet
            $videoCallRoomId = 'beautez-' . Str::random(16);
            // google_meet_link remains null - can be added manually later if needed
            // To create real Google Meet links, integrate with Google Calendar API:
            // https://developers.google.com/calendar/api/guides/create-events
        }

        // Create appointment
        $appointment = Appointment::create([
            'patient_id' => $patient->id,
            'doctor_id' => $validated['doctor_id'],
            'pharmacist_id' => $pharmacist->id,
            'branch_id' => $validated['branch_id'],
            'consultation_type' => $validated['consultation_type'],
            'appointment_type' => $validated['appointment_type'],
            'appointment_date' => $validated['appointment_date'] ?? now(),
            'status' => $validated['appointment_type'] === 'immediate' ? 'pending' : 'pending',
            'video_call_room_id' => $videoCallRoomId,
            'google_meet_link' => $googleMeetLink,
            'additional_medical_notes' => $validated['additional_medical_notes'],
            'pharmacist_signature' => $validated['pharmacist_signature'],
            'client_signature' => $validated['client_signature'],
        ]);

        // Send notification to doctor if appointment is assigned
        if ($appointment->doctor_id && $appointment->doctor) {
            $doctorUser = $appointment->doctor->user;
            if ($doctorUser) {
                try {
                    $doctorUser->notify(new AppointmentRequestNotification($appointment));
                } catch (\Exception $e) {
                    // Log error but continue - database notification will still work
                    \Log::warning('Failed to send email notification to doctor: ' . $e->getMessage());
                }
            }
        }

        // Create vitals if provided
        if (!empty($validated['resp_pattern']) || !empty($validated['spo2']) || !empty($validated['temperature']) || !empty($validated['blood_glucose']) || !empty($validated['bmi'])) {
            \App\Models\Vitals::create([
                'appointment_id' => $appointment->id,
                'resp_pattern' => $validated['resp_pattern'],
                'spo2' => $validated['spo2'],
                'temperature' => $validated['temperature'],
                'blood_pressure' => $validated['blood_pressure'],
                'pulse_rate' => $validated['pulse_rate'],
                'rbs' => $validated['rbs'],
                'blood_glucose' => $validated['blood_glucose'],
                'bmi' => $validated['bmi'],
            ]);
        }

        // Handle file uploads
        if ($request->hasFile('documents')) {
            foreach ($request->file('documents') as $file) {
                $path = $file->store('patient-documents', 'public');
                \App\Models\PatientDocument::create([
                    'appointment_id' => $appointment->id,
                    'file_path' => $path,
                    'file_name' => $file->getClientOriginalName(),
                    'file_type' => $file->getMimeType(),
                    'file_size' => $file->getSize(),
                ]);
            }
        }

        if ($validated['appointment_type'] === 'immediate') {
            return redirect()->route('pharmacist.video-call', $appointment->id)
                ->with('success', 'Appointment created. Connecting to doctor...');
        }

        return redirect()->route('pharmacist.appointments')
            ->with('success', 'Appointment created successfully.');
    }

    public function appointments()
    {
        $pharmacist = Auth::user()->pharmacist;
        $appointments = Appointment::where('pharmacist_id', $pharmacist->id)
            ->with(['patient', 'doctor', 'branch'])
            ->latest()
            ->get();

        return view('pharmacist.appointments', compact('appointments'));
    }

    public function videoCall($id)
    {
        $appointment = Appointment::with(['patient', 'doctor'])->findOrFail($id);
        return view('pharmacist.video-call', compact('appointment'));
    }

    public function prescriptions()
    {
        $pharmacist = Auth::user()->pharmacist;
        
        // Get prescriptions for appointments handled by this pharmacist
        $appointmentIds = Appointment::where('pharmacist_id', $pharmacist->id)->pluck('id');
        
        $prescriptions = \App\Models\Prescription::whereIn('appointment_id', $appointmentIds)
            ->with(['patient', 'doctor', 'appointment', 'items'])
            ->latest()
            ->get();

        return view('pharmacist.prescriptions', compact('prescriptions'));
    }

    public function getDoctorAvailability($doctorId)
    {
        $doctor = Doctor::findOrFail($doctorId);
        $availabilities = DoctorAvailability::where('doctor_id', $doctor->id)
            ->where('is_available', true)
            ->get()
            ->map(function($avail) {
                return [
                    'day_of_week' => $avail->day_of_week,
                    'start_time' => $avail->start_time ? (is_string($avail->start_time) ? date('H:i', strtotime($avail->start_time)) : $avail->start_time->format('H:i')) : null,
                    'end_time' => $avail->end_time ? (is_string($avail->end_time) ? date('H:i', strtotime($avail->end_time)) : $avail->end_time->format('H:i')) : null,
                ];
            });
        
        // Get existing appointments for the doctor
        $appointments = Appointment::where('doctor_id', $doctor->id)
            ->where('status', '!=', 'cancelled')
            ->whereNotNull('appointment_date')
            ->get(['appointment_date']);
        
        return response()->json([
            'availabilities' => $availabilities,
            'booked_slots' => $appointments->pluck('appointment_date')->map(function($date) {
                return $date->format('Y-m-d H:i:s');
            })
        ]);
    }

    public function notifications()
    {
        $user = Auth::user();
        $notifications = $user->notifications()->latest()->paginate(20);
        return view('pharmacist.notifications', compact('notifications'));
    }

    public function markNotificationRead($id)
    {
        $notification = Auth::user()->notifications()->findOrFail($id);
        $notification->markAsRead();
        return back()->with('success', 'Notification marked as read.');
    }

    public function markAllNotificationsRead()
    {
        Auth::user()->unreadNotifications->markAsRead();
        return back()->with('success', 'All notifications marked as read.');
    }
}

