<?php

namespace App\Http\Controllers;

use App\Models\App;
use App\Models\PricingPlan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class UserDashboardController extends Controller
{
    public function index()
    {
        $user    = Auth::user();
        $company = $user->company;
        $plan    = $user->plan_id ? PricingPlan::find($user->plan_id) : null;

        if ($plan && $plan->plugins) {
            $pluginKeys = array_filter(array_map('trim', explode(',', $plan->plugins)));
            $apps = App::where('is_active', true)->whereIn('app_key', $pluginKeys)->get();
        } else {
            $apps = App::where('is_active', true)->get();
        }

        return view('user.dashboard', compact('user', 'company', 'plan', 'apps'));
    }

    public function whatsappSetup()
    {
        $user = Auth::user();

        // api_token is the single token used for webhook URL, verify token, and API auth
        if (!$user->api_token) {
            $token = strtoupper(Str::random(20));
            $user->update(['api_token' => $token, 'verify_token' => $token]);
            $user->refresh();
        } elseif ($user->verify_token !== $user->api_token) {
            // Keep verify_token in sync if they drifted
            $user->update(['verify_token' => $user->api_token]);
            $user->refresh();
        }

        // Use admin-configured site URL so it works in production, not just locally
        $siteUrl         = rtrim(\App\Models\Setting::get('site_url', config('app.url')), '/');
        $webhookUrl      = $siteUrl . '/webhook/whatsapp?token=' . $user->api_token;
        $webhookVerified = false;

        return view('user.whatsapp-setup', compact('user', 'webhookUrl', 'webhookVerified'));
    }

    public function apiDocs()
    {
        $user = Auth::user();

        if (!$user->api_token) {
            $token = strtoupper(Str::random(20));
            $user->update(['api_token' => $token, 'verify_token' => $token]);
            $user->refresh();
        } elseif ($user->verify_token !== $user->api_token) {
            $user->update(['verify_token' => $user->api_token]);
            $user->refresh();
        }

        $baseUrl = url('/api/v1');
        return view('user.api-docs', compact('user', 'baseUrl'));
    }

    public function saveWhatsappSetup(Request $request)
    {
        $request->validate([
            'access_token'    => ['required', 'string'],
            'phone_number_id' => ['required', 'string'],
            'waba_id'         => ['required', 'string'],
        ]);

        Auth::user()->update([
            'access_token'    => $request->access_token,
            'phone_number_id' => $request->phone_number_id,
            'waba_id'         => $request->waba_id,
        ]);

        return redirect()->route('user.whatsapp-setup')
            ->with('success', 'WhatsApp Business API settings saved successfully.');
    }
}
