<?php

namespace App\Controllers\Frontend;

use App\Controllers\FrontendBaseController;

class WhatsApp extends FrontendBaseController
{
    public $title = 'Send WhatsApp';
    public $menu = 'whatsapp';
    public $submenu = '';

    public function index()
    {
        return view('frontend/whatsapp/test', [
            'apiKey' => (string) (env('whatsapp.sample_api_key') ?? env('whatsapp.api_key') ?? '1234567890'),
            'sender' => (string) (env('whatsapp.sample_sender') ?? env('whatsapp.sender') ?? '62888xxxx'),
        ]);
    }

    public function send()
    {
        $apiKey = trim(post('api_key') ?? setting('whatsapp_api_key') ?? '');
        $sender = trim(post('sender') ?? setting('whatsapp_sender_number') ?? '');
        $number = trim(post('number') ?? '');
        $message = trim(post('message') ?? 'Hello from Laksh News');
        $footer = trim(post('footer') ?? (setting('company_name') ?? 'Laksh News'));

        if ($apiKey === '' || $sender === '' || $number === '') {
            return redirect()->to(url('whatsapp-test/result'))
                ->with('wa_status', \CodeIgniter\HTTP\ResponseInterface::HTTP_BAD_REQUEST)
                ->with('wa_url', null)
                ->with('wa_response', 'Missing parameters: api_key, sender, number');
        }

        $params = [
            'api_key' => $apiKey,
            'sender' => $sender,
            'number' => $number,
            'message' => $message,
            'footer' => $footer,
        ];

        $client = \Config\Services::curlrequest();
        try {
            $resp = $client->get('https://beta.whatsapp.ai.in/send-message', [
                'query' => $params,
                'http_errors' => false,
                'timeout' => 15,
            ]);
            $status = $resp->getStatusCode();
            $body = (string) $resp->getBody();
            $fullUrl = 'https://beta.whatsapp.ai.in/send-message?' . http_build_query($params);
            $token = csrf_hash();
            return redirect()->to(url('whatsapp-test/result') . '?csrf_test_name=' . urlencode($token))
                ->with('wa_status', $status)
                ->with('wa_url', $fullUrl)
                ->with('wa_response', $body);
        } catch (\Throwable $e) {
            $token = csrf_hash();
            return redirect()->to(url('whatsapp-test/result') . '?csrf_test_name=' . urlencode($token))
                ->with('wa_status', \CodeIgniter\HTTP\ResponseInterface::HTTP_BAD_GATEWAY)
                ->with('wa_url', null)
                ->with('wa_response', 'Request failed: ' . $e->getMessage());
        }
    }

    public function result()
    {
        $status = (int) (session()->getFlashdata('wa_status') ?? 0);
        $url = (string) (session()->getFlashdata('wa_url') ?? '');
        $response = (string) (session()->getFlashdata('wa_response') ?? '');
        return view('frontend/whatsapp/result', compact('status', 'url', 'response'));
    }
}
