<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\Admin;
use App\Models\Degree;
use App\Models\Department;
use App\Models\Award;
use App\Models\Order;
use App\Models\Blog;
use App\Models\Experience;
use App\Models\Setting;
use App\Models\Gallery;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\File;
use App\Mail\sendmail;
use Carbon\Carbon;
use Browser;
use Session;
use Image;
use Redirect;

class UserController extends Controller
{
    public function dashboard() {
        $data['set'] = Setting::first();
        $user = User::whereid(Auth::guard('user')->user()->id)->first();
        $data['user'] = $user;
        $data['award'] = Award::whereuser_id($user->id)->orderBy('id', 'DESC')->get();
        $data['experience'] = Experience::orderBy('id', 'DESC')->count();
        $data['degree'] = Degree::orderBy('id', 'DESC')->get();
        $data['orders'] = Order::whereuser_id($user->id)->orderBy('id', 'DESC')->get();
            
        return view('/doctor/dashboard', $data);
    }

    public function profile(Request $request) {
        
    }
    //Update Profile Picture
    public function updateprofile(Request $request) {
        $data['set'] = Setting::first();
        $ch = User::whereid(Auth::guard('user')->user()->id)->count();
        if($ch>0) {
        $tr =  User::whereid(Auth::guard('user')->user()->id)->first();
        
        if ($request->hasFile('image')) {
            if($request->file('image')->getClientOriginalExtension() == 'jpg' || $request->file('image')->getClientOriginalExtension() == 'png' || $request->file('image')->getClientOriginalExtension() == 'jpeg') {
            $image = $request->file('image');
            $filename = time() . '_profile.png';
            $location = 'images/user/' . $filename;
            $image->move('images/user', $filename);
            $tr->image = $location;
            }
        }
        $tr->save();

        return back()->with('success', 'Profile Picture updated successfully');
        }
        else {
            return back()->with('alert', 'Invalid User');
        }
    }

    public function delbanner($id) {
        $data['set'] = Setting::first();
        $ch = Banner::whereid($id)->count();
        if($ch>0) {
            $tr =  Banner::whereid($id)->delete();
            return back()->with('success', 'Banner deleted successfully');
        }
        else {
            return back()->with('alert', 'Invalid Banner');
        }
        
    }

    //Banners
    public function blog() {
        $data['set'] = Setting::first();
        $admin = Admin::whereid(Auth::guard('admin')->user()->id)->first();
        $data['admin'] = $admin;
        $data['blog'] = Blog::orderBy('id', 'DESC')->get();
        return view('/admin/blog', $data);   
    }

    public function addblog(Request $request) {
        $data['set'] = Setting::first();
        $ch = Blog::wheretitle($request->title)->count();
        if($ch<1) {
        $tr = new Blog();
        $tr->title = $request->title;
        $tr->url = str_replace(' ', '_', $request->title);
        $tr->content = $request->content;
        if ($request->hasFile('image')) {
            if($request->file('image')->getClientOriginalExtension() == 'jpg' || $request->file('image')->getClientOriginalExtension() == 'png' || $request->file('image')->getClientOriginalExtension() == 'jpeg') {
            $image = $request->file('image');
            $filename = time() . '_blog.png';
            $location = 'images/blog/' . $filename;
            $image->move('images/blog', $filename);
            $tr->image = $location;
            }
        }
        $tr->code = Str::random(6);
        $tr->save();

        return back()->with('success', 'Blog Post created successfully');
        }
        else {
            return back()->with('alert', 'Post title exists');
        }
    }

    public function updateblog(Request $request) {
        $data['set'] = Setting::first();
        $ch = Blog::whereid($request->sid)->count();
        if($ch>0) {
        $tr =  Blog::whereid($request->sid)->first();
        $tr->title = $request->title;
        $tr->url = str_replace(' ', '_', $request->title);
        $tr->content = $request->content;
        if ($request->hasFile('image')) {
            if($request->file('image')->getClientOriginalExtension() == 'jpg' || $request->file('image')->getClientOriginalExtension() == 'png' || $request->file('image')->getClientOriginalExtension() == 'jpeg') {
            $image = $request->file('image');
            $filename = time() . '_blog.png';
            $location = 'images/blog/' . $filename;
            $image->move('images/blog', $filename);
            $tr->image = $location;
            }
        }
        $tr->save();

        return back()->with('success', 'Blog Post updated successfully');
        }
        else {
            return back()->with('alert', 'Invalid Post');
        }
    }

