<?php

namespace App\Http\Controllers;

use App\Beneficiary;
use App\Carrier;
use App\CCInfo;
use App\Country;
use App\PaymentTransaction;
use App\Product;
use App\ProductTransaction;
use App\Sku;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Mockery\Exception;

class MainController extends Controller
{




    //nexmo
    
    public function nexmoVerify($fullnumber)
    {
           
        $url = 'https://api.nexmo.com/verify/json?' . http_build_query([
            'api_key' => '7543f2bb',
            'api_secret' => 'ae40b80f53dca562',
            'number' => $fullnumber,
            'brand' => 'Cliqa'
        ]);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        curl_close($ch);

        $json = json_decode($response, true);

        return $json;

    }


    public function nexmoCheck($request_id, $code)
    {
        $url = 'https://api.nexmo.com/verify/check/json?' . http_build_query([
            'api_key' => '7543f2bb',
            'api_secret' => 'ae40b80f53dca562',
            'request_id' => $request_id,
            'code' => $code
        ]);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        
        curl_close($ch);

        $json = json_decode($response, true);

        return $json;
    }


    //end nexmo






    public function getCountries(){
        try{
            $countries = DB::table('country')
                ->select('country.id', 'country.name')
                ->leftJoin('product', 'country.id', '=', 'product.country_id')
                ->where('product.active', '=', 1)
                ->groupBy('country.id','country.name')
                ->orderBy('country.id')
                ->get();

            if($countries){
                return response()->json([
                    'code' => 200,
                    'mensaje' => 'success',
                    'data' => $countries->toArray()
                ]);
            }else{
                return response()->json([
                    'code' => 404,
                    'mensaje' => 'Countries not found'
                ]);
            }

        }catch (\Exception $e){
            return response()->json([
                'code' => 500,
                'mensaje' => 'An Error ocurred pls try again later'
            ]);
        }
    }


    public function getCarriers(){
        $carries = Country::find(1)->carriers()->get();
        return $carries;
    }



