<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use App\Models\Pembayaran;
use App\Models\Pembelian;


class VipCallbackController extends Controller
{


    private function getStatusLabel($status)
    {
        switch ($status) {
            case 'success':
                return 'Sukses';
            case 'error':
                return 'Gagal';
            case 'waiting':
            case 'processing':
                return 'Proses';
            default:
                return 'Batal';
        }
    }

    public function handleCallback(Request $request)
    {
        $api = \DB::table('setting_webs')->where('id', 1)->first();
        \Log::info($request->all());
        \Log::info($request->ip());
    
        // Whitelist IP
        $whitelistedIp = '178.248.73.218';
        if ($request->ip() !== $whitelistedIp) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
    
        // Validate Header
        $clientSignature = $request->header('X-Client-Signature');
        $apiId = $api->vip_apiid; // Ensure API_ID is defined in .env
        $apiKey = $api->vip_apikey; // Ensure API_KEY is defined in .env
        $expectedSignature = md5($apiId . $apiKey);

        
    
        if ($clientSignature !== $expectedSignature) {
            return response()->json(['error' => 'Invalid signature'], 403);
        }
    
        // Validate Data
        $data = $request->input('data');
        $validator = \Validator::make($data, [
            'trxid' => 'required|string',
            'data' => 'required|string',
            'zone' => 'nullable|string',
            'service' => 'required|string',
            'status' => 'required|string',
            'note' => 'required|string',
            'price' => 'required|numeric',
            'created_at' => 'nullable|date',
            'updated_at' => 'nullable|date',
        ]);
    
        if ($validator->fails()) {
            return response()->json(['error' => 'Invalid data', 'messages' => $validator->errors()], 400);
        }
    
        // Process data as needed
        Log::info('Webhook received:', $data);

        $updateStatus = $this->getStatusLabel($data['status']);
        \Log::info($updateStatus);
           $invoice = Pembelian::where('provider_order_id', $data['trxid'])->where('status', 'Proses')->first();
    

        if ($invoice) {
            \Log::info($invoice);
            $updateData = [
                'status' => $updateStatus,
                'log' => json_encode($data)
            ];

            if ($invoice->tipe_transaksi == 'voucher') {
                $updateData['voucher'] = $data['note'];
            }


            $invoice->update($updateData);
        

         $updatePesanan1 = Pembayaran::where('order_id', $invoice->order_id)->first();

        $updatePesanan = Pembayaran::where('order_id', $invoice->order_id)->where('metode', 'SALDO')->first();
        $order = Pembelian::where('order_id', $invoice->order_id)->where('tipe_transaksi', 'API')->first();

        if($updatePesanan1){
            
            $pesanSuksess = "*Pembelian $updateStatus*\n\n" .
            "No Invoice: *$invoice->order_id*\n" .
            "Layanan: *$invoice->layanan*\n" .
            "ID : *$invoice->user_id*\n" .
            "Server : *$invoice->zone*\n" .
            "Nickname : *$invoice->nickname*\n" .
            "Harga: *Rp. " . number_format($invoice->harga, 0, '.', ',') . "*\n" .
            "Status Pembelian: *$updateStatus*\n" .
            "Metode Pembayaran: *$updatePesanan1->metode*\n\n" .
            "*Invoice* : " . env("APP_URL") . "/pembelian/invoice/$invoice->order_id\n\n" .
            "INI ADALAH PESAN OTOMATIS";

        $this->msg($updatePesanan1->no_pembeli, $pesanSuksess);
        $this->msg($api->nomor_admin, $pesanSuksess);

        if ($updateStatus == 'Gagal') {
            // Add to the user's balance directly using the DB facade
            $refund = DB::table('users')
                ->where('username', $invoice->username)
                ->update(['balance' => DB::raw('balance + ' . $invoice->harga)]);
        
            if ($refund) {
                $pesanGagal = "
                Hai *$invoice->username*,\n\n" .
                "Maaf atas Kendala Pesanannya.\n\n" .
                "Saldo Anda Sudah Di Kembalikan.\n\n" .
                "Silakan Pesan Produk Lain Atau Tunggu Beberapa Saat.\n\n" .
                "> INI ADALAH PESAN OTOMATIS\n\n";
        
                // Use $pesanGagal instead of $pesanSuksess
                $this->msg($updatePesanan1->no_pembeli, $pesanGagal);
                $this->msg($api->nomor_admin, $pesanGagal);

            }
        }
        }


        

        if ($updatePesanan) {

            $url = $invoice['callback_url'] ?? 'https://example.com';

            $data = [
                'inputs' => $invoice['user_id'] . '|' . $invoice['zone'],
                'invoice_number' => $invoice['order_id'],
                'reference_number' => $invoice['provider_order_id'],
                'nickname' => $invoice['nickname'],
                'status_code' => $invoice['status'],
                'status_date' => $invoice['updated_at']->format('Y/m/d H:i:s'),
                'status_desc' => 'Transaksi berhasil pada ' . $invoice['updated_at']->format('Y/m/d H:i:s') . ' WIB',
                'total_price' => $invoice['harga'],
                'variant_code' => $data['data']['buyer_sku_code'] ?? '-',
                'variant_name' => $invoice['layanan']
            ];
            
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            
            // Opsional: Tambahkan header jika diperlukan
            // curl_setopt($ch, CURLOPT_HTTPHEADER, [
            //     'Content-Type: application/x-www-form-urlencoded',
            //     'Authorization: Bearer YOUR_TOKEN_HERE'
            // ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            if (curl_errno($ch)) {
                Log::error('Curl error:', ['error' => curl_error($ch)]);
            } else {
                Log::info('Response status:', ['status' => $httpCode]);
                Log::info('Response body:', ['body' => $response]);
            }
            
            curl_close($ch);




            
        }



    }
    
        // Return success response
        return response()->json(['message' => 'Webhook processed successfully'], 200);
    }

    private function convertToInternationalFormat($nomor)

    {
         // Cek apakah nomor diawali dengan '0'
         if (substr($nomor, 0, 1) === '0') {
            // Ganti '0' dengan '62' untuk format internasional
            $nomor = '62' . substr($nomor, 1);
        }
        return $nomor;
    }
    public function msg($nomor, $msg)
    
    {

        //Log::info('masilk kok bang tapi kok ga ke kirim ya?');

         $api = \DB::table('setting_webs')->where('id', 1)->first();
         $nomor = $this->convertToInternationalFormat($nomor);
         Log::info($nomor);

       
         $body = array(
            "api_key" => $api->wa_key ?? '',
            "receiver" => $nomor,
            "data" => array("message" => $msg)
          );
          
          $curl = curl_init();
          curl_setopt_array($curl, [
            CURLOPT_URL => "example.com/send-message",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($body),
            CURLOPT_HTTPHEADER => [
              "Accept: */*",
              "Content-Type: application/json",
            ],
          ]);
          
          $response = curl_exec($curl);
          $err = curl_error($curl);
          Log::info($response);

          $responseArray = json_decode($response, true); // true untuk mengembalikan sebagai array

    // Periksa status
    if (isset($responseArray['status']) && $responseArray['status'] == false) {
        // Jika status false dan pesan tertentu
        if ($responseArray['message'] == 'Session is stopped.') {
            $requestPesan = $this->msg($nomor, $msg);
        }
    
        // Panggil metode fonte terlepas dari pesan
        $requestPesanAdmin = $this->fonte($nomor, $msg);
    }
          curl_close($curl);
          
          if ($err) {
            echo "cURL Error #:" . $err;
          } else {
            return $response;
          }
        }
}