<?php

namespace App\Models;

class MessageLogModel extends TenantModel
{
    protected $table         = 'message_log';
    protected $primaryKey    = 'id';
    protected $returnType    = 'object';
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = '';

    protected $allowedFields = [
        'guest_id',
        'channel',
        'message_type',
        'to_phone',
        'body',
        'status',
        'sent_by',
        'provider_response',
    ];

    /**
     * Whether an attempt (sent or failed — "tried" is what matters here,
     * not "succeeded", same convention bookings.reminder_sent_at already
     * uses) already exists this calendar year — SendBirthdayOffers'
     * once-a-year dedup, reusing this table rather than a parallel
     * tracking column/table.
     */
    public function alreadySentThisYear(int $guestId, string $messageType): bool
    {
        return $this->where('guest_id', $guestId)
            ->where('message_type', $messageType)
            ->where('YEAR(created_at)', date('Y'), false)
            ->countAllResults() > 0;
    }

    public function record(?int $guestId, string $channel, string $messageType, string $toPhone, bool $success, string $providerResponse, ?string $body = null, ?int $sentBy = null): void
    {
        $this->insert([
            'guest_id'          => $guestId,
            'channel'           => $channel,
            'message_type'      => $messageType,
            'to_phone'          => $toPhone,
            'body'              => $body,
            'status'            => $success ? 'sent' : 'failed',
            'sent_by'           => $sentBy,
            'provider_response' => substr($providerResponse, 0, 5000),
        ]);
    }

    /**
     * A staff-typed record of a call or note that happened outside this
     * app — there's no telephony integration to auto-capture a call, so
     * this is how one lands in the guest's communication timeline at all.
     * `channel` is 'call' or 'note'; `provider_response` (normally a
     * gateway's raw reply) doubles as the note body here — see
     * AllowManualMessageLogEntries's doc comment for why no separate
     * column was added just for this. Also mirrored into `body` so the
     * Communication page can read ->body uniformly for every row type
     * instead of special-casing manual entries. $sentBy is the staff
     * member who logged it (GuestController::logCommunication() passes
     * currentUserId()) — null only for entries logged before this
     * parameter existed.
     */
    public function logManual(int $guestId, string $channel, string $notes, ?string $phone, ?int $sentBy = null): void
    {
        $this->insert([
            'guest_id'          => $guestId,
            'channel'           => $channel,
            'message_type'      => 'manual_log',
            'to_phone'          => $phone,
            'body'              => $notes,
            'status'            => 'logged',
            'sent_by'           => $sentBy,
            'provider_response' => $notes,
        ]);
    }
}
