<?php

namespace App\Models;

use App\Core\Security;

/**
 * MessageLog Model
 * Records every message sent or received with full payload encryption.
 */
class MessageLog extends BaseModel
{
    protected static string $table = 'messages_log';

    /**
     * Securely log a new message
     */
    public static function logMessage(array $data)
    {
        if (!empty($data['contact_phone'])) {
            $data['contact_phone_hash'] = Security::blindIndex($data['contact_phone']);
            $data['contact_phone'] = Security::encrypt($data['contact_phone']);
        }
        
        if (!empty($data['message_body'])) {
            $data['message_body'] = Security::encrypt($data['message_body']);
        }

        if (!empty($data['media_url'])) {
            $data['media_url'] = Security::encrypt($data['media_url']);
        }

        try {
            return self::create($data);
        } catch (\PDOException $e) {
            // Handle duplicate entry gracefully
            if ($e->getCode() === '23000' || strpos($e->getMessage(), '1062') !== false) {
                error_log("[MessageLog] Duplicate whatsapp_message_id: " . ($data['whatsapp_message_id'] ?? 'unknown'));
                // Retrieve and return existing log record
                if (!empty($data['whatsapp_message_id'])) {
                    $existing = \App\Core\Database::select(
                        "SELECT * FROM " . static::$table . " WHERE whatsapp_message_id = ? LIMIT 1",
                        [$data['whatsapp_message_id']]
                    );
                    if (!empty($existing)) {
                        return $existing[0];
                    }
                }
                return null;
            }
            throw $e;
        }
    }
}