    public function delblog($id) {
        $data['set'] = Setting::first();
        $ch = Blog::whereid($id)->count();
        if($ch>0) {
            $tr =  Blog::whereid($id)->delete();
            return back()->with('success', 'Blog Post deleted successfully');
        }
        else {
            return back()->with('alert', 'Invalid Post');
        }
        
    }


    //Products
    public function products() {
        $data['set'] = Setting::first();
        $user = User::whereid(Auth::guard('user')->user()->id)->first();
        $data['user'] = $user;
        $data['products'] = Product::whereuser_id($user->id)->orderBy('id', 'DESC')->get();
        $data['cat'] = Category::orderBy('id', 'DESC')->get();
        $data['location'] = Location::orderBy('id', 'DESC')->get();
        return view('/user/products', $data);   
    }

    public function addproducts(Request $request) {
        $data['set'] = Setting::first();
        $user = User::whereid(Auth::guard('user')->user()->id)->first();
        $ch = Product::wherename($request->name)->count();
        if($ch<1) {
        $tr = new Product();
        $tr->user_id = $user->id;
        $tr->name = $request->name;
        $tr->url = str_replace(" ", "-", $request->name);
        $tr->category = $request->category;
        $tr->location = $request->location;
        $tr->price = $request->price;
        $tr->max = $request->quantity;
        //$tr->featured = $request->featured;
        $tr->description = $request->description;
        $tr->amenities = $request->amenities;
        $tr->url = str_replace(" ", "_", $request->name);
        if ($request->hasFile('image')) {
            if($request->file('image')->getClientOriginalExtension() == 'jpg' || $request->file('image')->getClientOriginalExtension() == 'png') {
            $image = $request->file('image');
            $filename = time() . '_product.png';
            $location = 'images/product/' . $filename;
            $image->move('images/product', $filename);
            $tr->image = $location;
            }
        }
        $tr->code = Str::random(6);
        $tr->save();

        return back()->with('success', 'New Space added successfully');
        }
        else {
            return back()->with('alert', 'Space name exists');
        }
    }

    public function updateproducts(Request $request) {
        $data['set'] = Setting::first();
        $ch = Product::whereid($request->sid)->count();
        if($ch>0) {
        $tr =  Product::whereid($request->sid)->first();
        $tr->name = $request->name;
        $tr->url = str_replace(" ", "-", $request->name);
        $tr->category = $request->category;
        $tr->location = $request->location;
        $tr->price = $request->price;
        $tr->max = $request->quantity;
        //$tr->featured = $request->featured;
        $tr->description = $request->description;
        $tr->amenities = $request->amenities;
        if ($request->hasFile('image')) {
            if($request->file('image')->getClientOriginalExtension() == 'jpg' || $request->file('image')->getClientOriginalExtension() == 'png') {
            $image = $request->file('image');
            $filename = time() . '_product.png';
            $location = 'images/product/' . $filename;
            $image->move('images/product', $filename);
            $tr->image = $location;
            }
        }
        $tr->save();

        return back()->with('success', 'Space updated successfully');
        }
        else {
            return back()->with('alert', 'Invalid Space Listing');
        }
    }

    public function delproducts($id) {
        $data['set'] = Setting::first();
        $ch = Product::whereid($id)->count();
        if($ch>0) {
            $tr =  Product::whereid($id)->delete();
            return back()->with('success', 'Space deleted successfully');
        }
        else {
            return back()->with('alert', 'Invalid Space Record');
        }
        
    }
    
    public function settings() {
        $data['set'] = Setting::first();
        $admin = Admin::whereid(Auth::guard('admin')->user()->id)->first();
        $data['admin'] = $admin;
        $data['site'] = Setting::all();
        
        return view('/admin/settings', $data);   
    }
    public function gallery() {
        $data['set'] = Setting::first();
        $user = User::whereid(Auth::guard('user')->user()->id)->first();
        $data['user'] = $user;
        $data['gal'] = Gallery::whereuser_id($user->id)->orderBy('id', 'DESC')->get();
        $data['pro'] = Product::orderBy('id', 'DESC')->get();
        return view('/user/gallery', $data);   
    }

