<?php

namespace App\Http\Controllers;

use App\Models\AdminNotification;
use App\Models\File;
use App\Models\Frontend;
use App\Models\Language;
use App\Models\Page;
use App\Models\Subscriber;
use App\Models\SupportMessage;
use App\Models\SupportTicket;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request as RequestFacade;

class SiteController extends Controller
{
    public function index()
    {
        $reference = @$_GET['reference'];
        if ($reference) {
            session()->put('reference', $reference);
        }
        $pageTitle = 'Home';
        $sections = Page::where('tempname', $this->activeTemplate)->where('slug', '/')->first();
        return view($this->activeTemplate . 'home', compact('pageTitle', 'sections'));
    }

    public function pages($slug)
    {
        $page = Page::where('tempname', $this->activeTemplate)->where('slug', $slug)->firstOrFail();
        $pageTitle = $page->name;
        $sections = $page->secs;
        return view($this->activeTemplate . 'pages', compact('pageTitle', 'sections'));
    }


    public function contact()
    {
        $pageTitle = "Contact Us";
        return view($this->activeTemplate . 'contact', compact('pageTitle'));
    }

    public function searchByType(Request $request)
    {
        $this->validate(
            $request,
            [
                'search' => 'required',
            ],
            [
                'search.required' => 'Please enter something your desired.'
            ]
        );
        $query = $request->search;
        $pageTitle = 'Search Result';
        $explores = File::where('title', 'LIKE', "%$query%")->orWhere('description', 'LIKE', "%$query%")->where('status', 1)->get();
        return view($this->activeTemplate . 'explore', compact('pageTitle', 'explores'));
    }


