<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Hash;
use Auth;
use DB;
use App\Mail\Websitemail;
use App\Models\User;
use App\Models\Admin;
use App\Models\Slider;
use App\Models\Service;
use App\Models\ServiceFaq;
use App\Models\Setting;
use App\Models\Portfolio;
use App\Models\TeamMember;
use App\Models\TeamMemberExperience;
use App\Models\Testimonial;
use App\Models\Faq;
use App\Models\CustomPage;
use App\Models\Post;
use App\Models\PostCategory;
use App\Models\PricingPlan;
use App\Models\Offer;
use App\Models\OfferElement;
use App\Models\Client;
use App\Models\Subscriber;
use App\Models\Home1Section;
use App\Models\Home2Section;
use App\Models\Home3Section;
use App\Models\OtherPageItem;
use App;

class FrontController extends Controller
{
    public function home()
    {
        if(session('current_home') == 'Home Page 1') {
            $sliders = Slider::orderBy('id','asc')->get();
            $home1_all_data = Home1Section::get();
            foreach($home1_all_data as $item) {
                $home1_item[$item->name] = $item->value;
            }
            $services = Service::orderBy('id','asc')->limit($home1_item['s2_services_how_many'])->get();
            $portfolios = Portfolio::orderBy('id','asc')->limit($home1_item['s4_portfolios_how_many'])->get();
            $faqs = Faq::orderBy('id','asc')->limit($home1_item['s6_faqs_how_many'])->get();
            $clients = Client::orderBy('id','asc')->get();
            $testimonials = Testimonial::orderBy('id','asc')->get();
            $posts = Post::orderBy('id','desc')->limit($home1_item['s9_posts_how_many'])->get();

            return view('front.home-1', compact('sliders', 'home1_item', 'services', 'portfolios', 'faqs', 'clients', 'testimonials', 'posts'));
        } 
        elseif(session('current_home') == 'Home Page 2') {
            $sliders = Slider::orderBy('id','asc')->get();
            $home2_all_data = Home2Section::get();
            foreach($home2_all_data as $item) {
                $home2_item[$item->name] = $item->value;
            }
            $services = Service::orderBy('id','asc')->limit($home2_item['s4_services_how_many'])->get();
            $portfolios = Portfolio::orderBy('id','asc')->limit($home2_item['s6_portfolios_how_many'])->get();
            $testimonials = Testimonial::orderBy('id','asc')->get();
            $services2 = Service::orderBy('id','asc')->limit($home2_item['s8_services_how_many'])->get();
            $faqs = Faq::orderBy('id','asc')->limit($home2_item['s9_faqs_how_many'])->get();
            $posts = Post::orderBy('id','desc')->limit($home2_item['s12_posts_how_many'])->get();
            $clients = Client::orderBy('id','asc')->get();
            return view('front.home-2', compact('sliders', 'home2_item', 'services', 'testimonials', 'portfolios', 'services2', 'faqs', 'posts', 'clients'));
        } 
        elseif(session('current_home') == 'Home Page 3') {
            $sliders = Slider::orderBy('id','asc')->get();
            $home3_all_data = Home3Section::get();
            foreach($home3_all_data as $item) {
                $home3_item[$item->name] = $item->value;
            }
            $services = Service::orderBy('id','asc')->limit($home3_item['s1_services_how_many'])->get();
            $portfolios = Portfolio::orderBy('id','asc')->limit($home3_item['s3_portfolios_how_many'])->get();
            $team_members = TeamMember::orderBy('id','asc')->limit($home3_item['s5_team_members_how_many'])->get();
            $clients = Client::orderBy('id','asc')->get();
            $testimonials = Testimonial::orderBy('id','asc')->get();
            $posts = Post::orderBy('id','desc')->limit($home3_item['s9_posts_how_many'])->get();

            $pricing_plans = DB::table('pricing_plans as t1')
            ->select([
                't1.id as plan_id',
                't1.name as plan_name',
                't1.description',
                't1.price',
                't1.period',
                't1.is_popular',
                't1.button_url',
                't1.button_text',
                DB::raw('GROUP_CONCAT(t2.name) as options')
            ])
            ->leftJoin('pricing_plan_options as t2', 't1.id', '=', 't2.pricing_plan_id')
            ->groupBy(
                't1.id',
                't1.name',
                't1.description',
                't1.price',
                't1.period',
                't1.is_popular',
                't1.button_url',
                't1.button_text'
            )
            ->orderBy('t1.id', 'asc')
            ->get();

            return view('front.home-3', compact('sliders', 'home3_item', 'services', 'portfolios', 'team_members', 'testimonials', 'posts', 'clients', 'pricing_plans'));
        }
    }

