<?php

namespace Mtc\Plugins\Wisebee\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Wisebee\Wisebee;

class WisebeeRemoteSettingsController extends Controller
{
    /**
     * Display remote settings form
     *
     * @return mixed
     */
    public function index()
    {
        $settings = [];
        $error = null;

        try {
            $wisebee = new Wisebee(
                config('wisebee.host') . config('wisebee.api_endpoint'),
                config('wisebee.api_key')
            );

            $result = $wisebee->customApiCall('get', 'settings');

            if ($result !== false && isset($result->settings)) {
                $settings = (array) $result->settings;
            } else {
                $error = $wisebee->getErrorMessage() ?? 'Failed to fetch settings from Wisebee';
            }
        } catch (\Exception $e) {
            \Log::error('Wisebee connection error', ['exception' => $e]);
            $error = 'Unable to connect to Wisebee. Please check your configuration.';
        }

        return template('wisebee/admin/remoteSettings.twig', [
            'title' => 'Remote Settings',
            'settings' => $settings,
            'error' => $error,
            'success' => session()->get('success'),
        ]);
    }

    /**
     * Update remote settings
     *
     * @param Request $request
     * @return RedirectResponse
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'settings' => 'required|array',
            'settings.*' => 'nullable|string|max:1000',
        ]);

        try {
            $wisebee = new Wisebee(
                config('wisebee.host') . config('wisebee.api_endpoint'),
                config('wisebee.api_key')
            );

            $result = $wisebee->customApiCall('post', 'settings', [
                'settings' => $request->input('settings'),
            ]);

            if ($result !== false) {
                return redirect()->back()->with('success', 'Settings updated successfully.');
            }

            return redirect()->back()->with('error', $wisebee->getErrorMessage() ?? 'Failed to update settings');
        } catch (\Exception $e) {
            \Log::error('Wisebee connection error', ['exception' => $e]);
            return redirect()->back()->with('error', 'Unable to connect to Wisebee. Please check your configuration.');
        }
    }

    /**
     * Uploads a company logo to Wisebee via the API
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function uploadLogo(Request $request): JsonResponse
    {
        $request->validate([
            'file' => 'required|file|mimes:jpg,jpeg,png,gif|max:2048',
        ]);

        $apiUrl = config('wisebee.host') . config('wisebee.api_endpoint') . 'settings/upload-file';
        $apiKey = config('wisebee.api_key');

        $file = $request->file('file');
        $filePath = $file->getRealPath();
        $fileName = $file->getClientOriginalName();
        $fileMime = $file->getMimeType();

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $apiKey,
            'Accept: application/json',
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, [
            'type' => 'company_logo',
            'file' => new \CURLFile($filePath, $fileMime, $fileName),
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($response === false) {
            return response()->json([
                'success' => false,
                'error' => 'Connection error: ' . $curlError,
            ], 422);
        }

        $result = json_decode($response, true);

        if ($httpCode >= 200 && $httpCode < 300 && !empty($result['success'])) {
            return response()->json([
                'success' => true,
                'url' => $result['url'] ?? '',
            ]);
        }

        return response()->json([
            'success' => false,
            'error' => $result['error'] ?? 'Failed to upload logo',
        ], 422);
    }
}
