<?php

namespace App\Models;

use App\Core\Security;
use App\Core\Database;

/**
 * ChatbotRule Model
 * Handles the chatbot_rules table with encryption for Gemini API key.
 */
class ChatbotRule extends BaseModel
{
    protected static string $table = 'chatbot_rules';

    /**
     * Find chatbot rules for a company
     */
    public static function findAllByCompany(int $companyId)
    {
        self::ensureColumnsExist();

        $rules = Database::select(
            "SELECT * FROM " . static::$table . " WHERE company_id = ? ORDER BY id DESC",
            [$companyId]
        );

        foreach ($rules as &$rule) {
            if (!empty($rule['gemini_api_key'])) {
                $rule['gemini_api_key'] = Security::decrypt($rule['gemini_api_key']);
            }
            if (!empty($rule['elevenlabs_api_key'])) {
                $rule['elevenlabs_api_key'] = Security::decrypt($rule['elevenlabs_api_key']);
            }
        }

        return $rules;
    }

    /**
     * Find active chatbot rule for a specific company and session
     */
    public static function findActiveForRule(int $companyId, ?int $sessionId = null)
    {
        self::ensureColumnsExist();

        if ($sessionId) {
            $rule = Database::selectOne(
                "SELECT * FROM " . static::$table . " WHERE company_id = ? AND (session_id = ? OR session_id IS NULL) AND is_active = 1 LIMIT 1",
                [$companyId, $sessionId]
            );
        } else {
            $rule = Database::selectOne(
                "SELECT * FROM " . static::$table . " WHERE company_id = ? AND is_active = 1 LIMIT 1",
                [$companyId]
            );
        }

        if ($rule) {
            if (!empty($rule['gemini_api_key'])) {
                $rule['gemini_api_key'] = Security::decrypt($rule['gemini_api_key']);
            }
            if (!empty($rule['elevenlabs_api_key'])) {
                $rule['elevenlabs_api_key'] = Security::decrypt($rule['elevenlabs_api_key']);
            }
        }

        return $rule;
    }

    /**
     * Create or update chatbot rule securely
     */
    public static function saveSecure(array $data)
    {
        self::ensureColumnsExist();

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

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

        if (isset($data['id'])) {
            $id = $data['id'];
            unset($data['id']);
            self::update($id, $data);
            return $id;
        } else {
            return self::create($data);
        }
    }

    /**
     * Helper to run ALTER TABLE to make sure gemini_api_key exists in chatbot_rules
     */
    private static function ensureColumnsExist()
    {
        static $checked = false;
        if ($checked) return;
        try {
            // Check if gemini_api_key exists
            $columns = Database::select("SHOW COLUMNS FROM " . static::$table . " LIKE 'gemini_api_key'");
            if (empty($columns)) {
                Database::execute("ALTER TABLE " . static::$table . " ADD COLUMN gemini_api_key VARCHAR(512) DEFAULT NULL AFTER ai_prompt");
            }

            // Check if elevenlabs_api_key exists
            $elColumns = Database::select("SHOW COLUMNS FROM " . static::$table . " LIKE 'elevenlabs_api_key'");
            if (empty($elColumns)) {
                Database::execute("ALTER TABLE " . static::$table . " ADD COLUMN elevenlabs_api_key VARCHAR(512) DEFAULT NULL AFTER gemini_api_key");
            }

            // Check if elevenlabs_voice_id exists
            $voiceColumns = Database::select("SHOW COLUMNS FROM " . static::$table . " LIKE 'elevenlabs_voice_id'");
            if (empty($voiceColumns)) {
                Database::execute("ALTER TABLE " . static::$table . " ADD COLUMN elevenlabs_voice_id VARCHAR(100) DEFAULT NULL AFTER elevenlabs_api_key");
            }
            $checked = true;
        } catch (\Exception $e) {
            error_log("Failed to ensure chatbot_rules columns: " . $e->getMessage());
        }
    }
}
