<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SilentRemoveController extends Controller
{
    private $prefix = "admin/silent-remove/";
    private $resources = [];
    private $checkPermissionAndRolesController;

    function __construct(
        CheckPermissionsAndRolesController $checkPermissionAndRolesController
    ) {
        $this->resources['prefix'] = $this->prefix;
        $this->checkPermissionAndRolesController = $checkPermissionAndRolesController;
    }

    public function index(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Silent Remove']);
        return view('admin.silent-remove.index')->with($this->resources);
    }
    public function check(Request $request)
    {
        $credentials = $request->validate([
            'apple_id' => ['required', 'email'],
            'password' => ['required'],
        ]);
        try {
            $requestAll = $request->all();
            $data = $this->sendReq($requestAll['apple_id'], $requestAll['password']);
            $this->resources['data'] = $data;
            return view('admin.silent-remove.index')->with($this->resources);
        } catch (\Throwable $th) {
            $this->resources['messages'] = array("type" => "error", "description" => $th->getMessage());
            return redirect()->back()->with('messages', $this->resources);
        }
    }
    public function sendReq($apple_id, $password)
    {
        try {
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, "https://api4all.pro/auto/removeDevices.php?key=whhpayed&appleId=$apple_id&pwd=$password");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $res = curl_exec($ch);
            $info = curl_getinfo($ch);
            curl_close($ch);
            if ($info['http_code'] == 200) {
                return $res;
            }
            return false;
        } catch (\Throwable $th) {
            throw $th;
        }
    }
}
