<?php

namespace App\Http\Controllers;
use App\Http\Controllers\PaypalExpress;
use App\Http\Controllers\MigsController;
use App\Models\Article;
use App\Models\Campaign;
use App\Models\Cart;
use App\Models\Chapter;
use App\Models\EbookVolume;
use App\Models\Node;
use App\Models\Orders;
use App\Models\Country;
use App\Rules\Captcha;
use App\User;
use Auth;
use Crypt;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Mail;

class PromoContentController extends BenthamController
{

    public function index(Request $request)
    {
        

        $content_type = $request->content_type;
        $content_id = $request->content_id;
        $code =   $request->code;
        $user = '';
        $promo_code = '';
        $cartlist = '';

        //----------check if yser login------------
        if(session()->has('user_id'))
        {
            $user = User::where('id', session()->get('user_id'))->first();
        }

        $country        = Country::GetCountryList();

        $request->request->add(['url' => 'promocontent']); //add request

        app('App\Http\Controllers\CartController')->PromoCode($request);

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

        if ($promodiscount !== false) // if promotion code applicable
        { 
            $data     = Campaign::GetCampaignById(session()->get('campaign_id'));
            //    dd($data);
            $cartlist = $this->CheckPromoAccess($request, $data);

            //dd($cartlist);

            if(empty($cartlist))
            {
                Session::flash('message', " Invalid Content");
            }
            else
            {
                Session::forget('message');
            }

        }
        //dd($cartlist);
        return View::make('promo_content.general_content', with(['content_type' => $content_type, 'promo_code' => $code, 'user' => $user, 'country' => $country, 'promodiscount' => $promodiscount, 'cartlist' => $cartlist, 'content_id' => $content_id]));
    }

    /*
     * Date: 21-02-2022
     * Author: Imran
     * Parameter: Request Parameter and PromoCode data row
     * Description:  this function will return the true false, if access conditions applicable
     *  LIKE -- Journal wise promotions
    -- Ebook wise promotions
    -- Country wise promotions
    -- IP base promotions
     */

    public function CheckPromoAccess($request, $promo_data)
    {   
        $journal_access = false;
        $ebook_access   = false;
        $country_access = false;
        $ip_access      = false;
        $Promo_Access   = false;
        $cartlist       = '';
        $userip         = $request->ip();

        $cartlist = Cart::GetPromoProducts($request->content_id, $request->content_type);

        if(!empty($cartlist))
        {

            /*s
             * Check if Promotion has been given on all journals, ebooks and All countries
             */
            if ($promo_data->journals == 'All' && $promo_data->ebooks == 'All' && $promo_data->country == 'All' && ($promo_data->area_type == 'country' && $promo_data->country == 'All')) 
            {
                $Promo_Access = true;

                $discount                   = $promo_data->discount;
                $item_price                 = round(($discount / 100) * ($cartlist->item_price));
                $cartlist->item_price       = round($cartlist->item_cost - $item_price);
                $cartlist->discount         = $discount;

                return $cartlist;

            } else {

                $country_access_all = false;

                /*
                 * Check if Promotion has been given on Country wise
                 */
                if (($promo_data->area_type == 'country' && $promo_data->country == 'All')) {
                    $country_access = true;
                } elseif (($promo_data->area_type == 'country' && $promo_data->country != 'All')) {

                   
                    $query        = "select * from ip2location_db5 where ip_from<='" . ip2long($userip) . "' and ip_to>='" . ip2long($userip) . "'";
                    $user_country = DB::select($query);


                    if ($user_country[0]->country_name != '-') {

                        $promo_country = explode(',', $promo_data->country);
                        $user_country  = $user_country[0]->country_code;
                        if (in_array($user_country, $promo_country)) {
                            $country_access = true;
                        }

                    }

                    /*
                 * Check if Promotion has been given on IP range wise
                 */
                } 
                else if ($promo_data->area_type == 'ip') 
                {

                    $q2 = "select * from campaign_ips where campaign_id='" . $promo_data->id . "' and  from_ip<='" . ip2long($userip) . "' and to_ip>='" . ip2long($userip) . "'";
                    $user_ip_range = DB::select($q2);

                    if ($user_ip_range) {
                        $country_access = true;
                    }
                }

                if ($cartlist->item_type == 'article') 
                {
                    /*
                     * If $country_access true then check All journal access case
                     */
                    if ($promo_data->journals == 'All' && $country_access) 
                    {

                        $discount                   = $promo_data->discount;
                        $item_price                 = round(($discount / 100) * ($cartlist->item_price));
                        $cartlist->item_price = round($cartlist->item_price - $item_price);
                        $cartlist->discount   = $discount;
                        /*
                     * If $country_access true then check on selected journal access case
                     */
                    } else if ($promo_data->journals != 'All' && $country_access) 
                    {

                        $journals = explode(',', $promo_data->journal_ids);
                        if (in_array($cartlist->promotion_content_id, $journals)) 
                        {

                            $discount                   = $promo_data->discount;
                            $item_price                 = round(($discount / 100) * ($cartlist->item_price));
                            $cartlist->item_price = round($cartlist->item_price - $item_price);
                            $cartlist->discount   = $discount;
                        }
                    }
                }
                if ($cartlist->item_type == 'chapter') 
                {
                    /*
                     * If $country_access true then check All Ebook access case  for ebook chapters
                     */
                    if ($promo_data->ebooks == 'All' && $country_access) 
                    {

                        $discount                   = $promo_data->discount;
                        $item_price                 = round(($discount / 100) * ($cartlist->item_price));
                        $cartlist->item_price = round($cartlist->item_price - $item_price);
                        $cartlist->discount   = $discount;

                        /*
                     * If $country_access true then check on selected ebooks access case for ebook chapters
                     */
                    } 
                    else if ($promo_data->ebooks != 'All' && $country_access) 
                    {
                        $ebooks = explode(',', $promo_data->ebook_ids);
                        if (in_array($cartlist->promotion_content_id, $ebooks)) 
                        {
                            $ebook_access = true;
                            $Promo_Access = true;

                            $discount                   = $promo_data->discount;
                            $item_price                 = round(($discount / 100) * ($cartlist->item_price));
                            $cartlist->item_price = round($cartlist->item_price - $item_price);
                            $cartlist->discount   = $discount;
                        }
                    }
                }
                if ($cartlist->item_type == 'ebook_volume')
                 {

                    /*
                     * If $country_access true then check on All ebooks access case
                     */
                    if ($promo_data->ebooks == 'All' && $country_access)
                     {

                        $discount                   = $promo_data->discount;
                        $item_price                 = round(($discount / 100) * ($cartlist->item_price));
                        $cartlist->item_price = round($cartlist->item_price - $item_price);
                        $cartlist->discount   = $discount;

                        /*
                     * If $country_access true then check on Selected ebooks access case
                     */
                    } else if ($promo_data->ebooks != 'All' && $country_access) 
                    {
                        $ebooks = explode(',', $promo_data->ebook_ids);
                        if (in_array($cartlist->promotion_content_id, $ebooks)) 
                        {

                            $discount                   = $promo_data->discount;
                            $item_price                 = round(($discount / 100) * ($cartlist->item_price));
                            $cartlist->item_price = round($cartlist->item_price - $item_price);
                            $cartlist->discount   = $discount;

                        }
                    }
                }

            }

        }

        return $cartlist;

    } //end

