<?php

namespace Modules\WhatsApp\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\WhatsApp\Entities\WaChannel;
use Modules\WhatsApp\Entities\WaSetting;

class WaSettingsController extends Controller
{
    public function index()
    {
        if (!auth()->user()->can('whatsapp.access_settings')) {
            abort(403, 'Unauthorized action.');
        }
        $businessId = request()->session()->get('user.business_id');

        // Make sure starter templates exist so the dropdown isn't empty.
        \Modules\WhatsApp\Entities\Services\DefaultTemplates::ensure($businessId);

        $settings  = WaSetting::allFor($businessId);
        $channels  = WaChannel::where('business_id', $businessId)->pluck('label', 'id');
        $templates = \Modules\WhatsApp\Entities\WaTemplate::where('business_id', $businessId)
            ->where('active', true)->pluck('name', 'name');

        // Automated-event registry, grouped for the UI.
        $events = collect(\Modules\WhatsApp\Entities\Services\WaEvents::all())
            ->groupBy('group')->toArray();

        $aiUsage = $this->aiUsage((int) $businessId);

        return view('whatsapp::settings.index', compact('settings', 'channels', 'templates', 'events', 'aiUsage'));
    }

    /**
     * Month-to-date AI usage + estimated cost from the shared ai_usage_logs.
     * Soft dependency on AiCore — returns null if the table isn't there.
     */
    private function aiUsage(int $businessId): ?array
    {
        if (!\Illuminate\Support\Facades\Schema::hasTable('ai_usage_logs')) {
            return null;
        }

        $rows = \Illuminate\Support\Facades\DB::table('ai_usage_logs')
            ->where('business_id', $businessId)
            ->where('created_at', '>=', now()->startOfMonth())
            ->selectRaw('provider, model, COUNT(*) calls, SUM(tokens_in) tin, SUM(tokens_out) tout, SUM(ok=0) failed')
            ->groupBy('provider', 'model')
            ->get();

        $pricing = config('whatsapp.ai_pricing', []);
        $calls = 0; $tin = 0; $tout = 0; $failed = 0; $cost = 0.0; $models = [];

        foreach ($rows as $r) {
            $rate = $this->rateFor((string) $r->model, $pricing);
            $rowCost = ($r->tin / 1e6) * $rate['in'] + ($r->tout / 1e6) * $rate['out'];
            $calls += (int) $r->calls;
            $tin += (int) $r->tin;
            $tout += (int) $r->tout;
            $failed += (int) $r->failed;
            $cost += $rowCost;
            $models[] = [
                'provider' => $r->provider, 'model' => $r->model,
                'calls' => (int) $r->calls, 'tin' => (int) $r->tin, 'tout' => (int) $r->tout,
                'cost' => $rowCost,
            ];
        }

        return [
            'month'   => now()->format('M Y'),
            'calls'   => $calls,
            'failed'  => $failed,
            'tin'     => $tin,
            'tout'    => $tout,
            'tokens'  => $tin + $tout,
            'cost'    => $cost,
            'models'  => $models,
        ];
    }

    private function rateFor(string $model, array $pricing): array
    {
        $m = strtolower($model);
        foreach ($pricing as $key => $rate) {
            if ($key !== 'default' && $key !== '' && str_contains($m, $key)) {
                return $rate;
            }
        }
        return $pricing['default'] ?? ['in' => 0.15, 'out' => 0.60];
    }

    public function update(Request $request)
    {
        if (!auth()->user()->can('whatsapp.access_settings')) {
            abort(403, 'Unauthorized action.');
        }
        $businessId = request()->session()->get('user.business_id');

        $data = $request->validate([
            'notify_emails'      => 'nullable|string|max:500',
            'opt_out_keyword'    => 'nullable|string|max:40',
            'default_channel'    => 'nullable|integer',
            'gap_min'            => 'nullable|integer|min:0|max:600',
            'gap_max'            => 'nullable|integer|min:0|max:600',
            'typing_per_char_ms' => 'nullable|integer|min:0|max:1000',
            'typing_min_ms'      => 'nullable|integer|min:0|max:60000',
            'typing_max_ms'      => 'nullable|integer|min:0|max:60000',
            'low_stock_number'   => 'nullable|string|max:30',
        ]);

        WaSetting::set($businessId, 'enabled', $request->boolean('enabled') ? '1' : '0');
        WaSetting::set($businessId, 'ai_enabled', $request->boolean('ai_enabled') ? '1' : '0');
        WaSetting::set($businessId, 'ai_can_book', $request->boolean('ai_can_book') ? '1' : '0');
        WaSetting::set($businessId, 'powered_by', $request->boolean('powered_by') ? '1' : '0');

        // Anti-ban pacing (keep gap_max >= gap_min).
        $gapMin = (int) ($data['gap_min'] ?? 4);
        $gapMax = max($gapMin, (int) ($data['gap_max'] ?? 12));
        WaSetting::set($businessId, 'gap_min', (string) $gapMin);
        WaSetting::set($businessId, 'gap_max', (string) $gapMax);
        WaSetting::set($businessId, 'typing_per_char_ms', (string) ($data['typing_per_char_ms'] ?? 55));
        WaSetting::set($businessId, 'typing_min_ms', (string) ($data['typing_min_ms'] ?? 900));
        WaSetting::set($businessId, 'typing_max_ms', (string) ($data['typing_max_ms'] ?? 9000));
        WaSetting::set($businessId, 'notify_emails', $data['notify_emails'] ?? '');
        WaSetting::set($businessId, 'opt_out_keyword', $data['opt_out_keyword'] ?? 'STOP');
        WaSetting::set($businessId, 'default_channel', (string) ($data['default_channel'] ?? ''));

        // Inventory low-stock alert.
        WaSetting::set($businessId, 'low_stock_enabled', $request->boolean('low_stock_enabled') ? '1' : '0');
        WaSetting::set($businessId, 'low_stock_number', $data['low_stock_number'] ?? '');

        // Automated-event toggles + chosen templates (driven by the WaEvents registry).
        foreach (\Modules\WhatsApp\Entities\Services\WaEvents::all() as $key => $event) {
            WaSetting::set($businessId, $event['toggle'], $request->boolean($event['toggle']) ? '1' : '0');
            $tpl = $request->input($event['template']);
            if (!empty($tpl)) {
                WaSetting::set($businessId, $event['template'], (string) $tpl);
            }
        }

        // Keep the is_default flag in sync with the chosen default channel.
        if (!empty($data['default_channel'])) {
            WaChannel::where('business_id', $businessId)->update(['is_default' => false]);
            WaChannel::where('business_id', $businessId)->where('id', $data['default_channel'])
                ->update(['is_default' => true]);
        }

        return redirect()->route('whatsapp.settings.index')->with('status', [
            'success' => 1, 'msg' => __('whatsapp::lang.saved'),
        ]);
    }
}
