<?php

namespace App\Http\Controllers\ManualResponse;

use App\Models\ManualResponse\UsersConnectSpn;
use App\Http\Controllers\Controller;

class SpnConfigController extends Controller
{
    public function init_connection(UsersConnectSpn $user)
    {
        $username = $user->username;
        $password = $user->password;
        $link = $user->link;

        // Initialize cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "$link/spn/login_api.php");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Set the Authorization header for Basic Auth
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Basic ' . base64_encode("$username:$password"),
        ]);

        // Execute cURL request
        $response = curl_exec($ch);
        $error = curl_error($ch); // Check for errors
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        //dd($response, $error, $httpCode); //Debug response of cURL

        if ($error) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable peer verification
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Disable host verification
            $response = curl_exec($ch);
            $error = curl_error($ch); // Check for errors
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        }

        curl_close($ch); // Close the cURL handle
        
        if($httpCode == '404'){
            return [
                'success' => 'false',
                'message' => 'This endpoint does not support this feature. Please update patch before submit.'
            ];
        }

        if ($error) {
            return [
                'success' => 'false',
                'message' => 'cURL Error: ' . $error
            ];
        }

        // Process the response
        $decodedResponse = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            session()->flash('error', 'Invalid JSON response');
            return null; // Handle invalid JSON appropriately
        }

        return $decodedResponse; // Return the decoded response
    }
}
