<?php

namespace App\Http\Controllers;

use App\Constants\Status;
use App\Models\AdminNotification;
use App\Models\Advertisement;
use App\Models\Category;
use App\Models\Frontend;
use App\Models\Language;
use App\Models\Location;
use App\Models\Page;
use App\Models\Plan;
use App\Models\Seminar;
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\Support\Facades\Validator;

class SiteController extends Controller {
    public function index() {

        $pageTitle   = 'Home';
        $sections    = Page::where('tempname', activeTemplate())->where('slug', '/')->first();
        $seoContents = $sections->seo_content;
        $seoImage    = @$seoContents->image ? getImage(getFilePath('seo') . '/' . @$seoContents->image, getFileSize('seo')) : null;
        return view('Template::home', compact('pageTitle', 'sections', 'seoContents', 'seoImage'));
    }

    public function pages($slug) {
        $page        = Page::where('tempname', activeTemplate())->where('slug', $slug)->firstOrFail();
        $pageTitle   = $page->name;
        $sections    = $page->secs;
        $seoContents = $page->seo_content;
        $seoImage    = @$seoContents->image ? getImage(getFilePath('seo') . '/' . @$seoContents->image, getFileSize('seo')) : null;
        return view('Template::pages', compact('pageTitle', 'sections', 'seoContents', 'seoImage'));
    }

    public function contact() {
        $pageTitle   = "Contact Us";
        $user        = auth()->user();
        $sections    = Page::where('tempname', activeTemplate())->where('slug', 'contact')->first();
        $seoContents = $sections->seo_content;
        $seoImage    = @$seoContents->image ? getImage(getFilePath('seo') . '/' . @$seoContents->image, getFileSize('seo')) : null;
        return view('Template::contact', compact('pageTitle', 'user', 'sections', 'seoContents', 'seoImage'));
    }

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

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

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

        $random = getNumber();

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

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

