<?php

namespace App\Models;

use CodeIgniter\Model;

class WhatsappInviteLogModel extends Model
{
    protected $table            = 'whatsapp_invites_log';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;

    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;

    protected $allowedFields    = [
        'parent_id',
        'email',
        'class_section_id',
        'link_id',
        'status',
        'error_message',
        'sent_at',
    ];

    protected $useTimestamps = false; // we handle sent_at manually
    protected $createdField  = '';
    protected $updatedField  = '';

    // Validation (optional)
    protected $validationRules = [
        'parent_id'        => 'required|integer',
        'email'            => 'required|valid_email|max_length[255]',
        'status'           => 'required|max_length[20]',
        'class_section_id' => 'permit_empty|integer',
        'link_id'          => 'permit_empty|integer',
    ];

    protected $validationMessages = [];
    protected $skipValidation     = false;

    /**
     * Log a successful send.
     */
    public function logSuccess(int $parentId, string $email, ?int $classSectionId = null, ?int $linkId = null): bool
    {
        return (bool) $this->insert([
            'parent_id'        => $parentId,
            'email'            => $email,
            'class_section_id' => $classSectionId,
            'link_id'          => $linkId,
            'status'           => 'sent',
            'error_message'    => null,
            'sent_at'          => utc_now(),
        ]);
    }

    /**
     * Log a failure with error message.
     */
    public function logFailure(int $parentId, string $email, string $error, ?int $classSectionId = null, ?int $linkId = null): bool
    {
        return (bool) $this->insert([
            'parent_id'        => $parentId,
            'email'            => $email,
            'class_section_id' => $classSectionId,
            'link_id'          => $linkId,
            'status'           => 'failed',
            'error_message'    => $error,
            'sent_at'          => utc_now(),
        ]);
    }

    /**
     * Get logs for a specific term, parent, or section (optional helper).
     */
    public function getLogs(?int $parentId = null, ?int $classSectionId = null): array
    {
        $builder = $this->builder();

        if ($parentId) {
            $builder->where('parent_id', $parentId);
        }
        if ($classSectionId) {
            $builder->where('class_section_id', $classSectionId);
        }

        return $builder->orderBy('sent_at', 'DESC')->get()->getResultArray();
    }
}
