<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Helpers\Mailer;
use App\Models\Message;
use App\Models\AuditLog;
use App\Models\User;

class MessageController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Auth::requireLogin();
    }

    public function inbox()
    {
        $model = new Message();
        $messages = $model->getInbox(Auth::id());
        $this->view('messages/inbox', ['messages' => $messages]);
    }

    public function sent()
    {
        $model = new Message();
        $messages = $model->getSent(Auth::id());
        $this->view('messages/sent', ['messages' => $messages]);
    }

    public function compose()
    {
        $this->view('messages/compose');
    }

    public function searchUsers()
    {
        $query = isset($_GET['q']) ? trim($_GET['q']) : '';
        if (strlen($query) < 1) {
            $this->json([]);
        }
        $stmt = $this->db->prepare("SELECT id, first_name, other_names, last_name, name, email FROM users WHERE approval_status = 'approved' AND (first_name LIKE ? OR last_name LIKE ? OR other_names LIKE ? OR name LIKE ? OR email LIKE ?) ORDER BY first_name ASC LIMIT 15");
        $like = "%{$query}%";
        $stmt->execute([$like, $like, $like, $like, $like]);
        $users = $stmt->fetchAll(\PDO::FETCH_OBJ);

        $results = array_map(function ($u) {
            $fullName = $u->first_name ? trim($u->first_name . ' ' . $u->other_names . ' ' . $u->last_name) : $u->name;
            return [
                'id' => $u->id,
                'name' => $fullName,
                'email' => $u->email,
                'label' => "{$fullName} ({$u->email})",
            ];
        }, $users);

        $this->json($results);
    }

    public function send()
    {
        $subject = $_POST['subject'] ?? '';
        $body = $_POST['body'] ?? '';
        $recipients = $_POST['recipients'] ?? [];
        $sendToAll = isset($_POST['send_to_all']);

        if (empty($subject) || empty($body)) {
            $_SESSION['error'] = 'Subject and body are required';
            $this->redirect('/messages/compose');
        }

        $messageModel = new Message();
        $messageId = $messageModel->create([
            'sender_id' => Auth::id(),
            'subject' => $subject,
            'body' => $body,
            'priority' => $_POST['priority'] ?? 'normal',
        ]);

        if ($sendToAll) {
            $userModel = new User();
            $allUsers = $userModel->where('approval_status', 'approved');
            foreach ($allUsers as $user) {
                $this->db->prepare("INSERT INTO message_recipients (message_id, recipient_id) VALUES (?, ?)")->execute([$messageId, $user->id]);
                $recipientName = $user->first_name ? trim($user->first_name . ' ' . $user->last_name) : $user->name;
                Mailer::sendMessageNotification($user->email, $recipientName, Auth::user()->name, $subject, $body);
            }
        } elseif (!empty($recipients)) {
            foreach ($recipients as $userId) {
                $this->db->prepare("INSERT INTO message_recipients (message_id, recipient_id) VALUES (?, ?)")->execute([$messageId, $userId]);
            }
            $userModel = new User();
            foreach ($recipients as $userId) {
                $user = $userModel->find($userId);
                if ($user && $user->email) {
                    $recipientName = $user->first_name ? trim($user->first_name . ' ' . $user->last_name) : $user->name;
                    Mailer::sendMessageNotification($user->email, $recipientName, Auth::user()->name, $subject, $body);
                }
            }
        }

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'message.send', 'messages', $messageId, "Sent message: {$subject}");

        $_SESSION['success'] = 'Message sent successfully';
        $this->redirect('/messages/sent');
    }

    public function show($params)
    {
        $id = $params['id'] ?? null;
        $stmt = $this->db->prepare("SELECT m.*, u.name as sender_name FROM messages m LEFT JOIN users u ON m.sender_id = u.id WHERE m.id = ?");
        $stmt->execute([$id]);
        $message = $stmt->fetch(\PDO::FETCH_OBJ);

        if (!$message) {
            $_SESSION['error'] = 'Message not found';
            $this->redirect('/messages/inbox');
        }

        $this->db->prepare("UPDATE message_recipients SET is_read = 1, read_at = NOW() WHERE message_id = ? AND recipient_id = ?")->execute([$id, Auth::id()]);

        $this->view('messages/view', ['message' => $message]);
    }

    public function delete($params)
    {
        $id = $params['id'] ?? null;
        $this->db->prepare("UPDATE message_recipients SET is_archived = 1 WHERE message_id = ? AND recipient_id = ?")->execute([$id, Auth::id()]);
        $_SESSION['success'] = 'Message archived';
        $this->redirect('/messages/inbox');
    }
}
