<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use PhpMqtt\Client\MqttClient;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\IotMode;

class ProcessPengembalianJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function handle(): void
    {
        try {

            $bookId = $this->data['book_id'];
            $userId = $this->data['user_id'];

            DB::table('borrow_transactions')
                ->where('koleksi_id', $bookId)
                ->where('status', 'dipinjam')
                ->update([
                    'status' => 'dikembalikan',
                    'updated_at' => now()
                ]);

            // reset mode
            IotMode::where('id', 1)->update([
                'mode' => 'standby',
                'book_id' => null,
                'user_id' => null
            ]);

            $mqtt = new MqttClient(
                '127.0.0.1',
                1883,
                'job-kembali-' . uniqid()
            );

            $mqtt->connect();

            $mqtt->publish('rfid/status', 'finish', 0);
            $mqtt->publish('rfid/mode', 'standby', 0);

            $mqtt->disconnect();

            Log::info('Pengembalian berhasil');

        } catch (\Throwable $e) {

            Log::error(
                'Queue Pengembalian Error: ' .
                $e->getMessage()
            );
        }
    }
}