        $adminNotification            = new AdminNotification();
        $adminNotification->user_id   = auth()->user() ? auth()->user()->id : 0;
        $adminNotification->title     = 'A new contact message has been submitted';
        $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) {
        $policy      = Frontend::where('slug', $slug)->where('data_keys', 'policy_pages.element')->firstOrFail();
        $pageTitle   = $policy->data_values->title;
        $seoContents = $policy->seo_content;
        $seoImage    = @$seoContents->image ? frontendImage('policy_pages', $seoContents->image, getFileSize('seo'), true) : null;
        return view('Template::policy', compact('policy', 'pageTitle', 'seoContents', 'seoImage'));
    }

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

        session()->put('lang', $lang);
        return back();
    }

    public function blogs() {
        $pageTitle   = 'Blogs';
        $blogs       = Frontend::where('data_keys', 'blog.element')->latest()->paginate(getPaginate());
        $sections    = Page::where('tempname', activeTemplate())->where('slug', 'blog')->first();
        $seoContents = $sections->seo_content;
        $seoImage    = @$seoContents->image ? getImage(getFilePath('seo') . '/' . @$seoContents->image, getFileSize('seo')) : null;
        return view('Template::blogs', compact('blogs', 'pageTitle', 'seoContents', 'seoImage', 'sections'));
    }

    public function blogDetails($slug) {
        $blog = Frontend::where('slug', $slug)->where('data_keys', 'blog.element')->firstOrFail();
        $blog->increment('views');
        $recentBlogs = Frontend::where('slug', '!=', $slug)->where('data_keys', 'blog.element')->latest('id')->take(10)->get();
        $pageTitle   = 'Blog Detail';
        $seoContents = $blog->seo_content;
        $seoImage    = @$seoContents->image ? frontendImage('blog', $seoContents->image, getFileSize('seo'), true) : null;
        return view('Template::blog_details', compact('blog', 'pageTitle', 'seoContents', 'seoImage', 'recentBlogs'));
    }

    public function cookieAccept() {
        Cookie::queue('gdpr_cookie', gs('site_name'), 43200);
    }

    public function cookiePolicy() {
        $cookieContent = Frontend::where('data_keys', 'cookie.data')->first();
        abort_if($cookieContent->data_values->status != Status::ENABLE, 404);
        $pageTitle = 'Cookie Policy';
        $cookie    = Frontend::where('data_keys', 'cookie.data')->first();
        return view('Template::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/solaimanLipi_bold.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, 100, 100, 100);
        $bgFill    = imagecolorallocate($image, 255, 255, 255);
        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 maintenance() {
        $pageTitle = 'Maintenance Mode';
        if (gs('maintenance_mode') == Status::DISABLE) {
            return to_route('home');
        }
        $maintenance = Frontend::where('data_keys', 'maintenance.data')->first();
        return view('Template::maintenance', compact('pageTitle', 'maintenance'));
    }
    public function subscribe(Request $request) {
        $rules = [
            'email' => 'required|email|unique:subscribers,email',
        ];
        $message = [
            "email.unique" => 'You are already a subscriber',
        ];
        $validator = validator()->make($request->all(), $rules, $message);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()->getMessages()]);
        }
        $subscribe        = new Subscriber();
        $subscribe->email = $request->email;
        $subscribe->save();
        return response()->json(['success' => true, 'message' => 'Thanks for subscribe']);
    }

    public function addClickUp(Request $request) {
        $validate = Validator::make($request->all(), [
            'id' => 'required|integer|gt:0',
        ]);

        if ($validate->fails()) {
            return response()->json($validate->errors());
        }

        $add = Advertisement::findOrFail($request->id);
        $add->increment('click');
    }

    //Tour plan
    public function plans() {
        $pageTitle = 'Tour Plans';
        $from_date = null;
        $to_date   = null;

        $request = request();

        $plans = Plan::active()->searchable(['name', 'price', 'capacity', 'duration', 'category:name', 'location:name'])->filter(['category_id', 'location_id']);

        if ($request->from_date) {
            $from_date = Carbon::parse($request->from_date);
        }
        if ($request->to_date) {
            $to_date = Carbon::parse($request->to_date);
        }

        if ($from_date) {
            $plans = $plans->where('departure_time', '>=', $from_date);
        }

        if ($to_date) {
            if (!$from_date) {
                $notify[] = ['error', 'Have to select to date first'];
                return back()->withNotify($notify);
            }
            if ($to_date < $from_date) {
                $notify[] = ['error', 'Must be grater than from date'];
                return back()->withNotify($notify);
            }
            $plans = $plans->where('departure_time', '<=', $to_date);
        }

        if ($request->min_price) {
            $plans = $plans->where('price', '>=', $request->min_price);
        }

        if ($request->max_price) {
            $plans = $plans->where('price', '<=', $request->max_price);
        }

        $plans = $plans->orderBy('id', 'DESC')->paginate(getPaginate(18));

        $categories = Category::active()->whereHas('plans', function ($q) {
            $q->active();
        })->orderBy('name')->get();
        $locations = Location::active()->whereHas('plans', function ($q) {
            $q->active();
        })->orderBy('name')->get();

        return view('Template::plan.index', compact('pageTitle', 'plans', 'categories', 'locations'));
    }

    public function planDetails($id, $slug) {
        $plan        = Plan::active()->where('id', $id)->withCount('ratings')->withAvg('ratings', 'rating')->withCount('ratings')->firstOrFail();
        $pageTitle   = $plan->name;
        $seoContents = $plan->seo_content;
        $seoImage    = @$seoContents->image ? frontendImage('plan', $seoContents->image, getFileSize('seo'), true) : null;
        $breadcrumb  = getContent('tour_plan_breadcrumb.content', true);
        return view('Template::plan.details', compact('plan', 'pageTitle', 'seoContents', 'seoImage', 'breadcrumb'));
    }

    //Seminar plan
    public function seminars() {
        $pageTitle = 'Seminar Plans';
        $from_date = null;
        $to_date   = null;

        $request = request();

        $seminars = Seminar::active()->searchable(['name', 'price', 'capacity', 'duration', 'category:name', 'location:name'])->filter(['category_id', 'location_id']);

        if ($request->from_date) {
            $from_date = Carbon::parse($request->from_date);
        }
        if ($request->to_date) {
            $to_date = Carbon::parse($request->to_date);
        }

        if ($from_date) {
            $seminars = $seminars->where('start_time', '>=', $from_date);
        }

        if ($to_date) {
            if (!$from_date) {
                $notify[] = ['error', 'Have to select to date first'];
                return back()->withNotify($notify);
            }
            if ($to_date < $from_date) {
                $notify[] = ['error', 'Must be grater than from date'];
                return back()->withNotify($notify);
            }
            $seminars = $seminars->where('start_time', '<=', $to_date);
        }

        if ($request->min_price) {
            $seminars = $seminars->where('price', '>=', $request->min_price);
        }

        if ($request->max_price) {
            $seminars = $seminars->where('price', '<=', $request->max_price);
        }

        $seminars = $seminars->orderBy('id', 'DESC')->paginate(getPaginate());

        $categories = Category::active()->whereHas('seminars', function ($q) {
            $q->active();
        })->orderBy('name')->get();
        $locations = Location::active()->whereHas('seminars', function ($q) {
            $q->active();
        })->orderBy('name')->get();

        return view('Template::seminar.index', compact('seminars', 'pageTitle', 'categories', 'locations'));
    }

    public function seminarDetails($id, $slug) {
        $seminar            = Seminar::active()->where('id', $id)->with('ratings')->withAvg('ratings', 'rating')->withCount('ratings')->firstOrFail();
        $pageTitle          = $seminar->name;
        $seminar_breadcrumb = getContent('seminar_breadcrumb.content', true);
        $seoContents        = $seminar->seo_content;
        $seoImage           = @$seoContents->image ? frontendImage('seminar', $seoContents->image, getFileSize('seo'), true) : null;
        $breadcrumb         = getContent('seminar_breadcrumb.content', true);
        return view('Template::seminar.details', compact('seminar', 'pageTitle', 'seoContents', 'seoImage', 'breadcrumb'));
    }
}