    public function contactSubmit(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required',
            'subject' => 'required|string|max:255',
            'message' => 'required',
        ]);

        if (!verifyCaptcha()) {
            $notify[] = ['error', 'Invalid captcha provided'];
            return back()->withNotify($notify);
        }

        $request->session()->regenerateToken();

        $random = getNumber();

        $ticket = new SupportTicket();
        $ticket->user_id = auth()->id() ?? 0;
        $ticket->name = $request->name;
        $ticket->email = $request->email;
        $ticket->priority = 2;


        $ticket->ticket = $random;
        $ticket->subject = $request->subject;
        $ticket->last_reply = Carbon::now();
        $ticket->status = 0;
        $ticket->save();

        $adminNotification = new AdminNotification();
        $adminNotification->user_id = auth()->user() ? auth()->user()->id : 0;
        $adminNotification->title = 'A new support ticket has opened ';
        $adminNotification->click_url = urlPath('admin.ticket.view', $ticket->id);
        $adminNotification->save();

        $message = new SupportMessage();
        $message->support_ticket_id = $ticket->id;
        $message->message = $request->message;
        $message->save();

        $notify[] = ['success', 'Ticket created successfully!'];

        return to_route('ticket.view', [$ticket->ticket])->withNotify($notify);
    }

    public function policyPages($slug, $id)
    {
        $policy = Frontend::where('id', $id)->where('data_keys', 'policy_pages.element')->firstOrFail();
        $pageTitle = $policy->data_values->title;
        return view($this->activeTemplate . 'policy', compact('policy', 'pageTitle'));
    }

    public function changeLanguage($lang = null)
    {
        $language = Language::where('code', $lang)->first();
        if (!$language) $lang = 'en';
        session()->put('lang', $lang);
        return back();
    }

    public function blogDetails($slug, $id)
    {
        $blog = Frontend::where('id', $id)->where('data_keys', 'blog.element')->firstOrFail();
        $pageTitle = $blog->data_values->title;
        return view($this->activeTemplate . 'blog_details', compact('blog', 'pageTitle'));
    }

    public function exploreFiles()
    {
        $pageTitle = 'Explore';
        $activePaginate = 1;
        $files = File::where('status', 1)->latest()->get();
        $explores = $this->makeCollection($files);

        $perPage = 12;
        $currentPage = LengthAwarePaginator::resolveCurrentPage();
        $pagedData = $explores->slice(($currentPage - 1) * $perPage, $perPage)->all();
        $explores = new LengthAwarePaginator($pagedData, $explores->count(), $perPage);

        $explores->withPath(RequestFacade::url());

        return view($this->activeTemplate . 'explore', compact('pageTitle', 'explores', 'activePaginate'));
    }

    public function filesByCategory($id)
    {
        $pageTitle = 'Search Result';
        $activePaginate = 1;
        $files = File::where('status', 1)->where('category_id', $id)->latest()->get();
        $explores = $this->makeCollection($files);

        $perPage = 12;
        $currentPage = LengthAwarePaginator::resolveCurrentPage();
        $pagedData = $explores->slice(($currentPage - 1) * $perPage, $perPage)->all();
        $explores = new LengthAwarePaginator($pagedData, $explores->count(), $perPage);

        $explores->withPath(RequestFacade::url());

        return view($this->activeTemplate . 'explore', compact('pageTitle', 'explores', 'activePaginate'));
    }

    public function searchByTag($id)
    {
        $pageTitle = 'Search Result';
        $activePaginate = 1;
        $files = File::where('status', 1)->get();
        $files = $files->filter(function ($file) use ($id) {
            return in_array($id, $file->tags);
        });

        $explores = $this->makeCollection($files);

        $perPage = 12;
        $currentPage = LengthAwarePaginator::resolveCurrentPage();
        $pagedData = $explores->slice(($currentPage - 1) * $perPage, $perPage)->all();
        $explores = new LengthAwarePaginator($pagedData, $explores->count(), $perPage);

        $explores->withPath(RequestFacade::url());

        return view($this->activeTemplate . 'explore', compact('pageTitle', 'explores', 'activePaginate'));
    }

    public function fileDetails($id)
    {
        $pageTitle = 'File Detail';
        $file = File::find($id);
        return view($this->activeTemplate . 'file_details', compact('pageTitle', 'file'));
    }

    public function filterByCat(Request $request)
    {
        $givenCats = $request->categories;
        $givenTags = $request->tags;

        if (isset($givenCats) && !isset($givenTags)) {
            $pageTitle = 'Search Result';
            $explores = File::whereIn('category_id', $givenCats)->where('status', 1)->get();
            return view($this->activeTemplate . 'explore', compact('pageTitle', 'explores'));
        }

        if (!isset($givenCats) && isset($givenTags)) {
            $pageTitle = 'Search Result';
            $files = File::where('status', 1)->get();
            $explores = $files->filter(function ($file) use ($givenTags) {
                return $this->arrayContainsTags($file->tags, $givenTags);
            });
            return view($this->activeTemplate . 'explore', compact('pageTitle', 'explores'));
        }

        if (isset($givenCats) && isset($givenTags)) {
            $pageTitle = 'Search Result';
            $files = File::whereIn('category_id', $givenCats)->where('status', 1)->get();

            $files2 = $files->filter(function ($file) use ($givenTags) {
                return $this->arrayContainsTags($file->tags, $givenTags);
            });

            $explores = $files->merge($files2);
            return view($this->activeTemplate . 'explore', compact('pageTitle', 'explores'));
        }
    }

    private function arrayContainsTags($fileTags, $searchTags)
    {
        foreach ($searchTags as $searchTag) {
            if (!in_array($searchTag, $fileTags)) {
                return false;
            }
        }
        return true;
    }

    public function makeCollection($explores)
    {
        $biggerWidth = [];
        $biggerHeight = [];

        foreach ($explores as $item) {
            if ($item->width > $item->height) {
                $biggerWidth[] = $item;
            } else {
                $biggerHeight[] = $item;
            }
        }

        $orderedExplores = [];
        $biggerWidthCount = count($biggerWidth);
        $biggerHeightCount = count($biggerHeight);

        $rowCount = max(ceil($biggerWidthCount / 2), ceil($biggerHeightCount / 2));

        for ($i = 0; $i < $rowCount; $i++) {
            if ($i % 2 === 0) {
                if (isset($biggerWidth[$i])) {
                    $orderedExplores[] = $biggerWidth[$i];
                }

                if (isset($biggerHeight[$i * 2])) {
                    $orderedExplores[] = $biggerHeight[$i * 2];
                }

                if (isset($biggerHeight[$i * 2 + 1])) {
                    $orderedExplores[] = $biggerHeight[$i * 2 + 1];
                }
            } else {
                if (isset($biggerHeight[$i * 2])) {
                    $orderedExplores[] = $biggerHeight[$i * 2];
                }

                if (isset($biggerHeight[$i * 2 + 1])) {
                    $orderedExplores[] = $biggerHeight[$i * 2 + 1];
                }

                if (isset($biggerWidth[$i])) {
                    $orderedExplores[] = $biggerWidth[$i];
                }
            }
        }

        $explores = collect($orderedExplores);

        return $explores;
    }


    public function cookieAccept()
    {
        $general = gs();
        Cookie::queue('gdpr_cookie', $general->site_name, 43200);
        return back();
    }

    public function cookiePolicy()
    {
        $pageTitle = 'Cookie Policy';
        $cookie = Frontend::where('data_keys', 'cookie.data')->first();
        return view($this->activeTemplate . 'cookie', compact('pageTitle', 'cookie'));
    }

    public function placeholderImage($size = null)
    {
        $imgWidth = explode('x', $size)[0];
        $imgHeight = explode('x', $size)[1];
        $text = $imgWidth . '×' . $imgHeight;
        $fontFile = realpath('assets/font') . DIRECTORY_SEPARATOR . 'RobotoMono-Regular.ttf';
        $fontSize = round(($imgWidth - 50) / 8);
        if ($fontSize <= 9) {
            $fontSize = 9;
        }
        if ($imgHeight < 100 && $fontSize > 30) {
            $fontSize = 30;
        }

        $image     = imagecreatetruecolor($imgWidth, $imgHeight);
        $colorFill = imagecolorallocate($image, 255, 255, 255);
        $bgFill    = imagecolorallocate($image, 28, 35, 47);
        imagefill($image, 0, 0, $bgFill);
        $textBox = imagettfbbox($fontSize, 0, $fontFile, $text);
        $textWidth  = abs($textBox[4] - $textBox[0]);
        $textHeight = abs($textBox[5] - $textBox[1]);
        $textX      = ($imgWidth - $textWidth) / 2;
        $textY      = ($imgHeight + $textHeight) / 2;
        header('Content-Type: image/jpeg');
        imagettftext($image, $fontSize, 0, $textX, $textY, $colorFill, $fontFile, $text);
        imagejpeg($image);
        imagedestroy($image);
    }

    public function sendNewsLetter(Request $request)
    {
        $this->validate($request, [
            'newsletter' => 'required|email|unique:subscribers,email',
        ]);
        $subscriber = new Subscriber();
        $subscriber->email = $request->newsletter;
        $subscriber->save();
        $notify[] = ['success', 'You email has been added successfully'];
        return back()->withNotify($notify);
    }
}