    public function home_change()
    {
        if($_POST['layout_url'] == 'home_one') {
            session()->put('current_home', 'Home Page 1');
        } elseif($_POST['layout_url'] == 'home_two') {
            session()->put('current_home', 'Home Page 2');
        } elseif($_POST['layout_url'] == 'home_three') {
            session()->put('current_home', 'Home Page 3');
        }

        return redirect()->route('home');
    }

    public function about()
    {
        $other_page_item = OtherPageItem::where('id',1)->first();
        $services = Service::orderBy('name','asc')->limit($other_page_item->page_about_service_how_many)->get();
        $team_members = TeamMember::orderBy('id','asc')->get();
        $portfolios = Portfolio::orderBy('id','asc')->limit($other_page_item->page_about_portfolio_how_many)->get();
        $clients = Client::orderBy('id','asc')->get();
        return view('front.about', compact('services', 'team_members', 'portfolios', 'clients'));
    }

    public function services()
    {
        $services = Service::orderBy('name','asc')->get();
        return view('front.services', compact('services'));
    }

    public function service($slug)
    {
        $services = Service::orderBy('name','asc')->get();
        $service = Service::where('slug',$slug)->first();
        $service_faqs = ServiceFaq::orderBy('id','asc')->where('service_id',$service->id)->get();
        return view('front.service', compact('services', 'service', 'service_faqs'));
    }

    public function portfolios()
    {
        $portfolios = Portfolio::orderBy('name','asc')->get();
        return view('front.portfolios', compact('portfolios'));
    }

    public function portfolio($slug)
    {
        $portfolios = Portfolio::orderBy('name','asc')->get();
        $portfolio = Portfolio::where('slug',$slug)->first();
        $other_page_item = OtherPageItem::where('id', 1)->first();
        $portfolios_bottom = Portfolio::orderBy('id','asc')->where('slug', '!=', $slug)->limit($other_page_item->page_portfolio_single_bottom_how_many)->get();

        $next = Portfolio::where('id','>',$portfolio->id)->orderBy('id')->first();
        if($next) {
            $next_slug = $next->slug;
        } else {
            $next_slug = '';
        }

        $previous = Portfolio::where('id','<',$portfolio->id)->orderBy('id', 'desc')->first();
        if($previous) {
            $previous_slug = $previous->slug;
        } else {
            $previous_slug = '';
        }

        return view('front.portfolio', compact('portfolios', 'portfolio', 'next_slug', 'previous_slug', 'portfolios_bottom'));
    }

    public function team_members()
    {
        $team_members = TeamMember::orderBy('id','asc')->get();
        return view('front.team_members', compact('team_members'));
    }

    public function team_member($slug)
    {
        $team_member = TeamMember::where('slug',$slug)->first();
        $experiences = TeamMemberExperience::where('team_member_id',$team_member->id)->get();
        return view('front.team_member', compact('team_member', 'experiences'));
    }

