<?php

namespace App\Livewire\Pos\Member;

use App\Models\Member;
use App\Models\MemberTemp;
use App\Models\Settings;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\On;
use Livewire\Component;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class MemberIndex extends Component
{
    use LivewireAlert;
    public $isloading = false;
    public $member;

    protected function isConnectionResetError($e)
    {
        return $e instanceof \GuzzleHttp\Exception\RequestException &&
            strpos($e->getMessage(), 'cURL error 56: Recv failure: Connection was reset') !== false;
    }

    protected function reDoFunction($function, $args = [])
    {
        call_user_func_array([$this, $function], $args);
    }


    public function render()
    {
        $members = Member::all();
        return view('livewire.pos.member.member-index', [
            'members' => $members,
        ]);
    }


    public function mount()
    {
        $member = DB::table('Luv2_member')->get();
        $this->member = $member;
    }
    public function firstClickGetMember()
    {
        $this->isloading = true;
        $this->dispatch('getMember');
    }

    #[On('getMember')]
    public function sapGetMember()
    {

        $user = Auth::user();
        $setting = Settings::first();
        $userId = auth()->user()->id;
        $urladmin = $setting->url_admin;

        try {
            // $response = Http::post($url . '/api/search', [
            //     "Select" => "\"CardCode\" as \"code\",\"CardName\" as \"name\",\"Cellular\" as \"phone\",\"E_Mail\" as \"email\",\"Address\" as \"address\",\"validFor\" as \"active\",'" . $userId . "' as \"id_user\" ",
            //     "From" => "OCRD",
            //     "Where" => "\"CardType\"='C'"
            // ]);
            $response = Http::get($urladmin . 'member/' . $setting->id_company);

            if ($response->successful()) {
                $jsonData = $response->json();
                MemberTemp::where('id_user', $userId)->delete();

                $chunks = array_chunk($jsonData, 1000);

                foreach ($chunks as $chunk) {
                    $insertData = [];

                    foreach ($chunk as $member) {
                        $insertData[] = [
                            'code' => $member['code'],
                            'name' => $member['name'],
                            'phone' => $member['phone'],
                            'email' => $member['email'],
                            'address' => $member['address'],
                            'active' => $member['active'],
                            'hobby' => $member['hobby'],
                            'id_user' => Auth::user()->id,
                        ];
                    }

                    DB::table('Luv2_member_temp')->insert($insertData);
                }

                #insert member
                DB::statement("
                    INSERT INTO \"Luv2_member\" (\"code\", \"name\", \"phone\", \"email\", \"address\", \"active\" , \"hobby\") 
                    SELECT DISTINCT \"code\", \"name\", \"phone\", \"email\", \"address\", \"active\" , \"hobby\"
                    FROM \"Luv2_member_temp\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_member\" WHERE \"Luv2_member\".\"code\" = \"Luv2_member_temp\".\"code\" and \"Luv2_member_temp\".\"id_user\"='" . $userId . "'
                    ) and \"Luv2_member_temp\".\"id_user\"='" . $userId . "' 
                ");

                #update member
                DB::statement("
                    UPDATE \"Luv2_member\"
                    SET \"name\"=\"Luv2_member_temp\".\"name\",\"phone\"=\"Luv2_member_temp\".\"phone\",\"email\"=\"Luv2_member_temp\".\"email\",\"address\"=\"Luv2_member_temp\".\"address\",\"active\"=\"Luv2_member_temp\".\"active\",\"hobby\"=\"Luv2_member_temp\".\"hobby\"
                    FROM \"Luv2_member_temp\"
                    WHERE \"Luv2_member_temp\".\"code\"=\"Luv2_member\".\"code\" AND \"Luv2_member_temp\".\"id_user\"='" . $userId . "'
                    AND (
                        \"Luv2_member_temp\".\"name\"<>\"Luv2_member\".\"name\" OR
                        \"Luv2_member_temp\".\"phone\"<>\"Luv2_member\".\"phone\" OR
                        \"Luv2_member_temp\".\"email\"<>\"Luv2_member\".\"email\" OR
                        \"Luv2_member_temp\".\"address\"<>\"Luv2_member\".\"address\" OR
                        \"Luv2_member_temp\".\"hobby\"<>\"Luv2_member\".\"hobby\" OR
                        \"Luv2_member_temp\".\"active\"<>\"Luv2_member\".\"active\"
                    );
                ");

                MemberTemp::where('id_user', $userId)->delete();
                $this->alert('success', 'Data synchrone succesfully', [
                    'position' => 'top-right',
                    'timer' => 3000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
            } else {
                $this->alert('warning', 'Data Failed to Sync', [
                    'position' => 'top-end',
                    'timer' => 5000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
            }
        } catch (\Exception $e) {
            if ($this->isConnectionResetError($e)) {
                $this->alert('info', 'Please Wait Re-trying Sync Items', [
                    'position' => 'top-right',
                    'timer' => 3000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
                $this->reDoFunction('sapGetMember');
            } else {
                throw $e;
            }
        }
        $this->dispatch('finish');
    }
    #[On('finish')]
    public function afterSuccess()
    {
        $this->isloading = false;
        return redirect()->route('member.index');
    }


    public function generateAndSaveQRCode()
    {
        $user = Auth::user();
        $setting = Settings::first();
        $id_company = $setting->id_company;
        $url = env('MEMBER_URL') . '/?idcom=' . $id_company;
        $fileName = 'generategoogle' . '.svg'; // Unique filename for QR code, change extension as needed
        $qrCodePath = public_path('assets/') . $fileName; // Path to save QR code
        $logoPath = public_path('assets/logo.png'); // Path to your logo

        try {
            QrCode::size(185)
                ->format('svg') // Set format to JPEG
                ->merge($logoPath, 0.3, true) // Merge logo with 30% opacity
                ->margin(1)
                ->errorCorrection('M') // Error correction level
                ->generate($url, $qrCodePath);

                $this->alert('success', 'QR code generated and saved successfully', [
                    'position' => 'top-right',
                    'timer' => 3000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
        } catch (\Exception $e) {
            $this->alert('info', 'Failed to generate QR code: ' . $e->getMessage(), [
                'position' => 'top-right',
                'timer' => 3000,
                'toast' => true,
                'timerProgressBar' => true,
            ]);
        }
    }
}
