<?php

namespace App\Http\Controllers;

use App\Http\Controllers\PaypalExpress;
use App\Models\Article;
use App\Models\BundleOffer;
use App\Models\Orders;
use App\Models\Country;
use App\Models\UserAccess\UserAccess;
use App\Rules\Captcha;
use App\User;
use Auth;
use File;
use Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Mpdf\Mpdf;
use View;

class HomeController extends BenthamController
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (session()->has('referral_base_access')) {
            return Redirect::to('/');
        }
        $used_token            = array();
        $available_token       = array();
        $SearchToken           = array();
        $access_user_data      = array();
        $bundle_order          = array();
        $rental_order          = array();
        $used_token_array      = array();
        $available_token_array = array();
        $user_consortia_counter = array();
        $used_token_count      = 0;
        $available_token_count = 0;

        if ($request->ajx_search == true) {
            $param['bundle_offer_order_id'] = $request->get('bundle_offer_order_id');
            $bundle_content                 = BundleOffer::GetBundleOfferOrderContent($param);
            if (count($bundle_content) > 0) {
                return response()->json($bundle_content, 200);
            } else {
                return response()->json(false, 200);
            }
        }

        if (!Auth::check()) {
            return redirect("/");
        }
        $user = User::getUserInfo();
        $pages  = '';
        $orders = '';

        foreach ($user->role as $roles) {
            if ($roles->slug != "user") {
                if($request->pages != "editprofile")
                {
                    return redirect('/admin/dashboard');
                }
            }
        }
        $pages = $request->pages;

        // Token Report
        if (Auth::check()) {
            //$user_base_access_data  = $request->session()->get('access_user_data');
            $user_base_access_data = UserAccess::where('user_id', $user->id)->where('user_access_status', 1)->get();

            $token_type = array(444, 555, 666);
            if (!empty($user_base_access_data)) {
                foreach ($user_base_access_data as $k => $v) {
                    if ($v->user_id == $user->id) {
                        if (in_array($v->access_type_id, $token_type)) {
                            $access_user_data        = $user_base_access_data[$k];
                            $access_type_id          = $access_user_data->access_type_id;
                            $param['user_access_id'] = $access_user_data->user_access_id;
                            $param['access_on']      = $access_user_data->access_type_on;
                            if ($param['access_on'] == 'journal_volume' || $param['access_on'] == 'issue' || $param['access_on'] == 'article') {
                                $join['journal']      = true;
                                $join['volume']       = true;
                                $join['issue']        = true;
                                $join['article']      = true;
                                $join['ebook_volume'] = false;
                                $join['chapter']      = false;
                            }

                            if ($param['access_on'] == 'ebook_volume') {
                                $join['journal']      = false;
                                $join['volume']       = false;
                                $join['issue']        = false;
                                $join['article']      = false;
                                $join['ebook_volume'] = true;
                                $join['chapter']      = false;
                            }

                            if ($param['access_on'] == 'chapter') {
                                $join['journal']      = false;
                                $join['volume']       = false;
                                $join['issue']        = false;
                                $join['article']      = false;
                                $join['ebook_volume'] = true;
                                $join['chapter']      = true;
                            }

                            $used_token[] = UserAccess::GetAccessUsedTokenList($param, $join);
                            
							if($access_type_id == 555)
                            {
                                $param['download_count'] = 0;
                            }

                            $available_token[] = UserAccess::GetAccessTokenList($param);

                        }
                    }
                }
            }
        }
        if (!empty($access_user_data)) {
            $access_type_id          = $access_user_data->access_type_id;
            $param['user_access_id'] = $access_user_data->user_access_id;
            $param['access_on']      = $access_user_data->access_type_on;

            if (!empty($used_token)) {
                for ($k = 0; $k < count($used_token); $k++) {
                    $used_token_array = $used_token[$k]->merge($used_token_array);
                }
            }
            if (!empty($available_token)) {
                for ($k = 0; $k < count($available_token); $k++) {
                    $available_token_array = $available_token[$k]->merge($available_token_array);
                }
            }

            // dd($available_token_array);

            // All Tokens (Available and Used)
            $used_token      = $used_token_array;
            $available_token = $available_token_array;

            $used_token_count = $used_token->count();

            if (!empty($available_token_array)) {
                $av_count = 0;
                foreach ($available_token_array as $av_val) {
                    $av_count = $av_count + $av_val->download_count;
                }
            }
            // dd($av_count);

            //$available_token_count = $av_count - $used_token_count;

            $available_token_count = $user_base_access_data[0]->restricted_download_limit - $used_token_count;

            if ($access_type_id == 555) {
                $param['download_count'] = 0;
            }
            //$available_token = UserAccess::GetAccessTokenList($param);
            //$available_token = $available_token_array;

            if ($request->search == 'SearchToken') {
                return $this->SearchToken($request, $access_user_data);
            }
        }

        if ($pages == 'exporttokenlist') {
            return $this->ExportTokenList($request, $used_token, $available_token);
        }

        if ($pages == 'invoice') {
            $request->customer_email = $user->email;
            $request->order_status   = 'completed';
            $orders                  = Orders::GetOrderList($request, 100);
        }
        if ($pages == 'exportinvoice') {
            $details = $this->GetOrderDetails($request);

            /* $email_template='email_template.testing';
            $view_data['temp']='Arshad';
            $to='arshad@xolva.com';
            $from='admin@xolva.com';
            $subject='Testing Email';
            SendSmtpMail($email_template,$view_data, $to, $from, $subject);*/

            $mpdf = new Mpdf(['mode' => 'utf-8', 'format' => 'A4', 'margin_left' => '5', 'margin_right' => '5']);

            $html = View::make('admin.orders.template.invoice')
                ->with('order', $details['order'])
                ->with('user', $details['user'])
                ->with('payments', $details['payments'])
                ->with('balance', $details['balance'])
                ->with('products', $details['products'])
                ->with('comments', $details['comments'])
                ->with('admin_comments', $details['admin_comments'])
                ->with('order_logs', $details['order_logs'])
                ->with('ord_status', $details['ord_status']);
            $mpdf->WriteHTML($html, 2);
            $mpdf->Output($details['order']->order_id . '-order.pdf', 'D');
            exit();
        }
        $countries = $this->countries;
        //dd($user->user_id);
        //---------------------Bundle Order------------------------
        $sparam['user_id']             = $user->id;
        $sparam['order_status']        = 'C';
        $sparam['bundle_order_status'] = 'C';
        $sparam['bundle_offer_expiry'] = time();
        $sparam['paginate']            = true;
        $bundle_order                  = "";
        $bundle_content                = "";

        $bundle_order = BundleOffer::GetBundleOfferOrderDetail($sparam);

        if (count($bundle_order) > 0) {
            $a = 0;
            foreach ($bundle_order as $bo) {
                $bundle_count                       = "";
                $bundle['bundle_offer_order_id']    = $bo->bundle_offer_order_id;
                $bundle_count                       = BundleOffer::GetBundleOfferContentCount($bundle);
                $bundle_order->items()[$a]->article = $bundle_count[0]->article;
                $bundle_order->items()[$a]->chapter = $bundle_count[0]->chapter;
                $bundle_order->items()[$a]->ebook   = $bundle_count[0]->ebook;

                $a++;
            }
        }
        //-----------------------Bundle Order-------------------------
        $sparam['paginate'] = true;
        $rental_order       = Article::GetArticleRentalDetail($sparam);
        if (!empty($user->counter_report_year)) {
            $year_arr = explode(',', $user->counter_report_year);
            foreach ($year_arr as $yy) {
                $counteruseryears[$yy] = $yy;
            }

        } else {
            $counteruseryears = array(date('Y') => date('Y'));
        }

        // -----------------------Consortia User----------------//
        $cparam['agent_id'] = $user->id;
        $cparam['paginate'] = true;
        $user_consortia_counter = User::getUserConsoriaById($cparam);

        if($pages == "usagereport" && isset($request->id))
        {
            $user = User::where('id', $request->id)->first();
        }

        return view('home', with(['user' => $user,
            'countries'                      => $countries,
            'pages'                          => $pages,
            'orders'                         => $orders,
            'used_token'                     => $used_token,
            'used_token_count'               => $used_token_count,
            'available_token'                => $available_token,
            'available_token_count'          => $available_token_count,
            'SearchToken'                    => $SearchToken,
            'access_user_data'               => $access_user_data,
            'bundle_order'                   => $bundle_order,
            'bundle_content'                 => $bundle_content,
            'user_consortia_counter'         => $user_consortia_counter,
            'rental_order'                   => $rental_order,
            'counteruseryears'               => $counteruseryears]));
    }

    public function GetOrderDetails($request)
    {
        $balance      = 0;
        $paid_amounts = 0;
        $order        = Orders::GetOrder($request->id);
        $user         = User::getUserById($order->uid);
        $products     = Orders::GetOrderProducts($request->id);
        $payments     = Orders::GetOrderPaymentReceipts($request->id);
        if ($payments) {
            foreach ($payments as $paid) {
                $paid_amounts = $paid_amounts + $paid->amount;
            }
            $balance = $order->order_total - $paid_amounts;
        }
        $comments       = Orders::GetOrderComments($request->id);
        $admin_comments = Orders::GetOrderAdminComments($request->id);
        $order_logs     = Orders::GetOrderLogs($request->id);
        $ord_status     = Orders::GetOrderStatus();

        return with(['order' => $order,
            'user'               => $user,
            'payments'           => $payments,
            'balance'            => $balance,
            'products'           => $products,
            'comments'           => $comments,
            'admin_comments'     => $admin_comments,
            'order_logs'         => $order_logs,
            'ord_status'         => $ord_status]);
    }

    public function UpdateProfile(User $user, Request $request)
    {
        if ($request->password == null) {
            $validator = Validator::make($request->all(),
                [
                    'display_name' => 'required',
                    'first_name'   => 'required',
                    'last_name'    => 'required',
                ]
            );

        } else {
            $validator = Validator::make($request->all(),
                [
                    'display_name'     => 'required',
                    'first_name'       => 'required',
                    'last_name'        => 'required',
                    'password'         => 'required_with:password_confirm|same:password_confirm|min:6',
                    'password_confirm' => 'min:6',
                ]);

        }

        if ($validator->fails()) {
            return back()->withInput()->withErrors($validator);
        } else {
            try {

                $user_id                    = decrypt($request->utm);
                $update_obj['display_name'] = $request->display_name;
                $update_obj['first_name']   = $request->first_name;
                $update_obj['last_name']    = $request->last_name;
                $update_obj['dob']          = $request->dob;
                $update_obj['bio']          = $request->bio;
                $update_obj['gender']       = $request->gender;
                $update_obj['country']      = $request->country;
                $update_obj['state']        = $request->state;
                $update_obj['city']         = $request->city;
                $update_obj['address']      = $request->address;
                $update_obj['postal']       = $request->postal;
                $update_obj['updated_at']   = time();

                $user  = User::getUserById($user_id);

                if($user->change_password == 1)
                {
                    if (!empty($request->password)) {
                        $password               = Hash::make($request->password);
                        $update_obj['password'] = $password;
                    }
                }

                // is new image uploaded?
                if ($file = $request->file('pic_file')) {
                    $extension = $file->extension() ?: 'png';
                    //$destinationPath = public_path() . '/uploads/users/';
                    $destinationPath = 'uploads/users/';
                    $safeName        = str_random(10) . '.' . $extension;
                    $file->move($destinationPath, $safeName);
                    //delete old pic if exists
                    if (File::exists($destinationPath . $user->pic)) {
                        File::delete($destinationPath . $user->pic);
                    }
                    //save new file path into db
                    $update_obj['pic'] = $safeName;
                }
                User::where('id', $user_id)->update($update_obj);
                //save record

                // Was the user updated?
                if ($update_obj) {
                    // Redirect to the user pages
                    return redirect('home')->with('success', "User was successfully updated.");
                }

                // Prepare the error message
                $error = "There was an issue updating the user. Please try again.";
            } catch (UserNotFoundException $e) {
                // Prepare the error message
                $error = "User does not exist.";

                // Redirect to the user management page
                return redirect('home#profileedit')->withInput()->with('error', $error);
            }

            // Redirect to the user page
            return redirect('home#profileedit')->withInput()->with('error', $error);

        }
    }

    public function AdminDashboard(Request $request)
    {
        //dd($request->route()->getPrefix());
        return view('admin.dashboard');
    }

    public function ShowUserLogin($value = '')
    {
        return view('login');
    }

    public function ShowAdminLogin()
    {
        if (Auth::user()) {
            return redirect('/admin/dashboard');
        }
        return view('admin.login');
    }

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function refreshCaptcha()
    {
        return response()->json(['captcha' => captcha_img()]);
    }
    //Get content id, read pdf param, access type id, content type (article/chapter)
    public function Terms(Request $request)
    {
        return view('terms.termandcondition', with(['content_id' => $request->content_id, 'param' => $request->param, 'content' => $request->content, 'file_type' => $request->file_type]));
    }

    public function TermsTrial(Request $request)
    {
        return view('terms.termandcondition_trial', with(['access_type' => $request->access_type, 'content_id' => $request->content_id, 'param' => $request->param, 'content' => $request->content, 'file_type' => $request->file_type]));
    }

    public function FeedBack(Request $request)
    {
        if ($request->submit_feedback) {
            $validator = Validator::make($request->all(),
                [
                    'name'                 => 'required',
                    'email'                => 'required|string|email|max:255',
                    'g-recaptcha-response' => new Captcha(),
                ], ['captcha.captcha' => 'Invalid captcha code.']);

            if ($validator->fails()) {
                $detail['name']          = '';
                $detail['email']         = '';
                $detail['site_comment']  = '';
                $detail['other_comment'] = '';
                return view('feedback', with(['detail' => $detail]))->withErrors($validator);
            } else {
                //$to = "feedback@benthamscience.org";
                $to      = 'imrankhan@xolva.com';
                $cc      = env('email_xolva_2') . ',' . env('email_support_2');
                $from    = $request->email;
                $subject = "Eurekaselect: Feedback - (".$request->ip().")";
				
                $detail['name']          = $request->name;
                $detail['email']         = $request->email;
                $detail['site_comment']  = $request->site_comment;
                $detail['other_comment'] = $request->other_comment;
                //$detail['ip']            = $request->ip();
				
                //SendSmtpMail('email_template.feedback', $detail, $to, $from, $subject, $request->name, $cc);
                $message = true;
                return view('feedback', with(['detail' => $detail, 'message' => $message]));
            }

        } else {
            $detail['name']          = '';
            $detail['email']         = '';
            $detail['site_comment']  = '';
            $detail['other_comment'] = '';
        }
        return view('feedback', with(['detail' => $detail]));
    }

    public function CrossMark()
    {
        return view('crossmark');
    }

    public function SearchToken($request, $access_user_data)
    {

        $user_name = $request->user_name;
        $user_id   = session()->get('user_id');

        $user_access_id    = $access_user_data->user_access_id;
        $access_type_id    = $access_user_data->access_type_id;
        $access_type       = $access_user_data->access_type_on;
        $token_access_data = array();

        if (!empty($user_name) && !empty($user_id)) {
            $param['user_id']           = $user_id;
            $param['user_name']         = $user_name;
            $param['user_access_id']    = $user_access_id;
            $param['access_on']         = $access_type;
            $join['token_access_usage'] = true;
            $usage_token_list           = UserAccess::GetAccessTokenList($param, $join);
            $available_flag             = 0;
            $token_flag                 = 0;
            $token_access_data          = array();

            if ($usage_token_list->count() > 0) {
                $access_user_data = $request->session()->get('access_user_data');
                $token_type       = array(444, 555, 666);

                foreach ($access_user_data as $aud) {

                    if ($aud->access_type_id == '444' || $aud->access_type_id == '555') {
                        $token_access_data = $aud;
                        $token_flag        = 1;
                    }
                }
                if (!empty($token_access_data)) {
                    if ($token_access_data->restricted_download_limit > count($usage_token_list)) {
                        foreach ($usage_token_list as $available_token) {
                            if ($available_token->user_name === $user_name && $available_token->download_content_id == 0 && $token_flag == 1) {
                                $available_flag = 1;
                            }
                        }

                    }
                }
                if ($available_flag == 1) {
                    return array($available_token->user_name, 'Available');
                } else {
                    return array($user_name, 'Not Available');
                }
            } else {
                return array($user_name, 'Incorrect Username');
            }

        }
    }

    public function ExportTokenList($request, $used_token, $available_token)
    {
        $tr_data = '';
        if (!empty($used_token)) {
            $tableHeader = "<table width='1000' align='center' border='1'>
                <tr><td><b>'Used Token Report'</b></td></tr>";
            $tableHeader .= "<tr align='center'>";
            $tableHeader .= "<td align='center' bgcolor='#CCCCCC'><b>Journal Title</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Print ISSN</b></td>
                <td bgcolor='#CCCCCC'><b>Online ISSN</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Year</b></td>
                                <td bgcolor='#CCCCCC'><b>DOI</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Article Title</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Volume No</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Issue No</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Pages</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Content Access Key</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Downloaded From IP</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Download Date</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Access Assign Date</b></td></tr>";

            foreach ($used_token as $token) {

                $tr_data .= "<tr><td>" . $token->journal_title . "</td>
                                  <td>" . $token->journal_issn . "</td>
                                  <td>" . $token->journal_eissn . "</td>
                                  <td>" . $token->year . "</td>
                                  <td>" . $token->article_doi . "</td>
                                  <td>" . $token->article_title . "</td>
                                  <td>" . $token->volume_name . "</td>
                                  <td>" . $token->issue_title . "</td>
                                  <td>" . $token->first_page . ' to ' . $token->last_page . "</td>
                                  <td>" . $token->user_name . "</td>
                                  <td >" . long2ip($token->download_ip) . "</td>
                                  <td>'" . strftime("%d-%m-%Y", $token->download_time) . "</td>
                                  <td>" . strftime("%d-%m-%Y", $token->system_time) . "</td>";
                $tr_data .= "</tr>";

            }

            $table = $tableHeader;
            //$table.='<br>';
            $table .= $tr_data . "</table>";

            header("Content-type: application/vnd.ms-excel");
            header("Content-Disposition: attachment; filename=token_report.xls");
            print $table;
            exit;

        } else {
            return back();
        }

    }

    public function RenderImage($param)
    {

        $imagepath = decrypt($param);

        readfile($imagepath);

        die;
    }

    public function Webinars(Request $request)
    {

        $country      = Country::GetCountryList();
        if ($request->submit_webinars) {
            $validator = Validator::make($request->all(),
                [
                    'salutation'    => 'required',
                    'first_name'    => 'required',
                    'last_name'     => 'required',
                    'webinar_title' => 'required',
                    'webinar_id'    => 'required',
                    'email'         => 'required|string|email|max:255',

                ]);

            if ($validator->fails()) {
                $detail['name']          = '';
                $detail['email']         = '';
                $detail['site_comment']  = '';
                $detail['other_comment'] = '';
                return view('webinars', with(['detail' => $detail,'country' => $country]))->withErrors($validator);
            } else {

                $paypal['id']             = $request->webinar_id;
                $paypal['name']           = 'Academic branding: Improving your visibility, network, and career opportunities';
                $paypal['paypalEnv']      = env('paypalEnv');
                $paypal['paypalURL']      = env('paypalURL');
                $paypal['business']       = env('email_business', '');
                $paypal['price']          = 25;
                $paypal['currency_code']  = 'USD';
                $paypal['paypalClientID'] = env('paypalClientID');
                

                $salutation    = $request->salutation;
                $first_name    = $request->first_name;
                $last_name     = $request->last_name;
                $email         = $request->email;
                $city          = $request->city;
                $country       = $request->country;
                $phone_number  = $request->phone_number;
                $institute_org = $request->institute_org;
                $webinar_title = $request->webinar_title;
                $webinar_id    = $request->webinar_id;
                $webinar_info  = array('salutation' => $salutation,
                    'first_name'                        => $first_name,
                    'last_name'                         => $last_name,
                    'email'                             => $email,
                    'city'                              => $city,
                    'country'                           => $country,
                    'phone_number'                      => $phone_number,
                    'institute_org'                     => $institute_org,
                    'webinar_title'                     => $webinar_title,
                    'webinar_id'                        => $webinar_id);

                session(['webinar_info' => $webinar_info]);

                return view('webinars', with(['country' => $country,'paypal' => $paypal, 'webinar_info' => $webinar_info]));
            }

        }
        return view('webinars');
    }

    public function WebinarPaypalResponse(Request $request)
    {

        $webinar_info = session()->has('webinar_info') ? session()->get('webinar_info') : false;

        $paypal_obj = new PaypalExpress;
        $paymentID  = $request->paymentID;
        $token      = $request->token;
        $payerID    = $request->payerID;
        $productID  = $request->pid;
        // Validate transaction via PayPal API
        $paymentCheck = $paypal_obj->PaypalValidate($paymentID, $token, $payerID, $productID);

        // If the payment is valid and approved
        if ($paymentCheck && $paymentCheck->state == 'approved') {
            // Get the transaction data
            $id = $paymentCheck->id;
            $state = $paymentCheck->state;
            $payerFirstName = $paymentCheck->payer->payer_info->first_name;
            $payerLastName = $paymentCheck->payer->payer_info->last_name;
            $payerName = $payerFirstName.' '.$payerLastName;
            $payerEmail = $paymentCheck->payer->payer_info->email;
            $payerID = $paymentCheck->payer->payer_info->payer_id;
            $payerCountryCode = $paymentCheck->payer->payer_info->country_code;
            $webinar_info['paidAmount'] = $paidAmount = $paymentCheck->transactions[0]->amount->details->subtotal;
            $currency = $paymentCheck->transactions[0]->amount->currency;
            
            //print_r($paymentCheck); die;
            // Get product details
            $productData['price'] = 25;
        
            // If payment price is valid
            if($productData['price'] >= $paidAmount){

                // Paypal Payment Done Successfully
                //$to      = 'nomanakbar@benthamscience.net';
                $to      = 'arshad@xolva.com';
                $cc      = "aisha@benthamscience.net";
                $bcc     = "bentham.eureka@gmail.com";
                $subject = "Webinar: Paypal Payment";
                $from    = $payerEmail;
                $replyto = "marketing@benthamscience.net";

                SendSmtpMail('email_template.webinar', $webinar_info, $to, $from, $subject, $request->name, $cc);

                Session::flash('success', 'Thank you for your payment!');
            }
        }
        Session::flash('error', 'Somthing wrong with this page. Please try again!');
        return Redirect::to('admin/articles');
    }

}
