requireRole('patient')) { return $r; } $db = \Config\Database::connect(); $query = $db->query(" SELECT doctors.id AS doctor_id, users.name, doctors.specialization FROM users JOIN doctors ON doctors.user_id = users.id WHERE users.role = 'doctor' "); $data['doctors'] = $query->getResult(); $patientModel = new PatientModel(); $userId = (int) session()->get('id'); $patient = $patientModel->where('user_id', $userId)->first(); $data['myAppointments'] = []; if ($patient) { $data['myAppointments'] = $db->query(' SELECT a.id, a.appointment_date, a.appointment_time, a.status, u.name AS doctor_name, doctors.specialization FROM appointments a JOIN doctors ON doctors.id = a.doctor_id JOIN users u ON u.id = doctors.user_id WHERE a.patient_id = ? ORDER BY a.appointment_date ASC, a.appointment_time ASC ', [$patient['id']])->getResult(); } return view('patient/dashboard', $data); } public function bookAppointment() { if ($r = $this->requireRole('patient')) { return $r; } $rules = [ 'doctor_id' => 'required|integer', 'date' => 'required|valid_date', 'time' => 'required', ]; if (! $this->validate($rules)) { return redirect()->back()->withInput(); } $appointmentModel = new AppointmentModel(); $patientModel = new PatientModel(); $userId = (int) session()->get('id'); $patient = $patientModel->where('user_id', $userId)->first(); if (! $patient) { return redirect()->back()->with('error', 'Patient profile not found. Please contact support.'); } $appointmentTime = $this->normalizeAppointmentTime((string) $this->request->getPost('time')); $data = [ 'patient_id' => $patient['id'], 'doctor_id' => (int) $this->request->getPost('doctor_id'), 'appointment_date' => $this->request->getPost('date'), 'appointment_time' => $appointmentTime, ]; $taken = $appointmentModel ->where('doctor_id', $data['doctor_id']) ->where('appointment_date', $data['appointment_date']) ->where('appointment_time', $appointmentTime) ->whereIn('status', ['pending', 'approved']) ->first(); if ($taken) { return redirect()->back()->withInput()->with('error', 'That time slot is already booked for this doctor. Please choose another date or time.'); } if (! $appointmentModel->insert($data)) { return redirect()->back()->withInput()->with('error', 'Could not book appointment.'); } return redirect()->to(site_url('patient/dashboard'))->with('success', 'Appointment requested.'); } }