    public function PromoPaymentProceed(Request $request)
    {
        global $user;

        $user = '';
        $new_user ='';

        $validator = Validator::make($request->all(),
            [
                'name'                 => 'required',
                'email'                => 'required|string|email|max:255',
                'country'              => 'required',
                'captcha' => 'required|captcha'], 
            ['captcha.captcha' => 'Invalid captcha code.']);

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

        $campaign_data     = Campaign::GetCampaignById(session()->get('campaign_id'));

        $cartlist = $this->CheckPromoAccess($request, $campaign_data);

        if(session()->has('user_id'))
        {
            $user = User::where('email', $request->email)->first();
        }
        else
        {
            $user = User::where('email', $request->email)->first();

            if($user)
            {
                Auth::login($user);     
            }
            else
            {
                $user_data = (object) ['user_name' => $request->name, 'user_email' => $request->email, 'user_country' => $request->country];

                $new_user = UserController::CheckAddUserDetails($user_data);
                if(!empty($new_user))
                {
                    $user = User::where('email', $request->email)->first();

                    if($user)
                    {
                        Auth::login($user);     
                    }
                }
            }
        }

        if(session()->has('user_id'))
        {
            $data['uid']           = session()->get('user_id');
            $data['order_status']  = 'in_checkout';
            $data['primary_email'] = $user->email;
            $data['created']       = time();
            $data['host']          = $request->ip();
            $data['ip_address']    = ip2long($request->ip());
            $data['source']        = 'BSP';
            $data['source_val']    = 1;

            if ($cartlist) 
            {  
                $order_id = Orders::CreateOrder($data);

                $total = 0;
                $uc_order_products['order_id'] = $order_id;
                $uc_order_products['nid']      = $cartlist->nid;
                $uc_order_products['title']    = $cartlist->item_title;
                $uc_order_products['qty']      = 1;
                $uc_order_products['cost']     = $cartlist->item_cost;
                $uc_order_products['price']    = $cartlist->item_price;
                $uc_order_products['weight']   = 0;
                $uc_order_products['data']     = '';

                $total = $cartlist->item_price;
                
                Orders::AddProducts($uc_order_products);

                $order_data['order_total']   = round($total, 4);
                $order_data['product_count'] = 1;
                $order_data['modified']      = time();

                Orders::UpdateOrder($order_id, $order_data);

                if ($request->paypal) 
                {
                    $ptype = $request->paypal;
                }
                if ($request->migs) 
                {
                    $ptype = $request->migs;
                }
                
                if(empty($order_id)) { return redirect()->back();}

                switch ($ptype) {
                    
                    case 'paypal':

                        $order_products = Orders::GetOrderProducts($order_id);
                        $order          = Orders::GetOrder($order_id);

                        $paypal['paypalEnv']          = env('paypalEnv');
                        $paypal['paypalURL']          = env('paypalURL');
                        $paypal['invoice']            = $order->order_id;
                        $paypal['amount']             = round($order->order_total);
                        $paypal['currency_code']      = 'USD';
                        $paypal['paypalClientID']     = env('paypalClientID');
                        $paypal['return']             = url("/cart/paypal/complete/$order->order_id");


                        return view('cart.paypal', with(['order' => $order, 'order_products' => $order_products, 'paypal' => $paypal]));
                        break;
                    case 'migs':

                        $order = Orders::GetOrder($order_id);

                        $migs['merchat_id']         = env('migs_id');
                        $migs['order_id']           = $order->order_id;
                        $migs['amount']             = $order->order_total;
                        $migs['currency_code']      = 'USD';
                        $migs['return_url']         = url("/cart/migs/complete/".$order_id);   
                        $migs['cancel_url']         = url("/promo-content/".$request->content_type."/".$request->content_id."/".$request->promo_code."");   

                        $migs_obj = new MigsController;
                        $responseCheck = $migs_obj->RequestMigsResponse($migs['order_id']);
                        $migs['session_id']         = $responseCheck->session->id;

                        return view('migs', with(['migs' => $migs]));

                        exit;
                        break;

                    default:
                        return redirect()->back();
                        break;
                }

            }

        }

    }
}
