<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Pembelian;
use App\Models\Pembayaran;

class digiFlazzCallbackController extends Controller {

    public function status($x) {
        $y = strtolower($x);
        if(in_array($y,['failed','gagal','error'])) $str = 'Batal';
        if(in_array($y,['pending'])) $str = 'Pending';
        if(in_array($y,['processing','proses'])) $str = 'Process';
        if(in_array($y,['success','sukses','berhasil'])) $str = 'Success';
        return (!isset($str)) ? 'Pending' : $str;
    }

    public function handle(Request $request){
        try {
            $api = \DB::table('setings')->where('id', 1)->first();
            $secret = '132006'; // Sesuaikan dengan secret yang sesuai dengan digiflazz di webhook

            $post_data = file_get_contents('php://input');
            $signature = hash_hmac('sha1', $post_data, $secret);

            if ($request->header('X-Hub-Signature') == 'sha1='.$signature) {
                $data = json_decode($request->getContent(), true);
                $refId = $data['data']['ref_id'];
                $updateStatus = $this->status($data['data']['status']);
                $sn = $data['data']['sn'];

                if ($request->header('X-Digiflazz-Event') == 'update') {
                    // Mulai transaksi database atomik
                    \DB::beginTransaction();

                    $invoice = Pembelian::where('provider_order_id', $refId)
                                        ->whereIn('status', ['Pending', 'Process'])
                                        ->lockForUpdate()
                                        ->first();

                    if ($invoice) {
                        $invoice->update([
                            'keterangan' => $sn,
                            'status' => $updateStatus,
                            'log' => json_encode($data)
                        ]);

                        // Komit transaksi jika berhasil
                        \DB::commit();

                        // Kirim pesan jika status adalah "Success"
                        if ($updateStatus == "Success") {
                            $pembayaran = Pembayaran::where('order_id', $invoice->order_id)->first();
                            $pesan = "Hi\n".
"Pesanan Dengan Nomor Invoice *$invoice->order_id* Berhasil Dikirim\n\n".
"Silahkan cek akun kamu kak😊🙏.\n\n".
"Terima Kasih Sudah Membeli Item di $api->web_title Semoga Dilancarkan Terus Rezekinya dan sehat selalu yaa❤\n".
"▰ ▱ ▰ ▱ ▰ ▱ ▰ ▱ ▰ ▱ ▰ ▱ ▰ ▱ ▰ \n".
"Catatan: \n\n".
"Jika item belum diterima pada akun game kamu, mohon tunggu sekitar 5-15 menit.\n".
"Jika masih belum diterima silahkan kontak kami dengan mengirimkan No Transaksi biar kami bantu cek ^^\n".
"Silahkan Gabung Komunitas kami di link berikut yaa:.\n".
"chat.whatsapp.com/Fn6fjP9hPhfHDmOinV4ZQd\n".
"▰ ▱ ▰ ▱ ▰ ▱ ▰ ▱ ▰ ▱ ▰ ▱ ▰ ▱ ▰ \n".
"Customer Support : ".env('NOMOR_ADMIN')."\n".
"Online 24 Jam";
                            $this->msg($pembayaran->no_pembeli, $pesan);
                        }
                    } else {
                        // Rollback transaksi jika pesanan tidak ditemukan
                        \DB::rollback();
                        return response()->json(['message' => 'Pesanan tidak ditemukan'], 404);
                    }
                }
            } else {
                // Tanggapan jika tanda tangan tidak valid
                return response()->json(['message' => 'Tanda tangan tidak valid'], 403);
            }
        } catch (\Exception $e) {
            // Tanggapan jika terjadi kesalahan
            \DB::rollback();
            return response()->json(['message' => 'Terjadi kesalahan'], 500);
        }
    }

    public function msg($nomor, $msg)
    {
        $api = \DB::table('setings')->where('id',1)->first();
        $curl = curl_init();
        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://api.fonnte.com/send',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => array('target' => $nomor,'message' => $msg),
          CURLOPT_HTTPHEADER => array(
            'Authorization: '.$api->wa_key
          ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
}
