<?php

namespace App\Models;

/**
 * ContactGroup Model
 * Manages groupings/lists of contacts for broadcast campaigns.
 */
class ContactGroup extends BaseModel
{
    protected static string $table = 'contact_groups';

    /**
     * Attach a contact to this group
     */
    public static function attachContact(int $groupId, int $contactId)
    {
        $exists = \App\Core\Database::selectOne(
            "SELECT 1 FROM contact_group_relations WHERE group_id = ? AND contact_id = ?",
            [$groupId, $contactId]
        );
        
        if (!$exists) {
            \App\Core\Database::execute(
                "INSERT INTO contact_group_relations (group_id, contact_id) VALUES (?, ?)",
                [$groupId, $contactId]
            );
        }
        return true;
    }

    /**
     * Remove a contact from this group
     */
    public static function detachContact(int $groupId, int $contactId)
    {
        \App\Core\Database::execute(
            "DELETE FROM contact_group_relations WHERE group_id = ? AND contact_id = ?",
            [$groupId, $contactId]
        );
        return true;
    }

    /**
     * Get all raw contact records for a group (Decryption needed after fetch)
     */
    public static function getRawContacts(int $groupId)
    {
        return \App\Core\Database::select(
            "SELECT c.* FROM contacts c 
             JOIN contact_group_relations cgr ON c.id = cgr.contact_id 
             WHERE cgr.group_id = ?",
            [$groupId]
        );
    }
}