    public function addgallery(Request $request) {
        $data['set'] = Setting::first();
        $user = User::whereid(Auth::guard('user')->user()->id)->first();
        $tr = new Gallery();
        $tr->user_id = $user->id;
        $tr->product = $request->product;
        if ($request->hasFile('image')) {
            if($request->file('image')->getClientOriginalExtension() == 'jpg' || $request->file('image')->getClientOriginalExtension() == 'png') {
            $image = $request->file('image');
            $filename = time() . '_product.png';
            $location = 'images/product/' . $filename;
            $image->move('images/product', $filename);
            $tr->image = $location;
            }
        }
        $tr->code = Str::random(6);
        $tr->save();

        return back()->with('success', 'Gallery for space added successfully');
        
    }

    public function updategallery(Request $request) {
        $data['set'] = Setting::first();
        $ch = Gallery::whereid($request->sid)->count();
        if($ch>0) {
        $tr =  Gallery::whereid($request->sid)->first();
        $tr->product = $request->product;
        if ($request->hasFile('image')) {
            if($request->file('image')->getClientOriginalExtension() == 'jpg' || $request->file('image')->getClientOriginalExtension() == 'png') {
            $image = $request->file('image');
            $filename = time() . '_product.png';
            $location = 'images/product/' . $filename;
            $image->move('images/product', $filename);
            $tr->image = $location;
            }
        }
        $tr->save();

        return back()->with('success', 'Gallery updated successfully');
        }
        else {
            return back()->with('alert', 'Invalid Gallery Image');
        }
    }

    public function delgallery($id) {
        $data['set'] = Setting::first();
        $ch = Gallery::whereid($id)->count();
        if($ch>0) {
            $tr =  Gallery::whereid($id)->delete();
            return back()->with('success', 'Gallery deleted successfully');
        }
        else {
            return back()->with('alert', 'Invalid Gallery');
        }
        
    }

    public function ordernow(Request $request) {
        $data['set'] = Setting::first();
        //$ch = User::whereid(Auth::guard('user')->user()->id)->count();
        if(!Auth::check()) {
            return back()->with('alert', 'You need to login first');
            
        }
        else {
            $user = User::whereid(Auth::guard('user')->user()->id)->first();
            $product = Product::whereid($request->product)->first();
             $tr = new Order();
                $tr->user_id = $user->id;
                $tr->product = $request->product;
                $tr->intention = $request->intention;
                $tr->date = $request->date;
                $tr->start_time = $request->start;
                $tr->end_time = $request->end;
                $tr->guests = $request->guests;
                $tr->amount = $product->price;
                $tr->payment = 0;
                $tr->status = 0;
                $tr->save();
                
                $ttot = $product->price;
                
            
            $url = "https://api.paystack.co/transaction/initialize";
                        
                            $fields = [
                            'email' => $user->email,
                            'amount' => $ttot ."00",
                            'callback_url' => "https://mom.com.ng/eatrite/confirmpay",
                            'channels' => ["card", "bank", "ussd", "bank_transfer"],
                            ];
                        
                            $fields_string = http_build_query($fields);
                        
                            //open connection
                            $ch = curl_init();
                            
                            //set the url, number of POST vars, POST data
                            curl_setopt($ch,CURLOPT_URL, $url);
                            curl_setopt($ch,CURLOPT_POST, true);
                            curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                            "Authorization: Bearer sk_live_ee2a89605a7d763ba8a0200695fe501beb3019ab",
                            "Cache-Control: no-cache",
                            ));
                            
                            //So that curl_exec returns the contents of the cURL; rather than echoing it
                            curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
                            
                            
                                
                        
                            $response = curl_exec($ch);
                        
                            
                        
                            curl_close($ch);
                        
