<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Yajra\Datatables\Datatables as Datatables;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Facades\Excel;
use Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Str;
use Auth;
use Session;
use Request as req;

use App\User;
use App\Organization;
use App\Client_Organization;
use App\ServerConfig;
use App\Country;
use App\UserProduct;
use App\ProductDetails;
use App\PaymentLink;
use App\District;
use App\State;
use App\Seat;
use App\User_Seat;
use App\Seat_Permission;
use App\Office;
use App\Seat_Role;

class PlanController extends Controller
{
    /////invoice list/////////////////////////////////////////
    function checkemail($email_req)
    {
        $userarr = User::where('email','=', $email_req)->where('verified',1)->first();
        if(isset($userarr)) 
        {
            $user_id = $userarr->id;
            $user_seat_obj = User_Seat::where('user_id',$user_id)->first();
            if(isset($user_seat_obj))
            {
                $seat_id = $user_seat_obj->seat_id;
                $role_seat_obj = Seat_Role::where('seat_id',$seat_id)->first();
                if(isset($role_seat_obj))
                {
                    $role_id = $role_seat_obj->role_id;
                }
                $seat_obj = Seat::where('id',$seat_id)->first();
                if(isset($seat_obj))
                {
                    $office_id = $seat_obj->office_id;
                }
            }
            //$roleid = $userarr->role_id;
            //$organization_id = $userarr->organization_id;
            if($role_id==6)
            {
                $email = $email_req;
            }
            else
            {
                $role_seat_objt = Seat_Role::where('role_id',$role_id)->first();
                if(isset($role_seat_objt))
                {
                    $seat_id1 = $role_seat_objt->seat_id;
                }
                $user_seat_objt = User_Seat::where('seat_id',$seat_id1)->first();
                if(isset($user_seat_objt))
                {
                    $user_id_new = $user_seat_objt->user_id;
                }
                $seat_objt = Seat::where('id',$seat_id1)->first();
                if(isset($seat_objt))
                {
                    $office_id1 = $seat_objt->office_id;
                }
                $user_org = User::where('id',$user_id_new)->first();
                if(isset($user_org))
                {
                    $email = $user_org->email;
                }
            }
        }
        return $email;
    }
    public function invoice_list()
    {
        $user = \Auth::user();
        $email_req = $user->email;
        $server_config = ServerConfig::first();
        if(isset($server_config))
        {
            $api_url = $server_config->server_url;
        }

        $email = $this->checkemail($email_req);
        
        $data = [
                    'email' => $email,
                    'product_slugname' => 'digifile',
                ];
        /////to get the active invoices////////////////////////////////////////////////////
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api_url.'api/listinvoice',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array(
                // Set here requred headers
                "accept: */*",
                "accept-language: en-US,en;q=0.8",
                "content-type: application/json",
                "X-Authorization: BxybvQb457YhdKC7HduyxUnN5l4auMvEVF2HOfkOAIJbKTu6G4rPgLfOM2vkrvxV",     //////api key generated for get invoice
            ),
        ));
        $response = curl_exec($curl);
        //dd($response);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) 
        {
            echo "cURL Error #:" . $err;
        } 
        else 
        {
            $invoices = json_decode($response);
        }

        $slugname_arr =[];
        $display_name_arr =[];
        $paymentlink = PaymentLink::all();
        foreach($paymentlink as $paymentlinks)
        {
            $slugname = $paymentlinks->slugname;
            $frequency =$paymentlinks->frequency;
            $slugname_arr[]= $slugname;
            $display_name_arr[$slugname] = $paymentlinks->display_name;
            $display_frequency[$slugname] = $paymentlinks->frequency;
        }

        //dd($display_name);
        ////////////////////////////////////////////////////////////////////////////////////////
        ////////////////to get the active subscription details////////////////////////////////////
        $curl_plan = curl_init();
        curl_setopt_array($curl_plan, array(
            CURLOPT_URL => $api_url.'api/getplan',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array(
                // Set here requred headers
                "accept: */*",
                "accept-language: en-US,en;q=0.8",
                "content-type: application/json",
                "Accept: application/json",
                "X-Authorization: B78QZhy7rGG9EJvBQTa9bzVYzg4NT9jRdQ5JMV7rgmiDWCv0iBuaub4SAEXCBbP2",     //////api key generated for get plan to list in profile
            ),
        ));

        $response_plan = curl_exec($curl_plan);
        //dd($response_plan);
        $httpcode_plan = curl_getinfo($curl_plan, CURLINFO_HTTP_CODE);
        $err_plan = curl_error($curl_plan);
        curl_close($curl_plan);
        if ($err_plan) 
        {
            echo "cURL Error #:" . $err_plan;
        } 
        else 
        {
            $plan = json_decode($response_plan);
            //return $plan;
            if(isset($plan))
            {
                $plan_name = $plan->plan_name;
                $payment_interval = $plan->payment_interval;
                if($payment_interval=="year")
                {
                    $payment_interval_val = "annual";
                }
                if($payment_interval=="month")
                {
                    $payment_interval_val = "monthly";
                }
                $prd_det = PaymentLink::where('slugname','=', $plan_name)->where('frequency',$payment_interval_val)->first();  
            }
        }
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //dd($invoices);
        return view('plans/invoice_list', compact('invoices','email','plan','prd_det','display_name_arr','display_frequency','slugname_arr'));
    }

    /////invoice generation/////////////////////////////////////////
    public function invoice_pdf(Request $request)
    {
        $email = $request->email;
        $inv_id = $request->inv_id;
        $invoice_number = $request->invoice_number;
        $server_config = ServerConfig::first();
        if(isset($server_config))
        {
            $api_url = $server_config->server_url;
        }
        $data = [
                    'email' => $email,
                    'inv_id' => $inv_id,
                    'invoice_number' => $invoice_number,
                    'product_slugname' => 'digifile',
                ];
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api_url.'api/getinvoice',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array(
                // Set here requred headers
                "accept: */*",
                "accept-language: en-US,en;q=0.8",
                "content-type: application/json",
                "X-Authorization: BxybvQb457YhdKC7HduyxUnN5l4auMvEVF2HOfkOAIJbKTu6G4rPgLfOM2vkrvxV",     //////api key generated for get invoice
            ),
        ));
        $response = curl_exec($curl);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) 
        {
            echo "cURL Error #:" . $err;
        } 
        else 
        {
            $invoices = json_decode($response);
        }
        //dd($invoices);
        return view('plans/invoice_pdf', compact('invoices','email'));
    }   

    public function plan_edit(Request $request)
    {
        $user = \Auth::user();
        $email_req = $user->email;
        $email = $this->checkemail($email_req);
        $data = [
                    'email' => $email,
                    'product_slugname' => 'digifile',
                ];
        //$api_url = "http://139.59.43.152/raintelsplan/public/";
        $server_config = ServerConfig::first();
        if(isset($server_config))
        {
            $api_url = $server_config->server_url;
        }
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api_url.'api/checksubscription',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array(
                // Set here requred headers
                "accept: */*",
                "accept-language: en-US,en;q=0.8",
                "content-type: application/json",
                "X-Authorization: AlXoSUIrs9QSXVjMiDkpLX5ipqJUb1tPkKoEKKAIV22X70YkTH5ftXzaN5ryddl5",     //////api key generated for check active subscription
            ),
        ));
        
        $response = curl_exec($curl);
        //dd($response);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) 
        {
            echo "cURL Error #:" . $err;
        } 
        else 
        {
            $plan = json_decode($response);
        }
        $slugname_arr =[];
        $display_name_arr =[];
        $paymentlink = PaymentLink::all();
        foreach($paymentlink as $paymentlinks)
        {
            $slugname = $paymentlinks->slugname;
            $frequency =$paymentlinks->frequency;
            $slugname_arr[]= $slugname;
            $display_name_arr[$slugname] = $paymentlinks->display_name;
            $display_frequency[$slugname] = $paymentlinks->frequency;
        }
        //dd($response);
        return view('plans/subscription_check_msg', compact('plan','email','slugname_arr','display_name_arr'));
    }

    public function change_plan(Request $request)
    {
        $email_req = $request->email;
        $email = $this->checkemail($email_req);
        $product_slugname = 'digifile';
        $data = [
                    'product_slugname' => 'digifile',
                    'email' => $email,
                ];
        //dd($data);
        $server_config = ServerConfig::first();
        if(isset($server_config))
        {
            $api_url = $server_config->server_url;
        }
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api_url.'api/checkplans',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array(
                // Set here requred headers
                "accept: */*",
                "accept-language: en-US,en;q=0.8",
                "content-type: application/json",
                "X-Authorization: sglgvE0a0wvHNBhyT72ub4UHHn4Xk4JsgLr5WxxwWYjBzCUmZR4ZPn95KG0e5tmx",     //////api key generated for plans list
            ),
        ));
        $response = curl_exec($curl);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) 
        {
            echo "cURL Error #:" . $err;
        } 
        else 
        {
            $max_num_stds =[];
            $max_num_users=[];
            $payment_link_val = [];
            $plans = json_decode($response);
            foreach($plans as $plan)
            {
                $plan_name = $plan->plan_name;
                $payment_interval = $plan->payment_interval;
                if($payment_interval=="month")
                {
                    $frequency = "monthly";
                }
                if($payment_interval=="year")
                {
                    $frequency = "annual";
                }
                $prd_det = PaymentLink::where('slugname','=', $plan_name)->first();  
                if(isset($prd_det))
                {
                    $max_num_users[$plan_name] = $prd_det->number_of_users;
                    $max_num_stds[$plan_name] = $prd_det->no_of_standards;
                }
                $paymentlinks_val = PaymentLink::where('slugname',$plan_name)->where('frequency',$frequency)->orderBy('id','desc')->first();
                if(isset($paymentlinks_val))
                {
                    $payment_link_val[$plan_name][$frequency] = $paymentlinks_val->payment_link;
                }
            }
        }
        $slugname_arr =[];
        $display_name_arr =[];
        $paymentlink = PaymentLink::all();
        foreach($paymentlink as $paymentlinks)
        {
            $slugname = $paymentlinks->slugname;
            $slugname_arr[]= $slugname;
            $display_name_arr[$slugname] = $paymentlinks->display_name;
        }
        //dd($payment_link_val);
        return view('plans/change_plan', compact('plans','email','max_num_users','payment_link_val','max_num_stds','slugname_arr','display_name_arr'));
    }
    
    public function change_plan_subscription(Request $request)
    {
        $product_code = $request->product_code;   ///prod_xxxxxx 
        $plan_name = $request->plan_name; //new plan name
        $email_req = $request->email;
        $email = $this->checkemail($email_req);
        $data = [
                    'email' => $email,
                    'plan_name' => $plan_name,
                    'product_code' => $product_code,
                    'product_slugname' => 'digifile',
                ];
        $server_config = ServerConfig::first();
        if(isset($server_config))
        {
            $api_url = $server_config->server_url;
        }
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api_url.'api/getnewsubscription',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array(
                // Set here requred headers
                "accept: */*",
                "content-type: application/json",
                "accept-language: en-US,en;q=0.8",
                "X-Authorization: z7mTEy8mRZJKuwWGZFLrHSAdXTAHm5ZyJJObZKgMvay9k1uchig1yPVhpgLu2CpV",     //////api key generated for plans list
            ),
        ));
        
        $response = curl_exec($curl);
        //dd($response);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) 
        {
            echo "cURL Error #:" . $err;
        } 
        else 
        {
            //$change_plans = json_decode($response);
            $plan_name_new = $response;
        }
        $slugname_arr =[];
        $display_name_arr =[];
        $paymentlink = PaymentLink::all();
        foreach($paymentlink as $paymentlinks)
        {
            $slugname = $paymentlinks->slugname;
            $slugname_arr[]= $slugname;
            $display_name_arr[$slugname] = $paymentlinks->display_name;
        }
        //dd($plan_name_new);
        return view('plans/change_plan_subscription_msg', compact('plan_name_new','plan_name','email','slugname_arr','display_name_arr'));
    }

    public function subscription_cancel()
    {
        $user = \Auth::user();
        $email_req = $user->email;
        $email = $this->checkemail($email_req);
        $data = [
                    'email' => $email,
                    'product_slugname' => 'digifile',
                ];
                
        //$api_url = "http://139.59.43.152/raintelsplan/public/";
        $server_config = ServerConfig::first();
        if(isset($server_config))
        {
            $api_url = $server_config->server_url;
        }
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api_url.'api/listsubscription',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array(
                // Set here requred headers
                "accept: */*",
                "accept-language: en-US,en;q=0.8",
                "content-type: application/json",
                "X-Authorization: 5UnHob5Q0NUl4ICXf2c9AYG3EeFBNYhiNU0X7eTvX6I6cDUbobLy0cozTNbZ2YIS",     //////api key generated for check active subscription
            ),
        ));
        
        $response = curl_exec($curl);
        //dd($response);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) 
        {
            echo "cURL Error #:" . $err;
        } 
        else 
        {
            $plans = json_decode($response);
        }
        $slugname_arr =[];
        $display_name_arr =[];
        $paymentlink = PaymentLink::all();
        foreach($paymentlink as $paymentlinks)
        {
            $slugname = $paymentlinks->slugname;
            $slugname_arr[]= $slugname;
            $display_name_arr[$slugname] = $paymentlinks->display_name;
        }
        //dd($display_name_arr);
        return view('plans/subscription_cancel', compact('plans','email','slugname_arr','display_name_arr'));
    }

    public function subscription_cancel_post(Request $request)
    {
        $email_req = $request->email;
        $email = $this->checkemail($email_req);
        $data = [
                    'email' => $email,
                    'product_slugname' => 'digifile',
                ];
        $server_config = ServerConfig::first();
        if(isset($server_config))
        {
            $api_url = $server_config->server_url;
        }
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api_url.'api/cancelsubscription',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array(
                // Set here requred headers
                "accept: */*",
                "accept-language: en-US,en;q=0.8",
                "content-type: application/json",
                "X-Authorization: dKidkf15VcbdUE9BSNakmS2nBcEx7aEkoDG15ocXILFanlaQ0adtuaerQj1UGShr",     //////api key generated for plan cancel
            ),
        ));
        
        $response = curl_exec($curl);
        //dd($response);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) 
        {
            echo "cURL Error #:" . $err;
        } 
        else 
        {
            $plans = json_decode($response);
        }
        $slugname_arr =[];
        $display_name_arr =[];
        $paymentlink = PaymentLink::all();
        foreach($paymentlink as $paymentlinks)
        {
            $slugname = $paymentlinks->slugname;
            $slugname_arr[]= $slugname;
            $display_name_arr[$slugname] = $paymentlinks->display_name;
        }
        
        return view('plans/subscription_cancel_msg', compact('plans','email','slugname_arr','display_name_arr'));
    }
}
