<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Paypal as PayPal;
use Session;
use Redirect;
use Cart;
use Carbon\Carbon;
use App\Shoppingcart as mCart;
use App\Checkout as mCheckout;
use App\Settings as mSetting;
use App\BankList as mBankList;
use App\BankAccount as mBankAcc;
use App\Currency;
use App\Shipment;
use Mail;
use App\Mail\CheckoutMail as CheckoutMail;
use App\Mail\CheckoutNotifBuyer as OrderMail;
use Snowfire\Beautymail\Beautymail;

class PaypalController extends Controller
{
  private $_apiContext;

  public function __construct(){
    $this->_apiContext = PayPal::ApiContext(
            mSetting::where(['setting_name'=>'paypal_client_id'])->first()->setting_value,
            mSetting::where(['setting_name'=>'paypal_secret'])->first()->setting_value);

    $this->_apiContext->setConfig(array(
      'mode' => 'live',
      // 'service.EndPoint' => 'https://api.sandbox.paypal.com',
      'http.ConnectionTimeOut' => 30,
      'log.LogEnabled' => true,
      'log.FileName' => storage_path('logs/paypal.log'),
      'log.LogLevel' => 'FINE'
    ));

   }

  public function formCheckout(Request $req){
    $method = $req->payment_method;
    $shipment = Shipment::firstOrFail();
    if($method == "manual"){
      # FOR MANUAL PAYMENT

      $data['bank_list'] = mBankAcc::all();
      $data['page'] = "checkout";
      $data['payment_method'] = $method;
      return view("product.checkout.form")->with($data);
    }else{
      # FOR ONLINE PAYMENT
      $get = mSetting::where('setting_name','currency')->first();
      if(empty($get)){
        $currency = "USD";
      }else{
        $currency = $get->setting_value;
      }

      $amount = str_replace('.','',Cart::total());
      
      if ($shipment->option == 'flat') {
        $amount = $amount + $shipment->amount;
      } elseif ($shipment->option == 'delivery') {
        if (Cart::content()->count()) {
          $shipmentCost = 0;
          $shipmentCost = Cart::content()->first()->options->shipment_cost ? Cart::content()->first()->options->shipment_cost : 0;
          $amount = $amount + str_replace([',', '.'], "", $shipmentCost);
        }
      }
      
      $from = 'USD';
      $to = $currency;
      $api_key = 'c85f44834c961d5537a523d59de5a5d0';
      $url = 'http://www.apilayer.net/api/live?access_key='.$api_key.'&currencies='.$from.','.$to;

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_VERBOSE, 1);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_URL, $url);
      
      $currencies =  curl_exec($ch);
      $json = json_decode($currencies);
      $rate = 0;
      foreach ($json->quotes as $key => $val) {
        if ($key=='USD'.$currency) {
          $rate =  $val;
        }
      }

