<?php

namespace App\Http\Controllers;

use App\Models\Domain;
use App\Models\UrlShortener;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UrlShortenerController extends Controller
{
    private $prefix = "admin/url-shortener/";
    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' => 'Url Shortener']);
        $this->resources['data'] = $this->getUrls($request, 15);
        return view('admin.url-shortener.us_manage')->with($this->resources);
    }
    public function create(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Url Shortener']);
        $this->resources['authorized_domains'] = $this->getAuthorizedDomainList($request);
        return view('admin.url-shortener.us_add')->with($this->resources);
    }
    public function store(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Url Shortener']);

        $credentials = $request->validate([
            'domain_id' => ['required'],
            'long_link' => ['required'],
            'custom_name' => ['required', 'unique:url_shorteners']
        ]);
        try {

            $storeParam = $request->except('_token');

            $storeParam['created_by'] = $request->user()->id;
            UrlShortener::create($storeParam);
            $this->resources['messages'] = array("type" => "success", "description" => "Short Url creation success");
            return redirect()->back()->with('messages', $this->resources);
        } catch (\Throwable $th) {
            $this->resources['messages'] = array("type" => "error", "description" => $th->getMessage());
            return redirect()->back()->with('messages', $this->resources);
        }
    }
    public function edit(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission'=>'Edit SMTP']);
        $this->resources['authorized_domains'] = $this->getAuthorizedDomainList($request);
        $this->resources['data'] = $this->getUrlById($request);
        return view('admin.url-shortener.us_edit')->with($this->resources);
    }
    public function update(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Url Shortener']);

        $credentials = $request->validate([
            'id' => ['required'],
            'domain_id' => ['required'],
            'long_link' => ['required'],
            'custom_name' => ['required']
        ]);
        try {
            $get = $this->getUrlById($request);
            if($request->custom_name == $get->custom_name){
                if(Auth::user()->id != $get->created_by){
                    $request->validate([
                        'custom_name' => ['required', 'unique:url_shorteners']
                    ]);
                }
            }
            $storeParam = $request->except('_token');
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $query = UrlShortener::where('id', $request->id);
            if(!$superAdmin){
                $query->where('created_by', $request->user()->id);
            }
            $result = $query->update($storeParam);
            if($result){
                $this->resources['messages'] = array("type" => "success", "description"=>"Url updated success");
            }else{
                $this->resources['messages'] = array("type" => "error", "description"=>"Url updated failed");
            }
            return redirect()->back()->with('messages',$this->resources);
        } catch (\Throwable $th) {
            $this->resources['messages'] = array("type" => "error", "description"=>$th->getMessage());
            return redirect()->back()->with('messages',$this->resources);
        }
    }
    public function search(Request $request)
    {
        try {
            $request->validate([
                'search' => ['required'],
            ]);
            $order = UrlShortener::query();
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            if ($request->search) {
                $order->where('name', 'Like', '%' . $request->search . '%');
                if (!$superAdmin) {
                    $order->where('created_by', $request->user()->id);
                }
            }
            $this->resources['data'] = $order->orderBy('id', 'DESC')->paginate(15);
            return view('admin.url-shortener.us_manage')->with($this->resources);
        } catch (\Throwable $th) {
            $this->resources['messages'] = array("type" => "error", "description" => $th->getMessage());
            return redirect()->back()->with('messages', $this->resources);
        }
    }
    public function delete(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Url Shortener']);
        $request->validate([
            'id' => ['required'],
        ]);
        try {
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $query = UrlShortener::where('id', $request->id);
            if (!$superAdmin) {
                $query->where('created_by', $request->user()->id);
            }
            $result = $query->delete();

            if ($result) {
                $this->resources['messages'] = array("type" => "success", "description" => "Url deleted success");
            } else {
                $this->resources['messages'] = array("type" => "error", "description" => "Url deleted failed");
            }
            return redirect()->back()->with('messages', $this->resources);
        } catch (\Throwable $th) {
            $this->resources['messages'] = array("type" => "error", "description" => $th->getMessage());
            return redirect()->back()->with('messages', $this->resources);
        }
    }
    public function getUrls($request, $count)
    {
        try {

            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $query = UrlShortener::join('domains', 'url_shorteners.domain_id', 'domains.id')
            ->select("url_shorteners.*", "domains.link as domain")
            ->orderBy('url_shorteners.id', 'desc');
            if (!$superAdmin) {
                $query->where('url_shorteners.created_by', $request->user()->id);
            }
            $result = $query->paginate($count);
            return $result;
        } catch (\Exception $e) {
            throw $e;
        }
    }
    public function getUrlByCustomName($name)
    {
        try {
            $result = UrlShortener::join('domains', 'url_shorteners.domain_id', 'domains.id')
            ->select("url_shorteners.*", "domains.link as domain")
            ->where('url_shorteners.custom_name', $name)
            ->first();
            return $result;
        } catch (\Exception $e) {
            throw $e;
        }
    }
    public function getUrlById($request)
    {
        try{
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $query = UrlShortener::where('id', $request->id);
            if(!$superAdmin){
                $query->where('created_by', $request->user()->id);
            }
            $result = $query->first();
            return $result;
        }catch(\Exception $e){
            throw $e;
        }
    }
    public function getAuthorizedDomainList($request)
    {
        try {
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $query =  Domain::join('domain_authorizations', 'domains.id', 'domain_authorizations.domain_id');
            if (!$superAdmin) {
                $query->where('domain_authorizations.authorization', 1)->where('domain_authorizations.user_id', $request->user()->id);
            }
            $result = $query->select('domains.*')->get();
            return $result;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    public function shortenerRedirect(Request $request, $name)
    {
        try{
            if($name != ""){
                $data = $this->getUrlByCustomName($name);
                if($data){
                    return redirect()->to($data->long_link);
                }
            }
            abort(404);
        }catch (\Throwable $th) {
            dd($th);
            abort(404);
        }
    }
}
