<?php

namespace App\Http\Controllers;

use App\Models\Discount;
use App\Models\Purchase;
use App\Models\Theme;
use App\Models\Transaction;
use Auth;
use Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class PurchaseController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['view']]);
    }

    public function checkout($theme_code)
    {
        $theme = Theme::where('code', $theme_code)->first();
        return view('purchases.checkout', compact('theme'));
    }

    public function discountCheck()
    {
        $discounts = Discount::all();
        $discount_code = $_POST['discount_code'];

        foreach ($discounts as $discount) {
            if ($discount_code == $discount->code) {
                $amount = $discount->amount;
                return json_encode(array('err' => false, 'amount' => $amount, 'msg' => 'Discount Code Applied!'));
            }
        }
        return json_encode(array('err' => true, 'msg' => 'Unvalid Discount Code'));
    }

    public function postCheckout()
    {
        //Purchase Data
        Session::put('purchaseData', $_POST);
        //Set Variables
        $name = Auth::user()->name;
        $phone = $_POST['phone'];
        $theme_code = $_POST['theme_code'];
        $discount_code = $_POST['discount_code'];
        $retail_price = $_POST['retail_price'] * 100;
        $amount = $_POST['paid_price'] * 100;
        //Sent to Billplz
        $res = $this->billplz_curl($name, $phone, $amount);
        //Response from Billplz
        if (isset($res->error)) {
            return json_encode(array('err' => true, 'msg' => $res->error->message[0]));
        } else {
            $url = $res->url;
            return json_encode(array('err' => false, 'url' => $url));
        }
    }

    function billplz_curl($name, $phone, $amount)
    {
        $apiurl = Config::get('constants.billplz_api_url');
        $billplz_api_key = Config::get('constants.billplz_api_key');
        $billplz_api_token = base64_encode($billplz_api_key . ':');
        $Authorization = "Basic " . $billplz_api_token;

        $post = array();
        $post['collection_id'] = Config::get('constants.billplz_collection_id');
        $post['email'] = Auth::user()->email;
        $post['name'] = $name;
        $post['mobile'] = $phone;
        $post['amount'] = $amount;
        $post['callback_url'] = url('/');
        $post['description'] = 'KadKahwinDIgital.my Theme Purchase';
        $post['redirect_url'] = url('/purchase/thankyou');

        // HEADERS AND OPTIONS APPEAR TO BE A FIREFOX BROWSER REFERRED BY GOOGLE
        $header[] = "Accept: application/json";
        $header[] = "Cache-Control: max-age=0";
        $header[] = "Connection: keep-alive";
        $header[] = "Keep-Alive: 300";
        $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
        $header[] = "Accept-Language: en-us,en;q=0.5";
        $header[] = "Pragma: "; // BROWSERS USUALLY LEAVE THIS BLANK
        $header[] = "Authorization: " . $Authorization;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $apiurl);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
        curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
        //curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout  );
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
        $htm = curl_exec($curl);
        // ON FAILURE HANDLE ERROR MESSAGE
        if ($htm === FALSE) {
            // if ($error_report) {
            //     $err = curl_errno($curl);
            //     $inf = curl_getinfo($curl);
            //     echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            //     var_dump($inf);
            //     die;
            // }

            $err = curl_errno($curl);
            $inf = curl_getinfo($curl);
            echo "CURL_ERRNO=$err";
            var_dump($inf);

            curl_close($curl);
            return FALSE;
        }

        // ON SUCCESS RETURN XML / HTML STRING
        curl_close($curl);
        $res = json_decode($htm);
        return $res;
    }

    public function thankyou()
    {
        $purchaseSession = Session::get('purchaseData');
        if (isset($_GET) && isset($_GET['billplz'])) {
            $transaction = $this->billplz_transcation($_GET['billplz']['id']);
            $preExist = Purchase::where('bill_id', $_GET['billplz']['id'])->first();
            if (empty($preExist)) {
                //dd($transaction);
                if ($transaction->transactions[0]->status == 'failed') {
                    Session::forget('purchaseData');
                    //return view('fallback.error')
                    //	->with('err_title', 'FAILED')
                    //	->with('err_text', 'Technical problem occured during the payment process. Please contact us at bookklik.technologies@gmail.com for help.');
                    return view('purchases.failed');
                } else {
                    // Save order data
                    $purchaseData = new Purchase;
                    $purchaseData->bill_id = $transaction->bill_id;
                    $purchaseData->user_id = Auth::user()->id;
                    $purchaseData->email = $purchaseSession['email'];
                    $purchaseData->theme_code = $purchaseSession['theme_code'];
                    $purchaseData->discount_code = $purchaseSession['discount_code'];
                    $purchaseData->retail_price = $purchaseSession['retail_price'];
                    $purchaseData->paid_price = $purchaseSession['paid_price'];
                    $purchaseData->save();

                    // Purchase ID
                    $purchase_id = $purchaseData->id;

                    // Save order purchase meta data
                    $this->createPurchaseMetas($purchaseSession['theme_code'], $purchase_id, $purchaseSession, $purchaseData);

                    // Save Order Transactions data
                    $purchaseTransaction = new Transaction;
                    $purchaseTransaction->purchase_id = $purchase_id;
                    $purchaseTransaction->bill_id = $transaction->bill_id;
                    $purchaseTransaction->transaction_id = $transaction->transactions[0]->id;
                    $purchaseTransaction->amount = $purchaseSession['paid_price'];
                    $purchaseTransaction->transaction_status = $transaction->transactions[0]->status;
                    $purchaseTransaction->payment_channel = $transaction->transactions[0]->payment_channel;
                    $purchaseTransaction->save();

                    Session::forget('purchaseData');

                    //return view('fallback.success')
                    //	->with('suc_title', 'THANK YOU')
                    //	->with('suc_text', 'Your order had been placed succesfully.');
                    return view('purchases.thankyou');
                }

            }
        } else {
            return redirect('/home');
        }
    }

    public function billplz_transcation($billid)
    {
        $apiurl = 'https://www.billplz.com/api/v3/bills/' . $billid . '/transactions';
        $billplz_api_key = Config::get('constants.billplz_api_key');
        $billplz_api_token = base64_encode($billplz_api_key . ':');
        $Authorization = "Basic " . $billplz_api_token;

        $header[] = "Accept: application/json";
        $header[] = "Cache-Control: max-age=0";
        $header[] = "Connection: keep-alive";
        $header[] = "Keep-Alive: 300";
        $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
        $header[] = "Accept-Language: en-us,en;q=0.5";
        $header[] = "Pragma: "; // BROWSERS USUALLY LEAVE THIS BLANK
        $header[] = "Authorization: " . $Authorization;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $apiurl);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
        curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
        //curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout  );
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $htm = curl_exec($curl);
        // ON FAILURE HANDLE ERROR MESSAGE
        if ($htm === FALSE) {
            // if ($error_report) {
            //     $err = curl_errno($curl);
            //     $inf = curl_getinfo($curl);
            //     echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            //     var_dump($inf);
            //     die;
            // }

            $err = curl_errno($curl);
            $inf = curl_getinfo($curl);
            echo "CURL_ERRNO=$err";
            var_dump($inf);

            curl_close($curl);
            return FALSE;
        }

        // ON SUCCESS RETURN XML / HTML STRING
        curl_close($curl);
        $res = json_decode($htm);
        return $res;
    }

    public function createPurchaseMetas($theme_code, $purchase_id, $purchaseSession, $purchaseData) {
        if ($theme_code == 'service_print_card') {
            $purchaseData->metas()->create([
                'purchase_id' => $purchase_id,
                'key' => 'name',
                'value' => $purchaseSession['customer_name'],
            ]);
            $purchaseData->metas()->create([
                'purchase_id' => $purchase_id,
                'key' => 'customer_phone_no',
                'value' => $purchaseSession['phone'],
            ]);
            $purchaseData->metas()->create([
                'purchase_id' => $purchase_id,
                'key' => 'address',
                'value' => $purchaseSession['customer_address'],
            ]);
            $purchaseData->metas()->create([
                'purchase_id' => $purchase_id,
                'key' => 'card_amount',
                'value' => $purchaseSession['card_amount'],
            ]);
        }
    }
}
