<?php

namespace App\Controllers;

use App\Models\ConciergeConversationModel;
use App\Models\ConciergeMessageModel;

/**
 * Staff-facing inbox for the WhatsApp Concierge — see ConciergeService
 * and ConciergeWebhookController for how a conversation gets here.
 * Manager/front_desk only (see Lookups::$permissionModules['concierge']).
 */
class ConciergeController extends BaseController
{
    public function index()
    {
        $filter = $this->request->getGet('filter');
        $filter = in_array($filter, ['needs_staff', 'pending_reply'], true) ? $filter : null;

        $conversations = new ConciergeConversationModel();

        return view('concierge/index', [
            'pageTitle'      => 'WhatsApp Concierge',
            'conversations'  => $conversations->list($filter),
            'filter'         => $filter,
            'needsStaffCount' => $conversations->countNeedsStaff(),
            'pendingReplyCount' => $conversations->countPendingReply(),
        ]);
    }

    public function show(int $id)
    {
        $conversation = (new ConciergeConversationModel())
            ->select('concierge_conversations.*, guests.full_name as guest_name, guests.id as guest_id')
            ->join('guests', 'guests.id = concierge_conversations.guest_id', 'left')
            ->find($id);

        if ($conversation === null) {
            return redirect()->to('concierge')->with('error', 'Conversation not found.');
        }

        return view('concierge/show', [
            'pageTitle'    => 'Concierge Conversation',
            'conversation' => $conversation,
            'messages'     => (new ConciergeMessageModel())->forConversation($id),
        ]);
    }

    /** Staff approves a drafted AI reply — sends it for real over WhatsApp. */
    public function sendReply(int $conversationId, int $messageId)
    {
        $conversations = new ConciergeConversationModel();
        $conversation  = $conversations->find($conversationId);
        $message       = (new ConciergeMessageModel())->find($messageId);

        // (int) cast: the model's DB driver returns conversation_id as a
        // string, so a strict === against the route's real int would
        // never match — this bit a real test run before the cast was added.
        if ($conversation === null || $message === null || (int) $message->conversation_id !== $conversationId || $message->status !== 'pending') {
            return redirect()->to('concierge/' . $conversationId)->with('error', 'Reply not found or already handled.');
        }

        $success = service('conciergeService')->sendPendingReply($conversation, $message, $conversation->guest_id);

        $this->logActivity('concierge', ($success ? 'Sent' : 'Failed to send') . " an AI-drafted WhatsApp reply to {$conversation->phone}.");

        return redirect()->to('concierge/' . $conversationId)->with($success ? 'success' : 'error', $success ? 'Reply sent.' : 'Sending failed — check the WhatsApp integration settings.');
    }

    /** Staff declines to send a drafted AI reply — e.g. they'd rather reply themselves. */
    public function dismissReply(int $conversationId, int $messageId)
    {
        $messages = new ConciergeMessageModel();
        $message  = $messages->find($messageId);

        if ($message === null || (int) $message->conversation_id !== $conversationId || $message->status !== 'pending') {
            return redirect()->to('concierge/' . $conversationId)->with('error', 'Reply not found or already handled.');
        }

        $messages->update($messageId, ['status' => 'dismissed']);
        (new ConciergeConversationModel())->update($conversationId, ['pending_reply' => 0]);

        $this->logActivity('concierge', 'Dismissed an AI-drafted WhatsApp reply.');

        return redirect()->to('concierge/' . $conversationId)->with('success', 'Draft dismissed.');
    }

    public function resolve(int $id)
    {
        $conversations = new ConciergeConversationModel();

        if ($conversations->find($id) === null) {
            return redirect()->to('concierge')->with('error', 'Conversation not found.');
        }

        $conversations->update($id, [
            'needs_staff' => 0,
            'resolved_at' => date('Y-m-d H:i:s'),
            'resolved_by' => $this->currentUserId(),
        ]);

        $this->logActivity('concierge', "Marked concierge conversation #{$id} resolved.");

        return redirect()->to('concierge')->with('success', 'Conversation marked resolved.');
    }
}
