<?php

namespace App\Http\Controllers;

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

class DomainController extends Controller
{
    private $prefix = "admin/domains/";
    private $resources = [];
    private $checkPermissionAndRolesController;
    private $userController;

    public function __construct(
        CheckPermissionsAndRolesController $checkPermissionAndRolesController,
        UserController $userController
    )
    {

        $this->resources['prefix'] = $this->prefix;
        $this->checkPermissionAndRolesController = $checkPermissionAndRolesController;
        $this->userController = $userController;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, Auth $auth)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'View Domain']);
        $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
        $query = Domain::orderBy('id', 'desc');
        if (!$superAdmin)
        {
            $query->where('created_by', $request->user()->id);
        }
        $this->resources['data']  = $query->paginate(15);

        return view('admin.domains.domains_manage')->with($this->resources);
    }
    public function search(Request $request)
    {
        try
        {
            $request->validate([
                'search' => ['required'],
            ]);
            $order = Domain::query();
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            if ($request->search)
            {
                $order->where('link', 'Like', '%' . $request->search . '%');
                if (!$superAdmin)
                {
                    $order->where('created_by', $request->user()->id);
                }
            }
            $this->resources['data'] = $order->orderBy('id', 'DESC')->paginate(15);
            return view('admin.domains.domains_manage')->with($this->resources);
        }
        catch (\Throwable $th)
        {
            $this->resources['messages'] = array("type" => "error", "description" => $th->getMessage());
            return redirect()->back()->with('messages', $this->resources);
        }
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Create Domain']);
        return view('admin.domains.domain_add')->with($this->resources);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Create Domain']);

        $credentials = $request->validate([
            'link' => ['required', 'url'],
        ]);
        try
        {
            $requestParams = $request->all();
            $storeParam = ["link" => $requestParams['link'], "created_by" => $request->user()->id];
            $domain = Domain::create($storeParam);
            // Authorize the domain for the user who created it
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            if (!$superAdmin)
            {
                DomainAuthorization::updateOrCreate(
                    ['user_id' => $storeParam['created_by'], 'domain_id' => $domain['id']],
                    [
                        'user_id' => $storeParam['created_by'],
                        'domain_id' => $domain['id'],
                        'authorization' => 1,
                    ]
                );
            }
            $this->resources['messages'] = array("type" => "success", "description" => "Domain 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);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Domain  $domain
     * @return \Illuminate\Http\Response
     */
    public function show(Domain $domain)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Domain  $domain
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, Domain $domain)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Update Domain']);
        $this->resources['data'] = $this->getDomainById($request);
        return view('admin.domains.domain_edit')->with($this->resources);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Domain  $domain
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Domain $domain)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Update Domain']);

        $credentials = $request->validate([
            'id' => ['required'],
            'link' => ['required']
        ]);
        try
        {
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $query = Domain::where('id', $credentials['id']);
            if (!$superAdmin)
            {
                $query->where('created_by', $request->user()->id);
            }
            $result = $query->update(["link" => $credentials['link']]);
            if ($result)
            {
                $this->resources['messages'] = array("type" => "success", "description" => "Domain updated success");
            }
            else
            {
                $this->resources['messages'] = array("type" => "error", "description" => "Domain 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);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Domain  $domain
     * @return \Illuminate\Http\Response
     */
    public function delete(Request $request, Domain $domain)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Delete Domain']);
        $request->validate([
            'id' => ['required'],
        ]);
        try
        {
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $query = Domain::where('id', $request->id);
            if (!$superAdmin)
            {
                $query->where('created_by', $request->user()->id);
            }
            $result = $query->delete();
            if ($result)
            {
                // Also delete the domain authorization if it exists
                DomainAuthorization::where('domain_id', $request->id)->delete();
            }
            $this->resources['messages'] = array("type" => "success", "description" => "Domain deleted 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 getDomainById($request)
    {
        try
        {
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $query = Domain::where('id', $request->id);
            if (!$superAdmin)
            {
                $query->where('created_by', $request->user()->id);
            }
            $result = $query->firstOrFail();
            return $result;
        }
        catch (\Exception $e)
        {
            throw $e;
        }
    }
    public function statusUpdate(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Enable Disable Domain']);
        $request->validate([
            'id' => ['required'],
            'current' => ['required'],
        ]);
        try
        {
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $query = Domain::where('id', $request->id);
            if (!$superAdmin)
            {
                $query->where('created_by', $request->user()->id);
            }
            if ($request->current == 1)
            {
                $result = $query->update(['status' => 0]);
            }
            else
            {
                $result = $query->update(['status' => 1]);
            }
            if ($result)
            {
                $this->resources['messages'] = array("type" => "success", "description" => "Domain enabled/disabled success");
            }
            else
            {
                $this->resources['messages'] = array("type" => "error", "description" => "Domain enabled/disabled 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 checkDomainStatus(Request $request)
    {
        $request->validate([
            'domain_id' => ['required'],
        ]);
        try
        {
            $domain = Domain::findOrFail($request->domain_id);
            return response()->json(['status' => $domain->status]);
        }
        catch (\Exception $e)
        {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
