<?php
namespace App\Services;

use App\Models\AutomationRule;
use App\Models\Contact;
use App\Models\Conversation;
use App\Models\Message;
use App\Models\Setting;
use App\Models\User;

class AutomationService {

    /**
     * Process incoming message against automation rules
     */
    public static function processIncoming(array $contact, array $conversation, string $messageText, bool $isNewContact = false): void {
        $rules = AutomationRule::getActiveRules();
        $matched = false;

        // 1. Check Working Hours Out-of-Office Rule
        if (self::isOutsideWorkingHours()) {
            $outOfOfficeText = Setting::getVal('out_of_office_reply');
            if (!empty($outOfOfficeText)) {
                self::dispatchAutoReply($contact, $conversation, $outOfOfficeText);
                return;
            }
        }

        // 2. Check Welcome Rule for New Contacts
        if ($isNewContact) {
            foreach ($rules as $rule) {
                if ($rule['trigger_event'] === 'welcome_new_contact') {
                    self::executeRule($rule, $contact, $conversation);
                    $matched = true;
                    break;
                }
            }
        }

        // 3. Keyword Triggers
        $cleanText = strtolower(trim($messageText));

        foreach ($rules as $rule) {
            if ($rule['trigger_event'] === 'message_exact') {
                $keywords = array_map('trim', explode(',', strtolower($rule['trigger_keyword'] ?? '')));
                if (in_array($cleanText, $keywords, true)) {
                    self::executeRule($rule, $contact, $conversation);
                    $matched = true;
                    break;
                }
            } elseif ($rule['trigger_event'] === 'message_contains') {
                $keywords = array_map('trim', explode(',', strtolower($rule['trigger_keyword'] ?? '')));
                foreach ($keywords as $kw) {
                    if (!empty($kw) && str_contains($cleanText, $kw)) {
                        self::executeRule($rule, $contact, $conversation);
                        $matched = true;
                        break 2;
                    }
                }
            }
        }
    }

    /**
     * Execute an automation rule's actions and replies
     */
    protected static function executeRule(array $rule, array $contact, array $conversation): void {
        // Execute Action
        if (!empty($rule['action_type']) && $rule['action_type'] !== 'none') {
            switch ($rule['action_type']) {
                case 'add_tag':
                    if (!empty($rule['action_value'])) {
                        Contact::addTag((int)$contact['id'], (int)$rule['action_value']);
                    }
                    break;

                case 'assign_agent':
                    if (!empty($rule['action_value'])) {
                        $agentId = (int)$rule['action_value'];
                        Contact::update((int)$contact['id'], ['assigned_to' => $agentId]);
                        Conversation::update((int)$conversation['id'], ['assigned_user_id' => $agentId]);
                    }
                    break;

                case 'move_stage':
                    if (!empty($rule['action_value'])) {
                        $stageId = (int)$rule['action_value'];
                        Contact::update((int)$contact['id'], ['stage_id' => $stageId]);
                    }
                    break;
            }
        }

        // Send Auto Reply
        if (!empty($rule['reply_content'])) {
            $replyText = self::interpolateVariables($rule['reply_content'], $contact);
            self::dispatchAutoReply($contact, $conversation, $replyText);
        }
    }

    /**
     * Dispatch auto reply via WhatsApp and record in database
     */
    protected static function dispatchAutoReply(array $contact, array $conversation, string $text): void {
        // Send via WhatsApp API
        $res = WhatsAppService::sendText($contact['phone_number'], $text);
        $metaMsgId = $res['meta_message_id'] ?? ('wamid.AUTO_' . uniqid());

        // Store message in database
        Message::create([
            'conversation_id' => (int)$conversation['id'],
            'contact_id'      => (int)$contact['id'],
            'user_id'         => null, // Bot / System
            'direction'       => 'outbound',
            'message_type'    => 'text',
            'content'         => $text,
            'meta_message_id' => $metaMsgId,
            'status'          => 'sent',
            'created_at'      => date('Y-m-d H:i:s')
        ]);

        Conversation::updateLastMessage((int)$conversation['id'], $text, 'outbound');
    }

    /**
     * Check if current time is outside configured business working hours
     */
    protected static function isOutsideWorkingHours(): bool {
        $enabled = Setting::getVal('working_hours_enabled', '0');
        if ($enabled !== '1' && $enabled !== true && $enabled !== 'true') {
            return false;
        }

        $tz = Setting::getVal('timezone', 'Asia/Kolkata');
        date_default_timezone_set($tz);

        $now = date('H:i');
        $start = Setting::getVal('working_hours_start', '09:00');
        $end = Setting::getVal('working_hours_end', '18:00');

        return ($now < $start || $now > $end);
    }

    /**
     * Replace template variables like {{name}} with contact data
     */
    protected static function interpolateVariables(string $text, array $contact): string {
        $vars = [
            '{{name}}'    => $contact['name'] ?? 'there',
            '{{phone}}'   => $contact['phone_number'] ?? '',
            '{{company}}' => $contact['company'] ?? '',
            '{{email}}'   => $contact['email'] ?? ''
        ];

        return strtr($text, $vars);
    }
}
