<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\ContactMessage;
use Illuminate\Http\Request;

class LandingPageController extends Controller
{
    private static function whmcsAuth(): array
    {
        if (app()->environment('production')) {
            return [
                'identifier' => config('whmcs.identifier'),
                'secret'     => config('whmcs.secret'),
            ];
        }
        return [
            'username' => config('whmcs.base_user_name'),
            'password' => config('whmcs.base_secret'),
        ];
    }

    public function domainSearch(Request $request, $domain)
    {
        $curl = curl_init();

        $url = 'http://whoisbooks.com/api/v1/get-whois-data'
            . '?is_for_similar_domain=0'
            . '&domain_name=' . urlencode($domain)
            . '&api_key=6c03d7fdc84bb7d471b29d31cadcA290'
            . '&user_domain=http://hostinggods.kiubix.biz/WhoisBooks'
            . '&purchase_key=ce8a9bcc-141b-45f6-88ee-5cd39cc72ba8';

        curl_setopt_array($curl, [
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING       => '',
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST  => 'GET',
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        ]);

        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            $fallback = new \stdClass();
            $fallback->is_registered = true;
            $fallback->domain_name   = $domain;
            $response = json_encode($fallback);
        }

        curl_close($curl);

        return response()->json(json_decode($response));
    }

    public function check_available_domain(Request $request, $domain)
    {
        $client = new \GuzzleHttp\Client([
            'auth' => [config('whmcs.identifier'), config('whmcs.secret')],
        ]);

        $response = $client->post(config('whmcs.url_validate_subdomain'), [
            'form_params' => [
                'subdomain' => $domain . '.kit.guru',
                'token'     => config('whmcs.token'),
            ],
        ]);

        $contents = json_decode(utf8_encode(str_replace(chr(0), '', $response->getBody())));

        if ($contents->status == 401) {
            return response()->json(['status' => true, 'step' => 2]);
        }

        return response()->json(['status' => true, 'step' => 3]);
    }

    public function create_new_client(Request $request)
    {
        $firstname     = $request->get('firstname');
        $lastname      = $request->get('lastname');
        $email         = $request->get('email');
        $contact_phone = $request->get('contact_phone');
        $password      = $request->get('password');

        $params = compact('firstname', 'lastname', 'contact_phone', 'email', 'password');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, config('whmcs.base_domain'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array_merge(self::whmcsAuth(), [
            'action'       => 'AddClient',
            'firstname'    => $firstname,
            'lastname'     => $lastname,
            'email'        => $email,
            'address1'     => 'Aguascalientes',
            'city'         => 'Aguascalientes',
            'state'        => 'Aguascalientes',
            'postcode'     => '2000',
            'country'      => 'MX',
            'language'     => 'espanish',
            'phonenumber'  => $contact_phone,
            'password2'    => $password,
            'responsetype' => 'json',
            'noemail'      => true,
            'groupid'      => 13,
        ])));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response);

        if (!is_object($data)) {
            return response()->json(['status' => false, 'error' => 'Respuesta inesperada del servidor.'], 502);
        }

        if ($data->result === 'success') {
            self::alert_discord_new_client($params);
            return response()->json(['status' => true, 'user_id' => $data->clientid, 'step' => 3]);
        }

        if ($data->result === 'error' && $data->message === 'Ya existe un usuario con esa dirección de email') {
            return response()->json(['status' => false, 'code' => 2, 'step' => 2, 'message' => 'Este e-mail ya está registrado, por favor inicia sesión']);
        }

        return response()->json(['status' => false, 'step' => 2, 'message' => $data]);
    }

    public function validate_login(Request $request)
    {
        $email    = $request->get('email');
        $password = $request->get('password');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, config('whmcs.base_domain'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array_merge(self::whmcsAuth(), [
            'action'       => 'ValidateLogin',
            'email'        => $email,
            'password2'    => $password,
            'responsetype' => 'json',
        ])));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($response);

        if ($data->result === 'success') {
            $client_id = $this->getclient($email);
            if ($client_id) {
                self::alert_discord_login(['email' => $email]);
                return response()->json(['status' => true, 'user_id' => $client_id, 'step' => 3]);
            }
            return response()->json(['status' => false, 'code' => 2, 'step' => 2, 'message' => 'Error al obtener cliente']);
        }

        if ($data->result === 'error') {
            return response()->json(['status' => false, 'code' => 2, 'step' => 2, 'message' => 'Usuario o contraseña incorrectos']);
        }

        return response()->json(['status' => false, 'step' => 2]);
    }

    private function getclient($email)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, config('whmcs.base_domain'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array_merge(self::whmcsAuth(), [
            'action'       => 'GetClients',
            'search'       => $email,
            'responsetype' => 'json',
        ])));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($response);

        if ($data->result === 'success') {
            return $data->clients->client[0]->id;
        }

        return false;
    }

    public static function recovery_password(Request $request)
    {
        $email = $request->get('email');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, config('whmcs.base_domain'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array_merge(self::whmcsAuth(), [
            'action'       => 'ResetPassword',
            'email'        => $email,
            'responsetype' => 'json',
        ])));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($response);

        return response()->json(['status' => $data->result === 'success']);
    }

    public function create_installation_instance(Request $request)
    {
        $base_domain    = config('whmcs.base_domain');
        $payment_method = $request->get('payment_method', config('whmcs.payment_method', 'paypalcheckout'));

        $client_id   = (int) $request->get('user_id');
        $domain      = trim((string) $request->get('domain'));
        $package_raw = $request->get('package_type', $request->get('package', 'starter'));

        $package_aliases = [
            '1' => 'free', '2' => 'starter', '3' => 'professional',
            'free' => 'free', 'starter' => 'starter', 'professional' => 'professional',
        ];
        $package_type = $package_aliases[strtolower(trim((string) $package_raw))] ?? null;

        $package_map = [
            'free'         => ['product_id' => (int) config('whmcs.product_kearnit_id'),          'default_price' => 0,    'billing_cycle' => 'free',     'requires_domain_register' => false],
            'starter'      => ['product_id' => (int) config('whmcs.product_kearnit_start'),        'default_price' => 5500, 'billing_cycle' => 'annually', 'requires_domain_register' => true],
            'professional' => ['product_id' => (int) config('whmcs.product_kearnit_professional'), 'default_price' => 9500, 'billing_cycle' => 'annually', 'requires_domain_register' => true],
        ];

        if (!$package_type || !isset($package_map[$package_type])) {
            return response()->json(['status' => false, 'message' => 'package_type inválido. Valores permitidos: free|starter|professional o 1|2|3.'], 422);
        }

        $resolved_product_id      = (int) $request->get('product_id', $package_map[$package_type]['product_id']);
        $resolved_price           = $request->has('price') ? (float) $request->get('price') : (float) $package_map[$package_type]['default_price'];
        $billing_cycle            = $package_map[$package_type]['billing_cycle'];
        $requires_domain_register = $package_map[$package_type]['requires_domain_register'];

        if (!$client_id || $domain === '' || !$resolved_product_id) {
            return response()->json(['status' => false, 'message' => 'Parámetros requeridos: user_id, domain y package_type.'], 422);
        }

        if ($package_type !== 'free' && $resolved_price <= 0) {
            return response()->json(['status' => false, 'message' => 'Para starter/professional el precio debe ser mayor a 0.'], 422);
        }

        // Obtener datos del cliente y generar credenciales
        $info_ch = curl_init();
        curl_setopt($info_ch, CURLOPT_URL, $base_domain);
        curl_setopt($info_ch, CURLOPT_POST, 1);
        curl_setopt($info_ch, CURLOPT_POSTFIELDS, http_build_query(array_merge(self::whmcsAuth(), [
            'action' => 'GetClientsDetails', 'clientid' => $client_id, 'responsetype' => 'json',
        ])));
        curl_setopt($info_ch, CURLOPT_RETURNTRANSFER, 1);
        $info_data = json_decode(curl_exec($info_ch));
        curl_close($info_ch);

        $client_email    = (isset($info_data->email) && $info_data->email !== '') ? $info_data->email : '';
        $clean_local     = preg_replace('/[^a-z0-9]/', '', strtolower(explode('@', $client_email)[0]));
        $serviceusername = substr($clean_local, 0, 10) . substr(bin2hex(random_bytes(3)), 0, 6);
        $servicepassword = substr(str_replace(['+', '/', '='], '', base64_encode(random_bytes(16))), 0, 12) . 'K1!';

        $domain = strtolower($domain);
        if (strpos($domain, '.') === false) {
            $domain = $domain . '.kit.guru';
        }

        if ($requires_domain_register) {
            $check_ch = curl_init();
            curl_setopt($check_ch, CURLOPT_URL, $base_domain);
            curl_setopt($check_ch, CURLOPT_POST, 1);
            curl_setopt($check_ch, CURLOPT_POSTFIELDS, http_build_query(array_merge(self::whmcsAuth(), [
                'action' => 'DomainWhois', 'domain' => $domain, 'responsetype' => 'json',
            ])));
            curl_setopt($check_ch, CURLOPT_RETURNTRANSFER, 1);
            $check_data = json_decode(curl_exec($check_ch));
            curl_close($check_ch);

            if (!isset($check_data->result) || $check_data->result !== 'success') {
                return response()->json(['status' => false, 'message' => 'Error al consultar disponibilidad de dominio.'], 502);
            }
            if (!isset($check_data->status) || $check_data->status !== 'available') {
                return response()->json(['status' => false, 'message' => 'El dominio no está disponible para registro.', 'domain_status' => $check_data->status ?? null], 409);
            }
        }

        // Crear orden en WHMCS
        $add_order_fields = array_merge(self::whmcsAuth(), [
            'action'         => 'AddOrder',
            'clientid'       => $client_id,
            'pid'            => [$resolved_product_id],
            'domain'         => [$domain],
            'billingcycle'   => [$billing_cycle],
            'paymentmethod'  => $payment_method,
            'noemail'        => true,
            'noinvoiceemail' => true,
            'responsetype'   => 'json',
        ]);

        if ($requires_domain_register) {
            $add_order_fields['domaintype']    = ['register'];
            $add_order_fields['regperiod']     = [1];
            $add_order_fields['priceoverride'] = [$resolved_price];
        }

        $add_ch = curl_init();
        curl_setopt($add_ch, CURLOPT_URL, $base_domain);
        curl_setopt($add_ch, CURLOPT_POST, 1);
        curl_setopt($add_ch, CURLOPT_POSTFIELDS, http_build_query($add_order_fields));
        curl_setopt($add_ch, CURLOPT_RETURNTRANSFER, 1);
        $add_order_data = json_decode(curl_exec($add_ch));
        curl_close($add_ch);

        if (!isset($add_order_data->result) || $add_order_data->result !== 'success') {
            return response()->json(['status' => false, 'message' => 'WHMCS no pudo crear la orden.', 'whmcs' => $add_order_data], 502);
        }

        // Aceptar orden
        $accept_fields = array_merge(self::whmcsAuth(), [
            'action'          => 'AcceptOrder',
            'orderid'         => $add_order_data->orderid,
            'autosetup'       => true,
            'serviceusername' => $serviceusername,
            'servicepassword' => $servicepassword,
            'sendemail'       => false,
            'responsetype'    => 'json',
        ]);

        if ($requires_domain_register) {
            $accept_fields['sendregistrar'] = true;
        }

        $accept_ch = curl_init();
        curl_setopt($accept_ch, CURLOPT_URL, $base_domain);
        curl_setopt($accept_ch, CURLOPT_POST, 1);
        curl_setopt($accept_ch, CURLOPT_POSTFIELDS, http_build_query($accept_fields));
        curl_setopt($accept_ch, CURLOPT_RETURNTRANSFER, 1);
        $accept_data = json_decode(curl_exec($accept_ch));
        curl_close($accept_ch);

        if (!isset($accept_data->result) || $accept_data->result !== 'success') {
            return response()->json([
                'status'          => true,
                'accept_warning'  => true,
                'message'         => 'La orden se creó correctamente. La activación automática falló — un administrador la activará en breve.',
                'package_type'    => $package_type,
                'domain'          => $domain,
                'orderid'         => $add_order_data->orderid   ?? null,
                'invoiceid'       => $add_order_data->invoiceid ?? null,
                'serviceusername' => $serviceusername,
                'servicepassword' => $servicepassword,
            ]);
        }

        // Obtener credenciales del servicio recién creado
        $serviceusername = null;
        $servicepassword = null;
        if (!empty($add_order_data->serviceids)) {
            $service_id = (int) explode(',', (string) $add_order_data->serviceids)[0];
            if ($service_id > 0) {
                $cred_ch = curl_init();
                curl_setopt($cred_ch, CURLOPT_URL, $base_domain);
                curl_setopt($cred_ch, CURLOPT_POST, 1);
                curl_setopt($cred_ch, CURLOPT_POSTFIELDS, http_build_query(array_merge(self::whmcsAuth(), [
                    'action' => 'GetClientsProducts', 'serviceid' => $service_id, 'responsetype' => 'json',
                ])));
                curl_setopt($cred_ch, CURLOPT_RETURNTRANSFER, 1);
                $cred_data = json_decode(curl_exec($cred_ch));
                curl_close($cred_ch);
                if (isset($cred_data->result) && $cred_data->result === 'success' && isset($cred_data->products->product[0])) {
                    $product         = $cred_data->products->product[0];
                    $serviceusername = $product->username ?? null;
                    $servicepassword = $product->password ?? null;
                }
            }
        }

        return response()->json([
            'status'          => true,
            'message'         => 'Instancia creada correctamente.',
            'package_type'    => $package_type,
            'billing_cycle'   => $billing_cycle,
            'resolved_price'  => $resolved_price,
            'domain'          => $domain,
            'orderid'         => $add_order_data->orderid    ?? null,
            'invoiceid'       => $add_order_data->invoiceid  ?? null,
            'serviceids'      => $add_order_data->serviceids ?? null,
            'domainids'       => $add_order_data->domainids  ?? null,
            'serviceusername' => $serviceusername,
            'servicepassword' => $servicepassword,
        ]);
    }

    public function contact(Request $request)
    {
        $name  = trim((string) $request->get('name', ''));
        $email = trim((string) $request->get('email', ''));

        if ($name === '' || $email === '') {
            return response()->json(['status' => false, 'error' => 'Los campos name y email son requeridos.']);
        }

        try {
            ContactMessage::create([
                'name'    => $name,
                'phone'   => $request->get('phone'),
                'email'   => $email,
                'subject' => $request->get('subject'),
                'message' => $request->get('message'),
            ]);
            return response()->json(['status' => true]);
        } catch (\Exception $e) {
            return response()->json(['status' => false, 'error' => $e->getMessage()]);
        }
    }

    private static function alert_discord_new_client(array $params): void
    {
        // reservado para notificaciones Discord
    }

    private static function alert_discord_login(array $params): void
    {
        // reservado para notificaciones Discord
    }
}
