<?php

namespace App\Http\Controllers\Manage\Help;

use App\Http\Controllers\Manage\Help\Transformers\HelpTransformer;
use App\Modules\Help\Services\HelpService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Hashids;

class JumpController extends Controller
{
    public function index(){
        return view('jump.index');
    }

    public function addLink(Request $request){
        $description = $request->input('description');
        $url = $request->input('url');
        $data = compact('description','url');
        $data['status'] = 1;
        $data['created_at']=date('Y-m-d H:i:s');
        $res = DB::table('url_agent')->insert($data);
        return response()->success($res);
    }

    public function getLinksList(Request $request) {
        $page = $request->input('page');
        $pagesize = $request->input('pagesize');
        $recordsTotal = DB::table('url_agent')->count('id');

        $pagecount = ceil($recordsTotal/$pagesize);
        $offset = ($page-1)*$pagesize;
        $res = DB::table('url_agent')
            ->offset($offset)
            ->limit($pagesize)
            ->get();
        foreach ($res as $item){
            $item->final_url = env('JUMP_AGENT_URL').'/jump?sign='.Hashids::encode($item->id);
        }
        return response()->success(['data'=>$res,'pagecount'=>$pagecount]);
    }

    public function jump(Request $request){
        $sign = $request->input('sign','');
        if($sign){
            $id= Hashids::decode($sign)[0];
            $url = DB::table('url_agent')->where('id',$id)->first()->url;
            header('Location: ' . $url);
        }
    }
}
