<?php
// app/Services/CPanelApiService.php

namespace App\Services;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class CPanelApiService
{
    protected $client;
    protected $cpanelUrl;
    protected $cpanelUsername;
    protected $cpanelToken;

    public function __construct()
    {
        $this->cpanelUrl = env('CPANEL_URL');
        $this->cpanelUsername = env('CPANEL_USERNAME');
        $this->cpanelToken = env('CPANEL_TOKEN');

        $this->client = new Client([
            'base_uri' => $this->cpanelUrl,
            'headers' => [
                'Authorization' => 'cpanel ' . $this->cpanelUsername . ':' . $this->cpanelToken
            ]
        ]);
    }

    public function createEmailAccount($domain, $email, $password, $quota)
    {
        $query = [
            'cpanel_jsonapi_user' => $this->cpanelUsername,
            'cpanel_jsonapi_apiversion' => '2',
            'cpanel_jsonapi_module' => 'Email',
            'cpanel_jsonapi_func' => 'addpop',
            'domain' => $domain,
            'email' => $email,
            'password' => $password,
            'quota' => $quota
        ];

        try {
            $response = $this->client->request('GET', '/json-api/cpanel', ['query' => $query]);
            return json_decode($response->getBody(), true);
        } catch (GuzzleException $e) {
            return ['error' => $e->getMessage()];
        }
    }
}
