<?php

namespace App\Controllers\View;

use App\Models\UserModel;
use App\Models\StudentModel;
use App\Models\TeacherClassModel;
use App\Models\StudentClassModel;
use App\Models\UserRoleModel;
use App\Models\MessageModel;
use App\Controllers\BaseController;

class MessagesController extends BaseController
{
    protected $messageModel;

    public function __construct()
    {
        //$this->messageModel = new MessageModel();
    }

    public function inbox()
    {
        $userId = session()->get('user_id');
        $receivedMessages = $this->messageModel->getInboxMessages($userId);

        return view('messages/inbox', [
            'receivedMessages' => $receivedMessages
        ]);
    }

    public function sent()
    {
        $userId = session()->get('user_id');
        $sentMessages = $this->messageModel->getSentMessages($userId);

        return view('messages/sent', [
            'sentMessages' => $sentMessages
        ]);
    }

    public function drafts()
    {
        $userId = session()->get('user_id');
        $draftMessages = $this->messageModel->getDraftMessages($userId);

        return view('messages/drafts', [
            'draftMessages' => $draftMessages
        ]);
    }

    public function trash()
    {
        $userId = session()->get('user_id');
        $trashedMessages = $this->messageModel->getTrashedMessages($userId);

        return view('messages/trash', [
            'trashedMessages' => $trashedMessages
        ]);
    }

    public function index()
    {
        $userRoleModel = new UserRoleModel();
        //$role = session()->get('role');
        $userId = session()->get('user_id');
        // Fetch the user role from the user_roles and roles tables
        $role = $userRoleModel->select('roles.name')
            ->join('roles', 'roles.id = user_roles.role_id')
            ->where('user_roles.user_id', $userId)
            ->get()
            ->getRowArray();

        // Fetch received messages based on role
        $db = \Config\Database::connect();
        $builder = $db->table('messages');
        $builder->select('messages.*, users.firstname AS sender_name');
        $builder->join('users', 'messages.sender_id = users.id');
        $builder->where('messages.recipient_id', $userId);
        $query = $builder->get();
        $receivedMessages = $query->getResultArray();

        return view('/messages', [
            'receivedMessages' => $receivedMessages,
            'role' => $role['name']
        ]);
    }

    public function send()
    {
        $db = \Config\Database::connect();
        $userRoleModel = new UserRoleModel();
        //$role = session()->get('role');
        $userId = session()->get('user_id');
        // Fetch the user role from the user_roles and roles tables
        $role = $userRoleModel->select('roles.name')
            ->join('roles', 'roles.id = user_roles.role_id')
            ->where('user_roles.user_id', $userId)
            ->get()
            ->getRowArray();

        // Handle file upload (if any)
        $attachmentPath = null;
        $file = $this->request->getFile('attachment');
        if ($file && $file->isValid() && !$file->hasMoved()) {
            $attachmentPath = $file->store();
        }

        // Determine recipient based on role or input
        $recipientId = $this->getRecipientId($role);

        // Prepare data for insertion
        $data = [
            'sender_id' => $userId,
            'recipient_id' => $recipientId,
            'subject' => $this->request->getPost('subject'),
            'message' => $this->request->getPost('message'),
            'sent_datetime' => utc_now(),
            'message_number' => $this->generateMessageNumber(),
            'priority' => $this->request->getPost('priority') ?: 'normal',
            'attachment' => $attachmentPath,
            'status' => 'sent'
        ];

        $builder = $db->table('messages');
        $builder->insert($data);

        return redirect()->to(base_url('messages'))->with('status', 'Message sent successfully');
    }

    public function receive()
    {
        $userId = session()->get('user_id');

        $db = \Config\Database::connect();
        $builder = $db->table('messages');
        $builder->select('messages.*, users.firstname AS sender_name');
        $builder->join('users', 'messages.sender_id = users.id');
        $builder->where('messages.recipient_id', $userId);
        $builder->orderBy('sent_datetime', 'DESC');
        $query = $builder->get();
        $receivedMessages = $query->getResultArray();

        // Mark messages as read
        foreach ($receivedMessages as $message) {
            if ($message['read_status'] == 0) {
                $this->markAsRead($message['id']);
            }
        }
        // Assuming $role['name'] contains the role name
        //$roleName = strtolower($role['name']); // Convert role name to lowercase if needed

        // Construct the view path dynamically
        // $viewPath = '/' . $roleName . '/' . $roleName . '_messages';

        // Return the view
        //return view($viewPath, ['receivedMessages' => $receivedMessages]);
    }

    private function generateMessageNumber()
    {
        return 'MSG-' . date('YmdHis');
    }

    private function markAsRead($messageId)
    {
        $db = \Config\Database::connect();
        $builder = $db->table('messages');
        $builder->where('id', $messageId);
        $builder->update([
            'read_status' => 1,
            'read_datetime' => utc_now()
        ]);
    }

    private function getRecipientId($role)
    {
        // You can customize this logic to retrieve recipient_id based on the role or input  
        switch (strtolower($role['name'])) {
            case 'teacher':
                return 1; // Example: return teacher's ID
            case 'parent':
                return 2; // Example: return parent's ID
            case 'admin':
                return 3; // Example: return admin's ID
            case 'student':
                return 4; // Example: return student's ID
            case 'guest':
                return 5; // Example: return guest's ID
            case 'administrator':
                return 6; // Example: return administrator's ID
            default:
                throw new \Exception('Invalid role: ' . $role['name']);
        }
    }

    public function getRecipients($type)
    {
        $recipients = [];
        $teacherClassModel = new TeacherClassModel();
        $studentClassModel = new StudentClassModel();
        $studentsModel = new StudentModel();
        $teacherClasses = $teacherClassModel->findAll();

        if ($type === 'teacher') {
            $userModel = new UserModel(); // Assuming the UserModel is in the App\Models namespace

            foreach ($teacherClasses as $teacher) {
                $user = $userModel->find($teacher['teacher_id']);
                if ($user) {
                    $recipients[] = [
                        'id' => $teacher['teacher_id'],
                        'name' => $user['firstname'] . ' ' . $user['lastname']
                    ];
                }
            }
        } elseif ($type === 'parent') {
            foreach ($teacherClasses as $class) {
                $students = $studentClassModel
                    ->active()
                    ->where('student_class.class_section_id', $class['class_section_id'])
                    ->findAll();

                foreach ($students as $student) {
                    $studentData = $studentsModel
                        ->where('id', $student['student_id'])
                        ->where('is_active', 1)
                        ->first();
                    if ($studentData) {
                        if ($studentData['firstparent']) {
                            $recipients[] = [
                                'id' => $studentData['parent_id'],
                                'name' => $studentData['firstparent']
                            ];
                        }
                        if ($studentData['secondparent']) {
                            $recipients[] = [
                                'id' => $studentData['secondparent_user_id'],
                                'name' => $studentData['secondparent']
                            ];
                        }
                    }
                }
            }
        }

        return $this->response->setJSON($recipients);
    }
}