    public function team_member_send_message(Request $request)
    {
        if(env('PROJECT_MODE') == 0) {
            return redirect()->back()->with('info', env('PROJECT_NOTIFICATION'));
        }

        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required',
            'subject' => 'required',
            'message' => 'required',
        ], [
            'name.required' => __('Name is required'),
            'email.required' => __('Email is required'),
            'email.email' => __('Email is invalid'),
            'phone.required' => __('Phone is required'),
            'subject.required' => __('Subject is required'),
            'message.required' => __('Message is required'),
        ]);

        $subject = "Team Page Message";
        $message = "<b>Name:</b><br>".strip_tags($request->name)."<br><br>";
        $message .= "<b>Email:</b><br>".strip_tags($request->email)."<br><br>";
        $message .= "<b>Phone:</b><br>".strip_tags($request->phone)."<br><br>";
        $message .= "<b>Subject:</b><br>".strip_tags($request->subject)."<br><br>";
        $message .= "<b>Message:</b><br>".strip_tags($request->message)."<br><br>";

        \Mail::to($request->team_member_email)->send(new Websitemail($subject,$message));

        return redirect()->back()->with('success', __('Message sent successfully'));
    }

    public function testimonials()
    {
        $testimonials = Testimonial::orderBy('id','asc')->get();
        return view('front.testimonials', compact('testimonials'));
    }

    public function faqs()
    {
        $faqs = Faq::orderBy('id','asc')->get();
        return view('front.faqs', compact('faqs'));
    }

    public function page($slug)
    {
        $custom_page = CustomPage::where('slug',$slug)->first();
        return view('front.custom_page', compact('custom_page'));
    }

    public function blog()
    {
        $posts = Post::orderBy('id','desc')->paginate(15);
        return view('front.blog', compact('posts'));
    }

    public function post($slug)
    {
        $latest_posts = Post::orderBy('id','desc')->take(5)->get();
        $post = Post::where('slug',$slug)->first();
        if($post == null) {
            return redirect()->route('home');
        }
        $post_categories = PostCategory::orderBy('name', 'asc')->get();
        if($post->tags!='') {
            $post_tags = explode(',', $post->tags);
        } else {
            $post_tags = [];
        }
        $tags = Post::pluck('tags')->flatMap(function ($item) {
            return explode(',', $item);
        })->unique()->values();
        return view('front.post', compact('latest_posts', 'post', 'post_categories', 'tags', 'post_tags'));
    }

    public function category($slug)
    {
        $post_category = PostCategory::where('slug', $slug)->first();
        $posts = Post::where('post_category_id', $post_category->id)->paginate(15);
        return view('front.category', compact('posts', 'post_category'));
    }

    public function tag($name)
    {
        $posts = Post::whereRaw("FIND_IN_SET(?, tags)", [$name])->paginate(15);
        $tag_name = $name;
        return view('front.tag', compact('posts', 'tag_name'));
    }

    public function search(Request $request)
    {
        $search_text = strip_tags($request->search_text);

        $posts = Post::where('title', 'like', '%' . $search_text . '%')
                ->orWhere('description', 'like', '%' . $search_text . '%')
                ->paginate(15);
        $search_by = $search_text;
        return view('front.search', compact('posts', 'search_by'));
    }

    public function pricing_plans()
    {
        $pricing_plans = DB::table('pricing_plans as t1')
            ->select([
                't1.id as plan_id',
                't1.name as plan_name',
                't1.description',
                't1.price',
                't1.period',
                't1.is_popular',
                't1.button_url',
                't1.button_text',
                DB::raw('GROUP_CONCAT(t2.name) as options')
            ])
            ->leftJoin('pricing_plan_options as t2', 't1.id', '=', 't2.pricing_plan_id')
            ->groupBy(
                't1.id',
                't1.name',
                't1.description',
                't1.price',
                't1.period',
                't1.is_popular',
                't1.button_url',
                't1.button_text'
            )
            ->orderBy('t1.id', 'asc')
            ->get();

        return view('front.pricing_plans', compact('pricing_plans'));
    }

    // public function pricing_plans()
    // {
    //     $pricing_plans = DB::table('pricing_plans as t1')
    //         ->select([
    //             't1.id as plan_id',
    //             't1.name as plan_name',
    //             't1.description',
    //             't1.price',
    //             't1.period',
    //             't1.is_popular',
    //             't1.button_url',
    //             't1.button_text',
    //             DB::raw('GROUP_CONCAT(t2.name) as options')
    //         ])
    //         ->leftJoin('pricing_plan_options as t2', 't1.id', '=', 't2.pricing_plan_id')
    //         ->groupBy('t1.id')
    //         ->orderBy('t1.id', 'asc')
    //         ->get();

    //     return view('front.pricing_plans', compact('pricing_plans'));
    // }

    public function contact()
    {
        return view('front.contact');
    }

    public function contact_send_message(Request $request)
    {
        if(env('PROJECT_MODE') == 0) {
            return redirect()->back()->with('info', env('PROJECT_NOTIFICATION'));
        }

        $admin_data = Admin::where('id',1)->first();
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required',
            'subject' => 'required',
            'message' => 'required',
        ], [
            'name.required' => __('Name is required'),
            'email.required' => __('Email is required'),
            'email.email' => __('Email is invalid'),
            'phone.required' => __('Phone is required'),
            'subject.required' => __('Subject is required'),
            'message.required' => __('Message is required'),
        ]);

        $subject = "Contact Page Message";
        $message = "<b>Name:</b><br>".strip_tags($request->name)."<br><br>";
        $message .= "<b>Email:</b><br>".strip_tags($request->email)."<br><br>";
        $message .= "<b>Phone:</b><br>".strip_tags($request->phone)."<br><br>";
        $message .= "<b>Subject:</b><br>".strip_tags($request->subject)."<br><br>";
        $message .= "<b>Message:</b><br>".strip_tags($request->message)."<br><br>";

        \Mail::to($admin_data->email)->send(new Websitemail($subject,$message));

        return redirect()->back()->with('success', __('Message sent successfully'));
    }

    public function subscriber_submit(Request $request)
    {
        if(env('PROJECT_MODE') == 0) {
            return redirect()->back()->with('info', env('PROJECT_NOTIFICATION'));
        }
        
        $request->validate([
            'email' => 'required|email|unique:subscribers'
        ], [
            'email.required' => __('Email is required'),
            'email.email' => __('Email is invalid'),
            'email.unique' => __('Email already exists')
        ]);

        $subscriber = new Subscriber();
        $subscriber->email = strip_tags($request->email);
        $subscriber->token = hash('sha256',time());
        $subscriber->status = 0;
        $subscriber->save();

        $subject = "Subscriber Verification";
        $message = "Please verify your email address by clicking on the following link:<br><br>";
        $message .= "<a href='".route('subscriber_verify',[$request->email,$subscriber->token])."'>".route('subscriber_verify',[$request->email,$subscriber->token])."</a><br><br>";

        \Mail::to($request->email)->send(new Websitemail($subject,$message));

        return redirect()->back()->with('success', __('Your request has been received. Please check your email to verify'));
    }

    public function subscriber_verify($email,$token)
    {
        $subscriber = Subscriber::where('email',$email)->where('token',$token)->first();
        if($subscriber)
        {
            $subscriber->status = 1;
            $subscriber->token = '';
            $subscriber->save();
            
            return redirect()->route('home')->with('success', __('You are successfully verified as a subscriber'));
        }
        else
        {
            return redirect()->route('home')->with('error', __('Invalid email or token'));
        }
    }

    public function terms()
    {
        return view('front.terms');
    }

    public function privacy()
    {
        return view('front.privacy');
    }

    public function language_switch(Request $request)
    {
        $language = Language::where('code',$request->code)->first();
        if($language) {
            session(['sess_lang_name' => $language->name]);
            session(['sess_lang_code' => $language->code]);
            session(['sess_lang_direction' => $language->direction]);
        }
        return redirect()->back();
    }
}
