<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use App\Services\ServiceSIMBG;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class SyncronizeController extends Controller
{
    protected $service_simbg;
    public function __construct(ServiceSIMBG $service_simbg){
        $this->service_simbg = $service_simbg;
    }
    public function index(Request $request){
        $menuId = $request->query('menu_id');
        $user = Auth::user();
        $userId = $user->id;

        // Ambil role_id yang dimiliki user
        $roleIds = DB::table('user_role')
            ->where('user_id', $userId)
            ->pluck('role_id');

        // Ambil data akses berdasarkan role_id dan menu_id
        $roleAccess = DB::table('role_menu')
            ->whereIn('role_id', $roleIds)
            ->where('menu_id', $menuId)
            ->first();

        // Pastikan roleAccess tidak null sebelum mengakses properti
        $creator = $roleAccess->allow_create ?? 0;
        $updater = $roleAccess->allow_update ?? 0;
        $destroyer = $roleAccess->allow_destroy ?? 0;

        return view('settings.syncronize.index', compact('creator', 'updater', 'destroyer'));
    }

    public function syncPbgTask(){
        $res = $this->service_simbg->syncTaskPBG();
        return $res;
    }

    public function syncronizeTask(Request $request){
        $res = $this->service_simbg->syncTaskPBG();
        return redirect()->back()->with('success', 'Processing completed successfully');
    }

    public function getUserToken(){
        $res = $this->service_simbg->getToken();
        return $res;
    }

    public function syncIndexIntegration(Request $request, $uuid){
        $token = $request->get('token');
        $res = $this->service_simbg->syncIndexIntegration($uuid);
        return $res;
    }

    public function syncTaskDetailSubmit(Request $request, $uuid){
        $token = $request->get('token');
        $res = $this->service_simbg->syncTaskDetailSubmit($uuid, $token);
        return $res;
    }

    public function syncTaskAssignments($uuid){
        $res = $this->service_simbg->syncTaskAssignments($uuid);
        return $res;
    }
}