    public function getProducts(){
        $carries = DB::select(DB::raw("
            select country.name country_name, carrier.name carrier_name
            from product
            left join country
            on product.country_id = country.id
            left join carrier
            on product.carrier_id = carrier.id
            where product.active = 1 and country.id = 1;"));

        return response()->json([
            'message' => 'success',
            'data' => $carries
        ]);
    }



    public function getCountryCarriers($id)
    {
        $carries = DB::select(DB::raw("
            select product.carrier_id carrier_id, country.name country_name, carrier.name carrier_name
            from product
            left join country
            on product.country_id = country.id
            left join carrier
            on product.carrier_id = carrier.id
            where product.active = 1 and country.id = $id
            group by product.carrier_id
            order by carrier.name asc;"));

        return response()->json([
            'message' => 'success',
            'data' => $carries
        ]);
    }



    public function postBeneficiary(){
        $beneficiary = new Beneficiary();
        $beneficiary->user_id = Input::json('user_id');
        $beneficiary->country_id = Input::json('country_id');
        $beneficiary->carrier_id = Input::json('carrier_id');
        $beneficiary->number = Input::json('number');
        $beneficiary->save();
        return response()->json([
            'code'=> 200,
            'message' => 'beneficiary saved successfully',
            'data' => $beneficiary
        ]);
    }


    public function postProductTransaction(){

        try{
            $productTransaction = new ProductTransaction();
            $productTransaction->beneficiary_id = Input::json('beneficiary_id');
            $productTransaction->sku = Input::json('sku');
            $productTransaction->amount = Input::json('amount');
            $productTransaction->discount = Input::json('discount');
            $productTransaction->save();
            return response()->json([
                'code'=> 200,
                'message' => 'success',
                'data' => $productTransaction
            ]);
        }catch (\Exception $e){
            return response()->json([
                'code'=> 500,
                'message' => 'An error ocurred please try again later',
                'error' => $e
            ]);
        }

    }


    public function getCarrierProducts($countryId, $carrierId){
        $products = DB::select(DB::raw("
            select
            country.name country_name,
            carrier.name carrier_name, 
            product.country_id country_id,
            product.carrier_id carrier_id,
            product.amounts amounts,
            product.discount_pct discount_pct,
            product.sku sku
            from product
            left join country
            on product.country_id = country.id
            left join carrier
            on product.carrier_id = carrier.id
            where product.active = 1 and country.id = $countryId and product.carrier_id = $carrierId;"));

        return response()->json([
            'code'=> 200,
            'message' => 'success',
            'data' => $products
        ]);
    }


    public function getCCInfo($userId){
        try{
            $ccinfo = CCInfo::where('user_id', '=', $userId)->first();

            if($ccinfo){
                return response()->json([
                    'code'=> 200,
                    'message' => 'success',
                    'data' => $ccinfo
                ]);
            }else{
                return response()->json([
                    'code'=> 400,
                    'message' => 'Ccinfo not found'
                ]);
            }

        }catch (\Exception $e){
            return response()->json([
                'code'=> 500,
                'message' => 'An error ocurred please try again later'
            ]);
        }
    }


    //old ccinfo

    public function postCCInfo($userId){
        try{
            $ccinfo = CCInfo::where('user_id', '=', $userId)->first();
            if($ccinfo){
                $ccinfo->name = Input::json('name');
                $ccinfo->cardType = Input::json('cardType');
                $ccinfo->expirationDate = Input::json('expirationDate');
                $ccinfo->token = Input::json('token');
                $ccinfo->save();

                return response()->json([
                    'code'=> 200,
                    'message' => 'success',
                    'data' => $ccinfo
                ]);
            }else{
                $ccinfonew = new CCInfo();
                $ccinfonew->user_id = $userId;
                $ccinfonew->name = Input::json('name');
                $ccinfonew->cardType = Input::json('cardType');
                $ccinfonew->expirationDate = Input::json('expirationDate');
                $ccinfonew->token = Input::json('token');
                $ccinfonew->save();
                return response()->json([
                    'code'=> 200,
                    'message' => 'success',
                    'data' => $ccinfonew
                ]);
            }
        }catch (\Exception $e){
            return response()->json([
                'code'=> 500,
                'message' => 'An error ocurred please try again later'
            ]);
        }
    }


    // post ccinfo avs
    public function postCCInfoAvs($userId){
        try{
            $ccinfo = CCInfo::where('user_id', '=', $userId)->first();
            if($ccinfo){
                $ccinfo->name = Input::json('name');
                $ccinfo->cardType = Input::json('cardType');
                $ccinfo->expirationDate = Input::json('expirationDate');
                $ccinfo->token = Input::json('token');
                $ccinfo->city = Input::json('city');
                $ccinfo->country = Input::json('country');
                $ccinfo->street = Input::json('street');
                $ccinfo->state_province = Input::json('state_province');
                $ccinfo->zip_postal_code = Input::json('zip_postal_code');
                $ccinfo->save();

                return response()->json([
                    'code'=> 200,
                    'message' => 'success',
                    'data' => $ccinfo
                ]);
            }else{
                $ccinfonew = new CCInfo();
                $ccinfonew->user_id = $userId;
                $ccinfonew->name = Input::json('name');
                $ccinfonew->cardType = Input::json('cardType');
                $ccinfonew->expirationDate = Input::json('expirationDate');
                $ccinfonew->token = Input::json('token');
                $ccinfonew->city = Input::json('city');
                $ccinfonew->country = Input::json('country');
                $ccinfonew->street = Input::json('street');
                $ccinfonew->state_province = Input::json('state_province');
                $ccinfonew->zip_postal_code = Input::json('zip_postal_code');
                $ccinfonew->save();
                return response()->json([
                    'code'=> 200,
                    'message' => 'success',
                    'data' => $ccinfonew
                ]);
            }
        }catch (\Exception $e){
            return response()->json([
                'code'=> 500,
                'message' => 'A' . $e
            ]);
        }
    }





    public function getProductTransaction($userId){
        try{
            $transaction = DB::select(DB::raw("
            select
            users.id id,
            product_transaction.id product_transaction_id,
            beneficiary.id beneficiary_id,
            beneficiary.number number,
            carrier.name name,
            product_transaction.sku sku,
            product_transaction.amount amount,
            product_transaction.discount discount,
            ((product_transaction.discount * 100) / (product_transaction.amount)) discount_pct,
            ccinfo.name card_name,
            ccinfo.cardType card_type,
            ccinfo.expirationDate card_expiration,
            ccinfo.token card_token,
            ccinfo.city card_city,
            ccinfo.country card_country,
            ccinfo.street card_street,
            ccinfo.state_province card_state,
            ccinfo.zip_postal_code card_zip
            from users
            left join beneficiary
            on users.id = beneficiary.user_id
            left join ccinfo
            on users.id = ccinfo.user_id
            left join carrier
            on carrier.id = beneficiary.carrier_id
            left join product 
            on carrier.id = product.carrier_id
            left join product_transaction
            on beneficiary.id = product_transaction.beneficiary_id
            where users.id = $userId
            order by product_transaction.id desc
            limit 1;"));

            return response()->json([
                'code'=> 200,
                'message' => 'success',
                'data' => $transaction
            ]);

        }catch (\Exception $e){
            return response()->json([
                'code'=> 500,
                'message' => 'An error ocurred please try again later'
            ]);
        }
    }





public function postPaymentTransaction(){
    try{

        $payment = new PaymentTransaction();
        $payment->product_transaction_id = Input::json('product_transaction_id');
        $payment->carrier = Input::json('carrier');
        $payment->request_id = Input::json('request_id');
        $payment->transaction_id = Input::json('transaction_id');
        $payment->carrier_folio = Input::json('carrier_folio');
        $payment->save();

        return response()->json([
            'code'=> 200,
            'message' => 'success',
            'data' => $payment
        ]);


    }catch (\Exception $e){
        return response()->json([
            'code'=> 500,
            'message' => 'An error ocurred please try again later'
        ]);
    }
}










    //update products and carriers


    public function updateSku(){

        $url = 'https://api.latinotopup.com/api/sku_list.json';


        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_USERPWD, "cliqa:sYBUlnFpEG7TOVru7wc8");


        $output=curl_exec($ch);
        curl_close($ch);

        $json = json_decode($output, true);



        for($i = 0; $i < count($json); $i++){
           //$skuName[] = $json[$i]['sku'];
            $sku = Sku::Find($i+1);

            if($sku){
                $sku->carrier = $json[$i]['carrier'];
                $sku->country = $json[$i]['country'];
                $sku->sku = $json[$i]['sku'];
                $sku->topup_amount = $json[$i]['topup_amount'];
                $sku->topup_amount_currency = $json[$i]['topup_amount_currency'];
                $sku->face_value = $json[$i]['face_value'];
                $sku->face_value_currency = $json[$i]['face_value_currency'];
                $sku->for_testing = $json[$i]['for_testing'];
                $sku->pinless = $json[$i]['pinless'];
                $sku->open_amount = $json[$i]['open_amount'];
                $sku->category = $json[$i]['category'];
                $sku->type = $json[$i]['type'];
                $sku->save();
            }else{
                $sku = new Sku();
                $sku->carrier = $json[$i]['carrier'];
                $sku->country = $json[$i]['country'];
                $sku->sku = $json[$i]['sku'];
                $sku->topup_amount = $json[$i]['topup_amount'];
                $sku->topup_amount_currency = $json[$i]['topup_amount_currency'];
                $sku->face_value = $json[$i]['face_value'];
                $sku->face_value_currency = $json[$i]['face_value_currency'];
                $sku->for_testing = $json[$i]['for_testing'];
                $sku->pinless = $json[$i]['pinless'];
                $sku->open_amount = $json[$i]['open_amount'];
                $sku->category = $json[$i]['category'];
                $sku->type = $json[$i]['type'];
                $sku->save();
            }
        }


        $list = Sku::all();

        return $list;
    }




    //update carrier
    public function updateCarrier(){

        $sku = DB::table('sku_list')
            ->select('carrier')
            ->groupBy('carrier')->get();


        $json = json_decode($sku, true);


        for($i = 0; $i < count($sku); $i++){
            $carrier = Carrier::Where('name','=',$json[$i]['carrier'])->first();
            if($carrier){
                $carrier->name = $json[$i]['carrier'];
                $carrier->save();
            }else{
                $carrier = new Carrier();
                $carrier->name = $json[$i]['carrier'];
                $carrier->save();
            }
        }

    }



    public function updateProducts(){
        $sku = DB::table('sku_list')
            ->leftJoin('carrier', 'carrier.name', '=', 'sku_list.carrier')
            ->leftJoin('country', 'country.name', '=', 'sku_list.country')
            ->select('sku_list.*','carrier.id AS carrier_id', 'country.id AS country_id')
            ->get();

        $json = json_decode($sku, true);
            $conteo = 0;
            $no = 0;
        for($i = 0; $i < count($sku); $i++){
            $product = Product::Where('sku','=', $json[$i]['sku'])->first();

            if($product){
                $conteo++;
                $product->carrier_id = $json[$i]['carrier_id'];
                $product->amounts = '['.'"'.$json[$i]['face_value'].'"'.']';
                $product->save();
            }else{
                $no++;
                $product = new Product();
                $product->carrier_id = $json[$i]['carrier_id'];
                $product->country_id = $json[$i]['country_id'];
                $product->sku = $json[$i]['sku'];
                $product->amounts = '['.'"'.$json[$i]['face_value'].'"'.']';
                $product->is_pinless = $json[$i]['pinless'];
                $product->open_amount = $json[$i]['open_amount'];
                $product->for_testing = $json[$i]['for_testing'];
                $product->active = 0;
                $product->discount_pct = 0;
                $product->save();
            }
        }

        return response()->json([
            'conteo' => $conteo,
            'no' => $no,
            'sum' => $conteo + $no
        ]);


    }















    public function latinoRequest($userId){

        try{
            $transaction = DB::table('users')
                ->select(
                'users.id AS user_id', 
                'beneficiary.id AS beneficiary_id', 
                'beneficiary.number', 
                'product_transaction.sku',
                'product_transaction.amount AS amount',
                'product_transaction.discount AS discount',
                'ccinfo.name AS ccname',
                'ccinfo.cardType AS cctype',
                'ccinfo.token AS cctoken',
                'ccinfo.expirationDate As ccdate'
                )
                ->leftJoin('ccinfo', 'users.id', '=', 'ccinfo.user_id')
                ->leftJoin('beneficiary','users.id','=', 'beneficiary.user_id')
                ->leftJoin('product_transaction', 'beneficiary.id', '=', 'product_transaction.beneficiary_id')
                ->where('users.id', '=', $userId)
                ->orderBy('beneficiary.id', 'desc')
                ->limit(1)
                ->get();
            
                
               
        

            /*if($transaction){
                $charge = $transaction[0]->amount - $transaction[0]->discount;
                $client = new \Payeezy_Client();
                $client->setApiKey("adLERLl2EOJT6dVQ8ZKG5nVH4jr7VmQZ");
                $client->setApiSecret("35213261fb647a5c99b1101e83b2d823bbd1f80a683d5cd6d4f971ae42d92f2d");
                $client->setMerchantToken("fdoa-c45eae86cd45a88689a4643e512a165dc45eae86cd45a886");
                $client->setUrl("https://api.payeezy.com/v1/transactions");
                
                $card_transaction = new \Payeezy_Token($client);
                

                $response = $card_transaction->authorize(
                    [
                        "merchant_ref" => "cliqa-back-auth",
                        "transaction_type" => "authorize",
                        "method" => "token",
                        "amount" => ($charge * 100),
                        "currency_code" => "USD",
                        "token" => array(
                          "token_type" => "FDToken",
                          "token_data" => array(
                            "type" => $transaction[0]->cctype,
                            "value" => $transaction[0]->cctoken,
                            "cardholder_name" => $transaction[0]->ccname,
                            "exp_date" => \Carbon\Carbon::parse($transaction[0]->ccdate)->format('my')
                          )
                        )
                    ]
                );

              
                if($response->transaction_status == "approved" || $response->transaction_status ==  "Approved")
                {
                    $json = json_decode($transaction, true);
                    $user_id = $json[0]['user_id'];
                    $beneficiary_id = $json[0]['beneficiary_id'];
                    $number = $json[0]['number'];
                    $sku = $json[0]['sku'];
    

                    $body_post = [
                        'phonenumber' => $number,
                        'sku' => $sku
                    ];
    
                                       
                    $post_url = 'https://api.latinotopup.com/api/topup_requests.json';
                    $post_request = curl_init();
                    curl_setopt($post_request,CURLOPT_URL, $post_url);
                    curl_setopt($post_request,CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($post_request,CURLOPT_POSTFIELDS, $body_post);
                    curl_setopt($post_request, CURLOPT_USERPWD, "cliqa:sYBUlnFpEG7TOVru7wc8");
                    //curl_setopt($post_request, CURLOPT_TIMEOUT_MS, 5000);
    
                    $post_result = curl_exec($post_request);
                    curl_close($post_request);
    
                    $json_post = json_decode($post_result, true);
    
    
                    return $json_post;
                }
                else if($response->transaction_status == "declined" || $response->transaction_status == "Declined")
                {
                    return response()->json([
                        'code'=> 404,
                        'message' => 'Declined'
                    ]);
                }
                else
                {
                    return response()->json([
                        'code'=> 404,
                        'message' => 'Not Processed'
                    ]);
                }
                

            }*///transaction

            if($transaction)
            {
                $json = json_decode($transaction, true);
                $user_id = $json[0]['user_id'];
                $beneficiary_id = $json[0]['beneficiary_id'];
                $number = $json[0]['number'];
                $sku = $json[0]['sku'];


                $body_post = [
                    'phonenumber' => $number,
                    'sku' => $sku
                ];

                                   
                $post_url = 'https://api.latinotopup.com/api/topup_requests.json';
                $post_request = curl_init();
                curl_setopt($post_request,CURLOPT_URL, $post_url);
                curl_setopt($post_request,CURLOPT_RETURNTRANSFER, true);
                curl_setopt($post_request,CURLOPT_POSTFIELDS, $body_post);
                curl_setopt($post_request, CURLOPT_USERPWD, "cliqa:sYBUlnFpEG7TOVru7wc8");
                //curl_setopt($post_request, CURLOPT_TIMEOUT_MS, 5000);

                $post_result = curl_exec($post_request);
                curl_close($post_request);

                $json_post = json_decode($post_result, true);


                return $json_post;
            }

            else
            {
                return response()->json([
                    'code'=> 404,
                    'message' => 'not found'
                ]);
            }

        }catch (\Exception $e){
            return response()->json([
                'code'=> 500,
                'message' =>  $e
            ]);
        };

    }



    public function latinoExecute($requestId){
        try{

            $body_put = [
                'request_action' => 'execute'
            ];

            $put_url = 'https://api.latinotopup.com/api/topup_requests/'.$requestId.'.json';
            $put_request = curl_init();
            curl_setopt($put_request,CURLOPT_URL, $put_url);
            curl_setopt($put_request,CURLOPT_RETURNTRANSFER, true);
            curl_setopt($put_request, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($put_request,CURLOPT_POSTFIELDS, $body_put);
            curl_setopt($put_request, CURLOPT_USERPWD, "cliqa:sYBUlnFpEG7TOVru7wc8");
            

            $put_result = curl_exec($put_request);
            curl_close($put_request);
            $json_put = json_decode($put_result, true);

            return $json_put;


        }catch(\Exeption $e){
            return response()->json([
                'code'=> 500,
                'message' => 'An error ocurred please try again later'
            ]);
        }
    }





    public function latinoRead($requestId){
        try{
            $get_url = 'https://api.latinotopup.com/api/topup_requests/'.$requestId.'.json';
            $get_request = curl_init();
            curl_setopt($get_request, CURLOPT_URL,$get_url);
            curl_setopt($get_request, CURLOPT_HTTPGET, true);
            curl_setopt($get_request, CURLOPT_RETURNTRANSFER,true);
            curl_setopt($get_request, CURLOPT_USERPWD, "cliqa:sYBUlnFpEG7TOVru7wc8");
            

            $get_result = curl_exec($get_request);
            curl_close($get_request);
            $json_get = json_decode($get_result, true);
            return $json_get;

        }catch(\Exeption $e){
            return response()->json([
                'code'=> 500,
                'message' => 'An error ocurred please try again later'
            ]); 
        }
    }




















    public function findCode($code){
        $influencer = DB::select(DB::raw("
            select * from influencers
            where influencers.code like '$code';
            "));

        if($influencer){
            return response()->json([
                'code'=> 200,
                'message' => 'Success',
                'data' => $influencer
            ]);
        }
        else{
            return response()->json([
                'code'=> 404,
                'message' => 'code not found'
            ]);
        }
    }


    public function putCode($id){
        $user = User::find($id);

        if($user){
            $user->influencer_id = Input::json('influencer_id');
            $user->save();
            return response()->json([
                'code'=> 200,
                'message' => 'User updated',
                'data' => $user
            ]);

        }else{
            return response()->json([
                'code'=> 404,
                'message' => 'user not found'
            ]);
        }
    }



    public function getUserTransactions($id){
        $transactions = DB::table('users')
        ->select(
            'users.id as id',
            'payment_transactions.id as payment_id',
            'payment_transactions.carrier as carrier',
            'beneficiary.number as number',
            'payment_transactions.carrier as carrier',
            'payment_transactions.created_at as created_at'
        )
        ->leftJoin('beneficiary', 'users.id', '=', 'beneficiary.user_id')
        ->leftJoin('product_transaction', 'beneficiary.id', '=', 'product_transaction.beneficiary_id')
        ->leftJoin('payment_transactions', 'product_transaction.id', '=', 'payment_transactions.product_transaction_id')
        ->where('users.id', '=', $id)
        ->where('payment_transactions.carrier', '!=', NULL)
        ->where('payment_transactions.request_id', '!=', NULL)
        ->where('payment_transactions.transaction_id', '!=', NULL)
        ->where('payment_transactions.carrier_folio', '!=', NULL)
        ->orderBy('payment_transactions.id', 'desc')
        ->limit(10)
        ->get();
        
        return response()->json([
            'code'=> 200,
            'message' => 'Transactions',
            'data' => $transactions
        ]);
    }




}
