<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Client\Response;
use PDO;

class WhmcsServices 
{

    protected string $apiUrl;
    protected ?string $apiIdentifier;
    protected ?string $apiSecret;
    protected ?string $username;
    protected ?string $password;

    public function __construct()
    {
        $this->apiUrl = config('services.whmcs.api_url');
        $this->apiIdentifier = config('services.whmcs.api_identifier');
        $this->apiSecret = config('services.whmcs.api_secret');
        $this->username = config('services.whmcs.username');
        $this->password = config('services.whmcs.password');
    }

    public function validateLogin(string $email, string $password): array
    {
        return $this->request('ValidateLogin', [
            'email' => $email,
            'password2' => $password,
        ]);
    }

    private function request(string $action, array $data = [])
    {
        $defaultArray = [
            'action' => $action,
            'responsetype' => 'json',
        ];

        if ($this->apiIdentifier && $this->apiSecret) {
            $defaultArray['identifier'] = $this->apiIdentifier;
            $defaultArray['secret'] = $this->apiSecret;
        } elseif ($this->username && $this->password) {
            $defaultArray['username'] = $this->username;
            $defaultArray['password'] = $this->password;
        }

        if (count($data) > 0) {
            $defaultArray = array_merge($defaultArray, $data);
        }


        try {
           $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $this->apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,
            http_build_query($defaultArray)
            );
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $response = curl_exec($ch);
            $response = json_decode($response , true);
            curl_close($ch);
            return $response;
        } catch (\Exception $e) {
            Log::error("WHMCS API Exception", [
                'action' => $action,
                'url' => $this->apiUrl,
                'error' => $e->getMessage(),
            ]);

            throw new \Exception("WHMCS API request failed: " . $e->getMessage());
        }
    }


    public function getClientByEmail($email) {
        $result = $this->request('GetClientsDetails', ['email'=>$email]);
        return $result;
    }
    public function getClientById($clientId) {
        $result = $this->request('GetClientsDetails', ['clientid'=>$clientId]);
        return $result;
    }
    
    public function getClientsBySearch($search){
        return $this->request('GetClients', $search);
    }

    public function saveClient($user){
        $data = [
            'firstname' => $user['name'],
            'lastname' => $user['lastname'],
            'email' => $user['email'],
            'country' => $user['country'],
            'address1' => $user['address'],
            'city' => $user['city'],
            'state' => $user['state'],
            'postcode' => $user['post_code'],
            'country' => $user['country'],
            'phonenumber' => $user['phone'],
            'companyname' => $user['company'],
            'password2' => $user['password'],
        ];
        $this->request('AddClient', $data);
    }


    public function getClientOrderIdsByClientId($clientId){
        $products = $this->request('GetClientsProducts', ['clientid' => $clientId]);
        $orderids = [];

        if($products['products'] != ''){   
            $order_count = count($products['products']['product']);
            for($i =0; $i < $order_count; $i++){
                    $orderids[] = $products['products']['product'][$i]['orderid'];
            }
        }

        return $orderids;
    }

    public function getOrderDetailByOrderId($orderId){
        return $this->request('GetOrders', ['id' => $orderId]);
    }

    public function getClientOrdersByIds($orderIds) {
        $orders = [];
        foreach ($orderIds as $key => $id) {
            $orders[] = $this->getOrderDetailByOrderId($id);
        }
        return $orders;
    }


    public function LoginClientsToTheirProfileByClientId($clientId){
        $data = [
          'client_id'=>$clientId,
          'destination' => 'sso:custom_redirect',
          'sso_redirect_path' => 'clientarea.php',  
        ];
        $authenticated = $this->request('CreateSsoToken', $data);
        if($authenticated['result'] == 'success'){
            return redirect($authenticated['redirect_url']);
        }else{
            return redirect()->back()->with('warning_message', 'Error: 002 Oops, something went wrong. Please try again or contact our support team');
        }

    }

    public function LoginClientsToTheirCarts($clientId){
        $data = [
          'client_id'=>$clientId,
          'destination' => 'sso:custom_redirect',
          'sso_redirect_path' => 'cart.php?a=checkout&e=false',
        ];
        $authenticated = $this->request('CreateSsoToken', $data);
        if($authenticated['result'] == 'success'){
            return redirect($authenticated['redirect_url']);
        }else{
            return redirect()->back()->with('warning_message', 'Error: 002 Oops, something went wrong. Please try again or contact our support team');
        }
    }

    public function updateClient($req){
        $data = [
            'clientemail' => auth()->user()->email,
            'country' => $req['country'],
            'address1' => $req['address'],
            'city' => $req['city'],
            'state' => $req['state'],
            'postcode' => $req['post_code'],
            'phonenumber' => $req['phone_number'],
            'companyname' => $req['company'],
        ];
        $this->request('UpdateClient', $data);
    }

    public function getUserIdByDomain($domain){
        $domainInfo =  $this->request('GetClientsDomains', ['domain'=>$domain]);
        if($domainInfo['domains'] != null){
        	return $domainInfo['domains']['domain'][0]['userid'];
        }else{
        	return null;
        }
    }

    public function getInvoiceDetailByInvoiceNumber($invoiceNumber){
        return $this->request('GetInvoice', ['invoiceid' => $invoiceNumber]);
    }


}
