<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class WhatsAppController extends Controller
{
    protected function gatewayUrl(): string
    {
        return rtrim((string) env('WA_GATEWAY_URL', 'http://127.0.0.1:3001'), '/');
    }

    protected function gatewayToken(): string
    {
        return (string) env('WA_GATEWAY_TOKEN', '');
    }

    protected function api()
    {
        return Http::withHeaders([
            'Accept' => 'application/json',
            'X-WA-TOKEN' => $this->gatewayToken(),
        ])->timeout(30);
    }

    protected function normalizePhone(?string $phone): ?string
    {
        if (!$phone) {
            return null;
        }

        $phone = preg_replace('/[^0-9+]/', '', $phone);

        if (str_starts_with($phone, '+62')) {
            $phone = substr($phone, 1);
        } elseif (str_starts_with($phone, '08')) {
            $phone = '62' . substr($phone, 1);
        } elseif (str_starts_with($phone, '8')) {
            $phone = '62' . $phone;
        }

        $phone = preg_replace('/[^0-9]/', '', $phone);

        return $phone !== '' ? $phone : null;
    }

    public function status()
    {
        $response = $this->api()->get($this->gatewayUrl() . '/api/wa/status');

        if (!$response->successful()) {
            return response()->json([
                'connected' => false,
                'status' => 'offline',
                'message' => 'WA gateway tidak merespons.',
            ], 200);
        }

        return response()->json($response->json());
    }

    public function qr()
    {
        $response = $this->api()->get($this->gatewayUrl() . '/api/wa/qr');

        if (!$response->successful()) {
            return response()->json([
                'ok' => false,
                'message' => 'Gagal mengambil QR.',
            ], 500);
        }

        return response()->json($response->json());
    }

    public function logout()
    {
        $response = $this->api()->post($this->gatewayUrl() . '/api/wa/logout');

        if (!$response->successful()) {
            return response()->json([
                'ok' => false,
                'message' => 'Gagal logout WhatsApp.',
            ], 500);
        }

        return response()->json([
            'ok' => true,
            'message' => 'WhatsApp berhasil logout.',
        ]);
    }

    public function sendOrder(Order $order)
    {
        if (!$order->customer_phone) {
            return response()->json([
                'ok' => false,
                'need_scan' => false,
                'message' => 'Nomor customer kosong.',
            ], 422);
        }

        $phone = $this->normalizePhone($order->customer_phone);

        if (!$phone) {
            return response()->json([
                'ok' => false,
                'need_scan' => false,
                'message' => 'Nomor customer tidak valid.',
            ], 422);
        }

        $statusResponse = $this->api()->get($this->gatewayUrl() . '/api/wa/status');

        if (!$statusResponse->successful()) {
            return response()->json([
                'ok' => false,
                'need_scan' => true,
                'message' => 'WA gateway tidak aktif.',
            ], 200);
        }

        $statusJson = $statusResponse->json();
        $connected = (bool) ($statusJson['connected'] ?? false);

        if (!$connected) {
            return response()->json([
                'ok' => false,
                'need_scan' => true,
                'message' => 'WhatsApp belum login.',
            ], 200);
        }

        $message = \App\Models\Setting::buildWaMessage($order);

        $sendResponse = $this->api()->post($this->gatewayUrl() . '/api/wa/send', [
            'phone' => $phone,
            'message' => $message,
        ]);

        if (!$sendResponse->successful()) {
            return response()->json([
                'ok' => false,
                'need_scan' => false,
                'message' => $sendResponse->json('message') ?: 'Gagal mengirim WhatsApp.',
            ], 500);
        }

        if (!$order->wa_notified_at) {
            $order->forceFill([
                'wa_notified_at' => now(),
            ])->save();
        }

        return response()->json([
            'ok' => true,
            'need_scan' => false,
            'message' => 'WhatsApp berhasil dikirim.',
        ]);
    }
}