<?php

namespace App\Controllers;

use App\Models\AiMessageDraftModel;
use App\Models\MessageLogModel;
use Throwable;

/**
 * Shared staff-review inbox for every guest-facing AI-drafted message —
 * see CreateAiMessageDraftsTable's migration comment. send() is a real
 * SMS via the same Hubtel account/pattern already used everywhere else
 * in this app (UserController::resetPassword(), CommunicationController::
 * send()) — this costs real SMS credits per send, which is exactly why
 * nothing here sends without either a manager clicking Send or the
 * tenant having explicitly opted the category into autosend.
 */
class GuestMessageDraftController extends BaseController
{
    private const CATEGORY_LABELS = [
        'post_checkout_thankyou' => 'Post-Checkout Thank-You',
        'pre_arrival_upsell'     => 'Pre-Arrival Upsell',
    ];

    public function index()
    {
        $category = $this->request->getGet('category');
        $category = isset(self::CATEGORY_LABELS[$category]) ? $category : null;

        $model = new AiMessageDraftModel();

        return view('guest_message_drafts/index', [
            'pageTitle'  => 'Guest Message Drafts',
            'drafts'     => $model->pending($category),
            'category'   => $category,
            'categories' => self::CATEGORY_LABELS,
            'countAll'   => (new AiMessageDraftModel())->countPending(),
        ]);
    }

    public function send(int $id)
    {
        $model = new AiMessageDraftModel();
        $draft = $model->find($id);

        if ($draft === null || $draft->status !== 'pending') {
            return redirect()->to('guest-message-drafts')->with('error', 'Draft not found or already handled.');
        }

        self::reallySend($draft, $this->currentUserId());

        return redirect()->to('guest-message-drafts')->with('success', 'Message sent.');
    }

    public function dismiss(int $id)
    {
        $model = new AiMessageDraftModel();
        $draft = $model->find($id);

        if ($draft === null || $draft->status !== 'pending') {
            return redirect()->to('guest-message-drafts')->with('error', 'Draft not found or already handled.');
        }

        $model->update($id, ['status' => 'dismissed']);
        $this->logActivity('communication', 'Dismissed an AI-drafted ' . (self::CATEGORY_LABELS[$draft->category] ?? $draft->category) . ' message.');

        return redirect()->to('guest-message-drafts')->with('success', 'Draft dismissed.');
    }

    /**
     * The one real send path — called either by a manager clicking Send
     * here, or automatically right after a draft is created if the
     * tenant has that category's autosend flag on (see
     * CheckOutController::draftPostCheckoutThankYou()). $sentBy is null
     * for an autosend, a real user id for a manual send. Always writes
     * to message_log (channel 'sms') regardless of outcome, same as
     * every other outbound message in this app.
     */
    public static function reallySend(object $draft, ?int $sentBy): bool
    {
        $success = false;
        $raw     = '';

        try {
            $outcome = service('hubtelService')->sendSms($draft->to_phone, $draft->draft_text);
            $success = $outcome['success'];
            $raw     = $outcome['raw'];
        } catch (Throwable $e) {
            $raw = $e->getMessage();
        }

        $model = new AiMessageDraftModel();
        $model->update($draft->id, [
            'status'  => $success ? 'sent' : 'failed',
            'sent_at' => date('Y-m-d H:i:s'),
            'sent_by' => $sentBy,
        ]);

        (new MessageLogModel())->record(
            $draft->guest_id,
            'sms',
            'ai_' . $draft->category,
            $draft->to_phone,
            $success,
            $raw,
            $draft->draft_text,
            $sentBy,
        );

        return $success;
    }
}