                            $res = json_decode($response, true);
                            //var_dump($response);
                            // Redirect to payment validation
                            if ($res['status'] == 'true') {
                                 $tr->trx_id = $res['data']['reference'];
                                $tr->save();
                                
                                $link = $res['data']['authorization_url'];
                                return redirect()->away($link);
                            }
                            else{
                        
                                return back()->with('alert', 'Unable to process payment');
                            }
 
                    

        }
    }

    public function confirmpay(Request $request) {
        $data['set'] = Setting::first();
        // $ch = request()->status;
        // if($ch == 'cancelled') {
        //     return back()->with('alert', 'Payment Cancelled');
        // }
        // elseif($ch == 'successful') {
             $trxid = request()->reference;

                $curl = curl_init();
                
                curl_setopt_array($curl, array(
                    CURLOPT_URL => "https://api.paystack.co/transaction/verify/".$trxid,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => "GET",
                    CURLOPT_HTTPHEADER => array(
                    "Authorization: Bearer sk_live_ee2a89605a7d763ba8a0200695fe501beb3019ab",
                    "Cache-Control: no-cache",
                    ),
                ));
  

			$response = curl_exec($curl);

			curl_close($curl);

			// echo  '<pre>';
			// echo $response;
			// echo '</pre>';

			$res = json_decode($response, true);
            //var_dump($response);
            // Confirm status is 'success'
			if ($res['status'] == 'true') {
                $cf = Order::wheretrx_id($trxid)->count();
                if($cf <1) {
                    return redirect()->intended('/login')->with('alert', 'Unable to find transaction');
                }
                else {
                    $tr = Order::wheretrx_id($trxid)->get();
                    foreach($tr as $tp) {
                        $tp->payment = 1;
                        $tp->save();
                    }
                    
                    return redirect()->route('user/dashboard')->with('success', 'Space was booked successfully');
                    
                    
                }
            }
            else {
                return redirect()->intended('/login')->with('alert', 'Payment count not be verified');
                
            }
        }
   

    public function updatesite(Request $request) {
        $data['set'] = Setting::first();
        $ch = Setting::whereid($request->sid)->count();
        if($ch>0) {
        
            $user = Setting::first();
            $user->name = $request->name;
            $user->phone = $request->phone;
            $user->email = $request->email;
            $user->address = $request->address;
            if ($request->hasFile('image')) {
            if($request->file('image')->getClientOriginalExtension() == 'jpg' || $request->file('image')->getClientOriginalExtension() == 'png' || $request->file('image')->getClientOriginalExtension() == 'gif' || $request->file('image')->getClientOriginalExtension() == 'webp') {
            $image = $request->file('image');
            $filename = time() . '_site.png';
            $location = 'images/profile/' . $filename;
            $image->move('images/profile', $filename);
            $user->image = $location;
            }
            }
            if ($request->hasFile('fav')) {
                if($request->file('fav')->getClientOriginalExtension() == 'jpg' || $request->file('fav')->getClientOriginalExtension() == 'png') {
                $image = $request->file('image');
                $filename = time() . 'fav.png';
                $location = 'images/profile/' . $filename;
                $image->move('images/profile', $filename);
                $user->fav = $location;
                }
                }
            $user->save();

        return back()->with('success', 'Site Settings updated successfully');
        }
        else {
            $user = new Setting();
            $user->name = $request->name;
            $user->phone = $request->phone;
            $user->email = $request->email;
            $user->address = $request->address;
            if ($request->hasFile('image')) {
            if($request->file('image')->getClientOriginalExtension() == 'jpg' || $request->file('image')->getClientOriginalExtension() == 'png' || $request->file('image')->getClientOriginalExtension() == 'gif' || $request->file('image')->getClientOriginalExtension() == 'webp') {
            $image = $request->file('image');
            $filename = time() . '_site.png';
            $location = 'images/profile/' . $filename;
            $image->move('images/profile', $filename);
            $user->image = $location;
            }
            }
            if ($request->hasFile('fav')) {
                if($request->file('fav')->getClientOriginalExtension() == 'jpg' || $request->file('fav')->getClientOriginalExtension() == 'png') {
                $image = $request->file('image');
                $filename = time() . 'fav.png';
                $location = 'images/profile/' . $filename;
                $image->move('images/profile', $filename);
                $user->fav = $location;
                }
                }
            $user->save();

        }
    }
    
    public function users() {
        $data['set'] = Setting::first();
        $admin = Admin::whereid(Auth::guard('admin')->user()->id)->first();
        $data['admin'] = $admin;
        $data['users'] = User::orderBy('id', 'DESC')->get();
        $data['userss'] = User::orderBy('id', 'DESC')->count();
        return view('/admin/users', $data);   
    }

    public function orders() {
        $data['set'] = Setting::first();
        $admin = Admin::whereid(Auth::guard('admin')->user()->id)->first();
        $data['admin'] = $admin;
        $data['users'] = User::orderBy('id', 'DESC')->get();
        $data['trx'] = Order::orderBy('id', 'DESC')->get();
        $data['trxx'] = Order::orderBy('id', 'DESC')->count();
        return view('/admin/orders', $data);   
    }

    public function logout() {
        Auth::guard('user')->logout();
        
        return redirect()->intended('login');
    }
}
