<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Paste;
use Auth;
use App\User;
use Redirect;
use \Input;
use \Hash;
use Session;
use Cookie;
use DB;
use \Carbon;
use App\Order;

class UpgradeController extends Controller
{
	private function jsonError($msg = null){
		$r = (is_null($msg) ? ['status' => 'err'] : ['status' => 'err', 'msg' => $msg]);
		return response()->json($r);
	}
    public function upgrade(){
		$myUser = newGetUser();
        $products = DB::table('products')->get();
        
        $buttons = [];

        foreach($products as $product){
            if($product->id > 1 && $product->id < 5){ // roles
                if(!is_null($myUser) && $myUser->role > 0){
                    $pid = $product->id - 1;
                    if($pid <= $myUser->role){
                        $button = new \stdClass();
                        $button->text = "$".($product->price + 0);
                        $button->disabled = " disabled";
                        $buttons[] = $button;
                    }else{
                        $button = new \stdClass();
                        $button->text = "$".($product->price - $products->where('id', $myUser->role + 1)->first()->price + 0);
                        $button->disabled = "";
                        $buttons[] = $button;
                    }
                }else{
                    $button = new \stdClass();
                    $button->text = "$".($product->price + 0);
                    $button->disabled = "";
                    $buttons[] = $button;
                }
            }else if($product->id == 1){ // name colors
                $button = new \stdClass();
                $button->text = "$".($product->price + 0);
                if(!is_null($myUser) && ($myUser->has_name_color || $myUser->role >= 95)){
                    $button->disabled = " disabled";
                }else{
                    $button->disabled = "";
                }
                $buttons[] = $button;
            }else{ // just in case
                $button = new \stdClass();
                $button->text = "-";
                $button->disabled = " disabled";
                $buttons[] = $button;
            }

        }
        
		return view('upgrade', ['myUser' => $myUser, 'buttons' => $buttons]);
	}	

    public function webhook(Request $r){
        $file = fopen(env('BTCPAY_WEBHOOK_LOG'), 'a');

        try {
            $body = file_get_contents('php://input');
            $secret = utf8_encode(env('BTCPAY_SIGNATURE'));
            $sig = 'sha256=' . hash_hmac('sha256', $body, $secret);

            if (!isset($_SERVER['HTTP_BTCPAY_SIG']) || $_SERVER['HTTP_BTCPAY_SIG'] !== $sig) {
                fwrite($file, "Received webhook call without a valid signature, so it will be ignored.\n");

                return abort(404);
            }

            $data = json_decode($body);
            fwrite($file, $data->type . ' - ' . $r->getMethod() . ': ' . $sig . ' : ' . (isset($_SERVER['HTTP_BTCPAY_SIG']) ? $_SERVER['HTTP_BTCPAY_SIG'] : 'Unset') . "\n");

            if ($data->type == "InvoiceConfirmed" || $data->type == "InvoiceSettled") {
                $order = Order::where('order_id', $data->invoiceId)->first();

                if (is_null($order)) {
                    fwrite($file, $data->type . ' - ' . $r->getMethod() . ": No order was found, or order was null.\n");

                    return abort(403);
                }

                $myUser = User::find($order->user_id);

                if (is_null($myUser)) {
                    fwrite($file, $data->type . ' - ' . $r->getMethod() . ": Tried to retrieve associated user with ID $order->user_id, but no record was found.\n");

                    return abort(403);
                }

                $product = $order->product_id;

                $myUser->applyUpgrade($product, $data->invoiceId);
            }

            Order::where('order_id', $data->invoiceId)->update(['status' => $data->type]);

            fwrite($file, $data->type . ' - ' . $r->getMethod() . ": Status of order ID $data->invoiceId was updated to $data->type\n");

            return "ok";
        } finally {
            fclose($file);
        }
    }

    public function change_color(Request $r){
        $error = response()->json(['status' => 'err']);
        if(!$r->isMethod('post')){
            return $error;
        }


        $colors = array('none', 'BB71E4', '4B2E83', 'FEC8D8', 'BB1E64', 'FFFFFF', '365DDA', 'F96D31', 'FFFE71', 'B83C26', 'C5C6D3', /* new sep 2022: */'94FAAC', '964B00', '000080', 'FF69B4', 'FFD580', '601EF9', '30D5C8', '9999FF', '4C4CFF', '004C00');

        $myUser = newGetUser();

        if(is_null($myUser)){
            return $error;
        }

        if($myUser->role < 95 && !$myUser->has_name_color){
            return $error;
        }

        $color = Input::get('color');

        if(!in_array($color, $colors)){
            return $error;
        }
        $myUser->name_color = ($color == 'none' ? null : $color);
        $myUser->save();
        return response()->json(['status' => 'done']);
    }

	public function create_invoice(Request $r){
        if(!$r->isMethod('post')){
            return response()->json(['status' => 'err']);
        }

        $myUser = newGetUser();

        if (!$r->attributes->get('captcha', false)) {
            return $this->jsonError('Captcha verification failed. Try again');
        }
        
        if (is_null($myUser)){
            return response()->json(['status' => 'err']);
        }

        $pid = Input::get('pid');
        $products = DB::table('products')->get();
        $product = $products->where('id', $pid)->first();

        if ($product == null){
            return response()->json(['status' => 'err']);
        }
        
        $price = $product->price;
        if ($product->id > 1 && $product->id < 5) {
            if ($myUser->role > 0) {
                $pid = $product->id - 1;
                if ($pid <= $myUser->role) {
                    return response()->json(['status' => 'err']);
                } else {
                    $price = $product->price - $products->where('id', $myUser->role + 1)->first()->price;
                }
            } else {
                $price = $product->price;
            }
        } else if ($product->id == 1) {
            if($myUser->has_name_color || $myUser->role >= 95) {
                return response()->json(['status' => 'err']);
            } else {
                $price = $product->price;
            }
        }

        $params = [
            'amount' => $price,
            'redirectURL' => 'https://' . currentDomain() . '/',
            'itemDesc' => $product->title,
            'currency' => 'USD',
        ];

        $btcPayBase = env('BTCPAY_URL');
        $btcPayStoreId = env('BTCPAY_STORE_ID');
        $btcPayToken = env('BTCPAY_TOKEN');
        $path = "$btcPayBase/api/v1/stores/$btcPayStoreId/invoices";

        $btcPayReqHeaders = ['Content-Type: application/json', 'Authorization: token ' . $btcPayToken];

        $params = json_encode($params);
        $c = curl_init($path);

        curl_setopt($c, CURLOPT_HTTPHEADER, $btcPayReqHeaders);
        curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($c, CURLOPT_POSTFIELDS, $params);
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true); 
        $result = curl_exec($c);
        $r = curl_getinfo($c, CURLINFO_HTTP_CODE);

        if ($r != 200) {
            return response()->json(['status' => 'err1']);
        }

        $result = json_decode($result);
        $redirect = $result->checkoutLink;
        Order::create([
            'order_id' => $result->id,
            'user_id' => $myUser->id,
            'price' => $price,
            'product_id' => $product->id,
        ]);

        return response()->json(['status' => 'done', 'redirect' => $redirect]);
    }
}
