<?php

namespace Modules\Patient\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

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

    public $action;
    public $zakatFund;

    public $tries = 2;

    public function backoff()
    {
        return [60, 120];
    }

    public function __construct($zakatFund, $action = 'sync')
    {
        $this->zakatFund = $zakatFund;
        $this->action = $action;
    }

    public function handle()
    {
        $url = config('core.pms.shared_pms_url');
        $token = config('core.pms.shared_pms_token');

        if (empty($url)) {
            Log::error('PMS sync failed: configuration "core.pms.shared_pms_url" not found');
        }

        if (empty($token)) {
            Log::error('PMS sync failed: configuration "core.pms.shared_pms_token" not found');
        }

        $response = Http::withToken($token)
            ->timeout(10)->post($url . '/zakat-fund/sync-from-erp', [
                'action' => $this->action,
                'name'     => $this->zakatFund->name,
                'code'     => $this->zakatFund->code,
                'status'   => $this->zakatFund->status == 'Active' ? '1' : '2',
                'priority' => $this->zakatFund->priority,
                'amount'   => $this->zakatFund->amount,
                'is_synced' => $this->zakatFund->is_synced ? '1' : '0',
            ]);

        if ($response->successful()) {
            $this->zakatFund->updateQuietly(['is_synced' => true]);
        } else {
            Log::error("ERP to PMS Sync Failed: " . $response->body());
            throw new \Exception("Sync Failed");
        }
    }
}
