<?php

namespace App\Controllers;

use App\Models\MessageLogModel;
use Throwable;

/**
 * Manager-only view over message_log (WhatsApp/SMS sends — see
 * App\Libraries\MessagingService — plus manually-logged calls/notes,
 * see MessageLogModel::logManual()). send() is the one write path here:
 * a real, manually-composed SMS via the same Hubtel account already
 * used for staff password resets (UserController::resetPassword()) —
 * this costs the hotel real SMS credits per send, unlike every other
 * screen redesigned this session which was read-only or record-keeping
 * only.
 */
class CommunicationController extends BaseController
{
    public function index()
    {
        $model = new MessageLogModel();

        $filters = [
            'date_from' => $this->request->getGet('date_from') ?: '',
            'date_to'   => $this->request->getGet('date_to') ?: '',
            'channel'   => $this->request->getGet('channel') ?: '',
            'status'    => $this->request->getGet('status') ?: '',
        ];

        $model->select('message_log.*, guests.full_name as guest_name, users.full_name as sent_by_name')
            ->join('guests', 'guests.id = message_log.guest_id', 'left')
            ->join('users', 'users.id = message_log.sent_by', 'left');

        if ($filters['date_from'] !== '') {
            $model->where('message_log.created_at >=', $filters['date_from'] . ' 00:00:00');
        }

        if ($filters['date_to'] !== '') {
            $model->where('message_log.created_at <=', $filters['date_to'] . ' 23:59:59');
        }

        if ($filters['channel'] !== '') {
            $model->where('message_log.channel', $filters['channel']);
        }

        if ($filters['status'] !== '') {
            $model->where('message_log.status', $filters['status']);
        }

        $perPage = (int) ($this->request->getGet('per_page') ?: 10);
        $perPage = in_array($perPage, [10, 25, 50], true) ? $perPage : 10;

        $entries = $model->orderBy('message_log.created_at', 'desc')->paginate($perPage);

        return view('communication/index', [
            'pageTitle' => 'Communication',
            'entries'   => $entries,
            'pager'     => $model->pager,
            'perPage'   => $perPage,
            'filters'   => $filters,
            'stats'     => $this->stats(),
        ]);
    }

    /**
     * Always the tenant-wide totals regardless of the filter row (same
     * convention as every other redesigned list page's KPI cards this
     * session).
     */
    private function stats(): array
    {
        return [
            'sms'      => (new MessageLogModel())->where('channel', 'sms')->countAllResults(),
            'whatsapp' => (new MessageLogModel())->where('channel', 'whatsapp')->countAllResults(),
            'calls'    => (new MessageLogModel())->where('channel', 'call')->countAllResults(),
            'failed'   => (new MessageLogModel())->where('status', 'failed')->countAllResults(),
        ];
    }

    /**
     * Manager composes a phone number (optionally tied to an existing
     * guest) and free-text — sent as a real SMS via Hubtel, logged
     * either way (sent or failed) so it shows up in the table exactly
     * like every automated message. WhatsApp isn't offered here: a
     * free-form WhatsApp send generally needs an approved Meta template
     * or an open customer-service window, neither of which this form can
     * safely guarantee, unlike SMS which has no such restriction.
     */
    public function send()
    {
        $phone   = trim((string) $this->request->getPost('to_phone'));
        $message = trim((string) $this->request->getPost('message'));
        $guestId = (int) $this->request->getPost('guest_id') ?: null;

        if ($phone === '' || $message === '') {
            return redirect()->to('communication')->with('error', 'Enter a phone number and a message.');
        }

        $success = false;
        $raw     = '';

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

        (new MessageLogModel())->record($guestId, 'sms', 'manual_send', $phone, $success, $raw, $message, $this->currentUserId());

        $this->logActivity('communication', 'Sent a manual SMS to ' . $phone . ($success ? '.' : ' (failed).'));

        return redirect()->to('communication')->with(
            $success ? 'success' : 'error',
            $success ? 'Message sent.' : 'Message failed to send — ' . $raw,
        );
    }
}