      $total = $amount/$rate;
      // return $total;
      $data['pay_amount'] = number_format($total,2,'.',',');
      $data['shipment_cost'] = $req->shipment_cost;
      $data['shipment_destination'] = $req->shipment_destination;
      $data['page'] = "checkout";
      $data['payment_method'] = $method;
      return view("product.checkout.form")->with($data);
    }
  }

  public function getCheckout(Request $req){
    $get = mSetting::where('setting_name','currency')->first();
    if(empty($get)){
      $currency = "USD";
    }else{
      $currency = $get->setting_value;
    }

    $this->validate($req, [
      'checkout_fname' => 'required',
      'checkout_lname' => 'required',
      'checkout_email' => 'email|required',
      'checkout_phone' => 'required',
      'checkout_address' => 'required',
    ]);

    $order_id = $req->order_id;
    $total = Cart::total();
    $pay_amount = $req->pay_amount;

    $req->session()->put('checkout-data',$req->all());

    $payer = PayPal::Payer();
  	$payer->setPaymentMethod('paypal');

  	$amount = PayPal:: Amount();
    if($currency == "IDR"){
      $amount->setCurrency('USD');
    }else{
      $amount->setCurrency($currency);
    }

  	$amount->setTotal($pay_amount); // This is the simple way,
  	// you can alternatively describe everything in the order separately;
  	// Reference the PayPal PHP REST SDK for details.

  	$transaction = PayPal::Transaction();
  	$transaction->setAmount($amount);
    $total = $currency." ".$total." (".$amount->currency." ".$amount->total.")";
  	$transaction->setDescription($order_id." Amount: ".$total);

  	$redirectUrls = PayPal:: RedirectUrls();
  	$redirectUrls->setReturnUrl(action('PaypalController@getDone'));
  	$redirectUrls->setCancelUrl(action('PaypalController@getCancel'));

  	$payment = PayPal::Payment();
  	$payment->setIntent('sale');
  	$payment->setPayer($payer);
  	$payment->setRedirectUrls($redirectUrls);
  	$payment->setTransactions(array($transaction));

  	$response = $payment->create($this->_apiContext);
  	$redirectUrl = $response->links[1]->href;

  	return Redirect::to( $redirectUrl );
  }

  public function getDone(Request $request){
  	$id = $request->get('paymentId');
  	$token = $request->get('token');
  	$payer_id = $request->get('PayerID');

  	$payment = PayPal::getById($id, $this->_apiContext);

  	$paymentExecution = PayPal::PaymentExecution();

  	$paymentExecution->setPayerId($payer_id);
  	$executePayment = $payment->execute($paymentExecution, $this->_apiContext);

    // Clear the shopping cart, write to database, send notifications, etc.

    $get = mSetting::where('setting_name','currency')->first();
    if(empty($get)){
      $currency = "USD";
    }else{
      $currency = $get->setting_value;
    }

    $req = $request->session()->get('checkout-data');

    $order_id = $req['order_id'];
    $total = Cart::total();
    $pay_amount = $req['pay_amount'];

    $fname = $req['checkout_fname'];
    $lname = $req['checkout_lname'];
    $email = $req['checkout_email'];
    $phone = $req['checkout_phone'];
    $address = $req['checkout_address'];

    $request->session()->flash('checkout-email',$email);

    $send = [
      'order_id' => $order_id,
      'fname' => $fname,
      'lname' => $lname,
      'email' => $email,
      'phone' => $phone,
      'address' => $address,
      'paypal_total' => $pay_amount,
      'status'=>'paid',
      'to' => 'buyer',
    ];

    if($currency == "IDR"){
      $send['total'] = str_replace(['.',','],'',$total);
    }elseif($currency == "EUR"){
      $send['total'] = str_replace('.','',$total);
    }else{
      $send['total'] = str_replace(',','',$total);
    }

    /* SENT EMAIL */

    // to client
    Mail::to($email)->send(new OrderMail($send,Cart::content()));

    // to admin
    $email_admin = mSetting::where(['setting_name'=>'companyEmail'])->first()->setting_value;
    $send['to'] = "vendor";
    Mail::to($email_admin)->send(new OrderMail($send,Cart::content()));



    $db = new mCheckout;
    $db->order_id = $order_id;
    $db->paypal_payment_id = $id;
    $db->checkout_fname = $fname;
    $db->checkout_lname = $lname;
    $db->checkout_email = $email;
    $db->checkout_phone = $phone;
    $db->checkout_address = $address;
    if($currency == "IDR"){
      $db->checkout_total = str_replace(['.',','],'',$total);
    }elseif($currency == "EUR"){
      $db->checkout_total = str_replace('.','',$total);
    }else{
      $db->checkout_total = str_replace(',','',$total);
    }
    $db->checkout_total_paypal = $pay_amount;
    $db->checkout_status = 'paid';
    $db->save();

    Cart::store($order_id);
    Cart::destroy();

    // Thank the user for the purchase
    $data['payment_method'] = 'online';
    $data['page'] = 'checkout';
  	return view('product.checkout.done')->with($data);
  }

  public function getCancel(){
    // Curse and humiliate the user for cancelling this most sacred payment (yours)
    $data['page'] = 'checkout';
  	return view('product.checkout.cancel')->with($data);
  }

  public function checkOrder(Request $req, $order_id = ""){
    if($order_id != ""):
      $data['checkout'] = mCheckout::where(['order_id'=>$order_id])->first();
      $data['cart'] = unserialize(mCart::where(['identifier'=>$order_id])->first()->content);
    endif;

    // return unserialize(mCart::where(['identifier'=>$order_id])->first()->content);
    $data['order_id'] = $order_id;
    $data['page'] = "Check Order";
    return view('product.checkout.check')->with($data);
  }

  public function manualCheckout(Request $req){
    $this->validate($req, [
      'checkout_fname' => 'required',
      'checkout_lname' => 'required',
      'checkout_email' => 'email|required',
      'checkout_phone' => 'required',
      'checkout_address' => 'required',
    ]);

    $payment_method = $req->payment_method;
    $order_id = $req->order_id;
    $total = Cart::total();

    $fname = $req->checkout_fname;
    $lname = $req->checkout_lname;
    $email = $req->checkout_email;
    $phone = $req->checkout_phone;
    $address = $req->checkout_address;

    $send = [
      'order_id' => $order_id,
      'fname' => $fname,
      'lname' => $lname,
      'email' => $email,
      'phone' => $phone,
      'address' => $address,
      'status' => 'not paid yet',
      'to' => 'buyer',
    ];

    $currency = mSetting::where('setting_name', 'currency')->first()->setting_value;
    // return $req->all();

    if($currency == "IDR"){
      $send['total'] = str_replace(['.',','],'',$total);
    }elseif($currency == "EUR"){
      $send['total'] = str_replace('.','',$total);
    }else{
      $send['total'] = str_replace(',','',$total);
    }

    /* SENT EMAIL */

    // to client
    Mail::to($email)->send( new OrderMail($send,Cart::content()) );

    // to admin
    $email_admin = mSetting::where(['setting_name'=>'companyEmail'])->first()->setting_value;
    $send['to'] = "vendor";
    Mail::to($email_admin)->send( new OrderMail($send,Cart::content()) );

    $db = new mCheckout;
    $db->order_id = $order_id;
    $db->paypal_payment_id = '-';
    $db->checkout_fname = $fname;
    $db->checkout_lname = $lname;
    $db->checkout_email = $email;
    $db->checkout_phone = $phone;
    $db->checkout_address = $address;
    if($currency == "IDR"){
      $db->checkout_total = str_replace(['.',','],'',$total);
    }elseif($currency == "EUR"){
      $db->checkout_total = str_replace('.','',$total);
    }else{
      $db->checkout_total = str_replace(',','',$total);
    }
    $db->checkout_total_paypal = 0;
    $db->save();

    Cart::store($order_id);
    Cart::destroy();

    $req->session()->flash('manual-payment-status','done');

    return redirect()->route('manualDone');
  }

  public function manual_checkout_done(Request $req){
    if(empty($req->session()->get('manual-payment-status'))){
      return redirect('/');
    }

    $data['bank_list'] = mBankAcc::all();
    $data['payment_method'] = 'manual';
    $data['page'] = 'checkout';
  	return view('product.checkout.done')->with($data);
  }

}
