<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use App\Models\DepositAddress;
use App\Models\SupportedCoin;

class AddressController extends Controller
{
    protected string $userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36';

    public function getSymbols()
    {
        $app_id = get_setting('cc_app_id');
        $app_secret = get_setting('cc_app_secret');
        $url = "https://ccpayment.com/ccpayment/v2/getCoinList";
        $content = [];
    
        $timestamp = time();
        $body = json_encode($content);
        $sign_text = $app_id . $timestamp;
        
        if (strlen($body) != 2) {
            $sign_text .= $body;
        } else {
            $body = "";
        }
    
        $server_sign = hash_hmac('sha256', $sign_text, $app_secret);
    
        $headers = [
            "Content-Type: application/json;charset=utf-8",
            "Appid: $app_id",
            "Sign: $server_sign",
            "Timestamp: $timestamp",
            "User-Agent: {$this->userAgent}",
        ];
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
    
        $response = curl_exec($ch);
        curl_close($ch);
    
        $result = json_decode($response, true);
    
        if (!isset($result['code']) || $result['code'] !== 10000 || !isset($result['data']['coins'])) {
            return response()->json(['error' => 'Failed to fetch symbols'.print_r($result, true)], 500);
        }
    
        $symbols = [];
        foreach ($result['data']['coins'] as $coin) {
            if ($coin['status'] === "Normal" && isset($coin['networks'])) {
                foreach ($coin['networks'] as $network) {
                    $chains = array_keys($coin['networks']);
                    $symbols[$coin['symbol']] = $chains;
                }
            }
        }
        
        return response()->json($symbols);
    }

    public function getAddress($symbol, $chain)
    {
        $appId = get_setting('cc_app_id');
        $appSecret = get_setting('cc_app_secret');
        $userId = Auth::id();

        $existingAddress = DepositAddress::where('user_id', $userId)
            ->where('symbol', $symbol)
            ->where('chain', $chain)
            ->first();

        if (!$existingAddress) {
            $url = "https://ccpayment.com/ccpayment/v2/getOrCreateAppDepositAddress";
            $content = ["referenceId" => 'uid-' . $userId, "chain" => $chain];

            $timestamp = time();
            $body = json_encode($content);
            $signText = $appId . $timestamp . (strlen($body) != 2 ? $body : "");
            $serverSign = hash_hmac('sha256', $signText, $appSecret);

            try {
                $response = Http::withHeaders([
                    "Content-Type"  => "application/json;charset=utf-8",
                    "Appid"         => $appId,
                    "Sign"          => $serverSign,
                    "Timestamp"     => $timestamp,
                    "User-Agent"    => $this->userAgent,
                ])->post($url, $content);

                $depositAddress = $response->json();

                if (isset($depositAddress['data']['address'])) {
                    $memo = $depositAddress['data']['memo'] ?? 'none';

                    DepositAddress::create([
                        'user_id' => $userId,
                        'symbol' => $symbol,
                        'coin_id' => 0,
                        'token_id' => 0,
                        'address' => $depositAddress['data']['address'],
                        'chain' => $chain,
                        'memo' => $memo
                    ]);

                    return response()->json([
                        'code' => 10000,
                        'msg' => 'success',
                        'data' => [
                            'msg' => 'The deposit address has been successfully added, you can now make a deposit to that address.',
                            'symbol' => $symbol,
                            'address' => $depositAddress['data']['address'],
                            'chain' => $chain,
                            'memo' => $memo,
                        ]
                    ]);
                }

                return response()->json([
                    'code' => 10001,
                    'msg' => 'Failed to create deposit address',
                    'error' => $depositAddress
                ]);

            } catch (\Exception $e) {
                return response()->json([
                    'code' => 10001,
                    'msg' => 'Request failed',
                    'error' => $e->getMessage()
                ]);
            }
        }

        return response()->json([
            'code' => 10001,
            'msg' => 'This deposit address already exists.'
        ]);
    }
}