<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Entities\APIData;
use laravelLara\infoinst\utils\ApiCheckHelper;
use Illuminate\Support\Facades\Http;
use App\Models\Setting;
use App\Models\User;
use Auth;

class EnvatoAppinfoController extends Controller
{
    use ApiCheckHelper;
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index()
    {

        $this->authorize('App Purchase Code Access');

        $apidata = APIData::first();
        $data['apidata'] = $apidata;

        // Check purchase code
        $output = '';
        $purchaseCodeData = $this->verifyupdatechecker(setting('update_setting'));
        if ($purchaseCodeData->valid == false) {
            $data['invalid'] = 'No Purchase Code';
        }
        if ($purchaseCodeData->valid == true) {
            $checkapis = $this->updatesettingapi(setting('update_setting'));

            // Format object data
            $result = json_decode($checkapis);

            if ($result != null) {
                $output .= '
                    <div class="card">
                        <div class="card-header border-0">
                            <h4 class="card-title">App Purchase Code</h4>
                            <div class="card-options">
                                <span class="badge badge-gray">Version:' . $result->version . '</span>
                            </div>
                        </div>
                        <div class="card-body">
                            <form>
                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-xl-6 col-lg-6 col-md-6">
                                            <input type="text" class="form-control" name="envato_search" value="' . str_pad(substr($result->purchaseCode, -4), strlen($result->purchaseCode), '*', STR_PAD_LEFT) . '" readonly disabled>
                                            <input type="hidden" class="form-control" name="envato_id" value="' . $result->purchaseCode . '">
                                        </div>
                                    </div>
                                </div>
                            </form>
                            <table class="table table-striped table-bordered">
                                <tbody>
                                    <tr>
                                        <td class="w-30"><b>App License:</b></td>
                                        <td>' . $result->license . '</td>
                                    </tr>
                                    <tr>
                                        <td class="w-30"><b>Application Url:</b></td>
                                        <td>' . $result->url . '</td>
                                    </tr>
                                    <tr>
                                        <td class="w-30"><b>Author:</b></td>
                                        <td>' . $result->author . '</td>
                                    </tr>

                                </tbody>
                            </table>
                        </div>
                    </div>
                ';
            }
            if ($result == null) {
                $data['invalid'] = 'No Purchase Code';
            }

            $data['output'] = $output;
        }
        return $data;
    }
    public function testinginfo()
    {
        // return view('Installation::installer.newupdate.testinginfo');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        // Check purchase code
        $this->validate($request, [
            'envato_id' => 'required'
        ]);
        $user = User::first();
        $purchaseCodeData = $this->verifysettingcreate($request->envato_id, $user->firstname, $user->lastname, $user->email);
        if ($purchaseCodeData->App == 'invalid') {
            return response(['error' => $purchaseCodeData->message]);
        }
        if ($purchaseCodeData->App == 'old') {
            return response(['error' => $purchaseCodeData->message]);
        }
        if ($purchaseCodeData->App == 'New') {

            if (Setting::where("key", "newupdate")->first()) {
                $uset = Setting::where("key", "newupdate")->first();
                $uset->value = config('installer.requirements.version');
                $uset->save();
            } else {
                $uset = new Setting();
                $uset->key = 'newupdate';
                $uset->value = config('installer.requirements.version');
                $uset->save();
            }

            if ($request->envato_id) {
                $data['update_setting'] = $request->envato_id;
                $this->updateSettings($data);
            }

            $usermailkey = Setting::where("key", "mail_key_set")->first();
            $usermailkey->value = $purchaseCodeData->mail_key;
            $usermailkey->save();

            return response(['success' => "Updated Successfully", 'status' => 'success']);
        }
    }

    public function envatogetdetails($id)
    {

        $apiURL = 'https://panel.spruko.com/api/api/apidetail/deletes/' . $id;

        $client = new \GuzzleHttp\Client();
        $response = Http::delete($apiURL);
        $statusCode = $response->getStatusCode();
        $responseBody = json_decode($response->getBody(), true);

        $data['envato_purchasecode'] = null;
        $this->updateSettings($data);

        return response()->json(['error' => 'Deleted Successfully']);
    }

    /**
     *  Settings Save/Update.
     *
     * @return \Illuminate\Http\Response
     */
    private function updateSettings($data)
    {

        foreach ($data as $key => $val) {
            $setting = Setting::where('key', $key);
            if ($setting->exists())
                $setting->first()->update(['value' => $val]);
        }
    }
}
