<?php

namespace Modules\ZimflowApi\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use App\Models\Setting; // Assuming you use the central Setting model
use Modules\ZimflowApi\Services\ZimflowService;

class ZimflowConfigController extends Controller
{
    protected array $settingKeys = [
        'zimflow_api_endpoint',
        'zimflow_api_token',
        'zimflow_notifications_enabled', // To globally enable/disable notifications via Zimflow
    ];

    protected ZimflowService $zimflowService;

    public function __construct(ZimflowService $zimflowService)
    {
        $this->zimflowService = $zimflowService;
    }

    public function edit()
    {
        $settings = [];
        foreach ($this->settingKeys as $key) {
            $settings[$key] = setting($key); // Using your global setting() helper
        }
        $settings['zimflow_api_endpoint'] = $settings['zimflow_api_endpoint'] ?? config('ZimflowApi.api_endpoint');
        $settings['zimflow_api_token'] = $settings['zimflow_api_token'] ?? config('ZimflowApi.api_token');
        $settings['zimflow_notifications_enabled'] = $settings['zimflow_notifications_enabled'] ?? '0';


        return view('ZimflowApi::admin.config', compact('settings'));
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'zimflow_api_endpoint' => 'required|url',
            'zimflow_api_token' => 'required|string',
            'zimflow_notifications_enabled' => 'nullable|boolean',
        ]);

        foreach ($this->settingKeys as $key) {
            $valueToStore = null;
            if ($key === 'zimflow_notifications_enabled') {
                $valueToStore = $request->has('zimflow_notifications_enabled') ? '1' : '0';
            } elseif ($request->filled($key)) {
                 $valueToStore = $request->input($key);
            }

            Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $valueToStore, 'group' => 'Zimflow Gateway', 'type' => ($key === 'zimflow_notifications_enabled' ? 'checkbox' : 'text'), 'name' => ucwords(str_replace('_', ' ', $key))]
            );
        }

        // Clear config cache so the .env overrides in config/ZimflowApi.php are re-read
        // if they are used as fallbacks or if the service reads directly from config()
        Artisan::call('config:clear');
        Artisan::call('cache:clear'); // For your setting() helper

        return redirect()->back()->with('success', 'Zimflow Gateway settings updated successfully.');
    }

    public function sendTestNotification(Request $request)
    {
        $notificationsEnabled = setting('zimflow_notifications_enabled', '0') === '1';
        // The ZimflowService will now fetch its own configuration (endpoint and token)

        if (!$notificationsEnabled) {
            return redirect()->back()->with('error', 'Zimflow notifications are currently disabled.');
        }

        // The service constructor logs if not configured, but an early return here is still good for UX.
        // We check the settings directly as the service might not throw an exception immediately.
        if (empty(setting('zimflow_api_endpoint', config('ZimflowApi.api_endpoint'))) || empty(setting('zimflow_api_token', config('ZimflowApi.api_token')))) {
            return redirect()->back()->with('error', 'Zimflow API endpoint or token is not configured.');
        }

        // You'll need to know the expected recipient format for Zimflow.
        // This is a placeholder; replace with a valid test recipient number.
        // It might be good to have a setting for a "Test Recipient Number".
        $testRecipient = $request->input('test_recipient_number', setting('zimflow_test_recipient_number')); 

        if (empty($testRecipient)) {
            return redirect()->back()->with('error', 'Test recipient number is not configured. Please provide one.');
        }

        $message = "This is a test notification from your Digital Vocano application via Zimflow API.";

        try {
            // The ZimflowService->sendGenericMessage method needs to have the correct
            // API path and authentication method (Bearer token or token in payload)
            // as per Zimflow's documentation for sending generic messages.
            $result = $this->zimflowService->sendGenericMessage($testRecipient, $message);

            // Check the structure of the result from ZimflowService
            if (isset($result['status']) && $result['status'] === 'error') {
                $errorMessage = 'Failed to send test notification. API Response: ' . ($result['message'] ?? 'Unknown error');
                if (isset($result['details'])) {
                    $errorMessage .= ' Details: '. (is_string($result['details']) ? $result['details'] : json_encode($result['details']));
                }
                return redirect()->back()->with('error', $errorMessage);
            } elseif ($result && (!isset($result['status']) || $result['status'] !== 'error')) { // Assuming successful response is not an error status or is structured differently
                return redirect()->back()->with('success', 'Test notification sent successfully to ' . $testRecipient . '!');
            }
            return redirect()->back()->with('error', 'Failed to send test notification. Unexpected API response structure.');
        } catch (\Exception $e) {
            Log::error('Zimflow API test notification error: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while trying to send the test notification: ' . $e->getMessage());
        }
    }
}
