<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Customers;
use App\Addresses;
use App\Packages;
use App\Facilities;
use App\Excesses;
use Session;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Hash;
use App\Repository\PackagesRepository;
use App\SubscriptionFacilities;
use App\Transactions;
use App\GocardlessCustomers;
use App\GocardlessSubscriptions;
use PDF;

class AccountsController extends FrontController {

    public function __construct() {
        $this->middleware('auth:customers');
    }

    private $packages;

    public function index() {

        $id = auth("customers")->user()->id;

        $model = Customers::with(array('transaction' => function($query) {
                        $query->where('confirmed', 1);
                        $query->orderBy("id", "desc");
                        $query->limit(1);
                    }))->where("id", $id)->first();


        $data["model"] = $model;
        return view('front/account', $data);
    }

    public function update(Request $request) {

        $rules = [
            'title' => 'required',
            'first_name' => 'required',
            'last_name' => 'required',
            'phone' => 'required|size:11',
            'address1' => 'required',
            'postcode' => 'required',
            'city' => 'required',
        ];
        $rules["email"] = 'required|email|unique:customers,email,' . auth('customers')->user()->id;


        $messages = [
            'first_name.required' => 'We need to know your First Name!',
            'last_name.required' => 'We need to know your Last Name!',
            'phone.required' => 'We need to know your phone!',
            'email.required' => 'We need to know your email address!',
            'address1.required' => 'We need to know your address!',
            'postcode.required' => 'We need to know your postcode!',
            'city.required' => 'We need to know your city!'
        ];

        if (!empty($request->password)) {
            $rules["password"] = 'required|confirmed|min:8';
        }

        $id = auth("customers")->user()->id;
        $model = Customers::find($id);

        $validator = Validator::make($request->all(), $rules, $messages);

        if (!empty($request->current_password)) {
            $validator->after(function($validator) use ($request, $model) {
                if (!Hash::check($request->current_password, $model->password)) {
                    $validator->errors()->add('current_password', 'This is the error message');
                }
            });
        }

        $failed = $validator->failed();

        $header = 200;
        $response = array();
        $response['errors'] = array();
        $response['error'] = false;
        if ($validator->fails()) {
            $errors = $validator->errors();
            $response['errors'] = $errors;
            $response['error'] = true;
            $header = 402;
            //return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {


            $account["firstName"] = $request->first_name;
            $account["lastName"] = $request->last_name;
            $account["email"] = $request->email;
            $account["phone"] = $request->phone;
            $account["title"] = $request->title;

            if (!empty($request->current_password)) {
                $account["password"] = $request->password;
            }

            Customers::where("id", $id)->update($account);

            $address["address1"] = $request->address1;
            $address["address2"] = $request->address2;
            $address["city"] = $request->city;
            $address["postcode"] = $request->postcode;
            Addresses::where("customer_id", $id)->update($address);


            $_POST["firstname"] = $request->first_name;
            $_POST["lastname"] = $request->last_name;
            $_POST["phone"] = $request->phone;

            $_POST["old_email"] = $request->old_email;
            $_POST["email"] = $request->email;
            $_POST["address"] = $request->address1;

            $this->updateContactOnHubspot($_POST);
        }

        return response()->json($response, $header);
    }

    public function mypackage(PackagesRepository $packages) {

        $id = auth("customers")->user()->id;
        $this->packages = $packages;
        $data = array();

        $model = Customers::with(array('transaction' => function($query) {
                        $query->where('confirmed', 1);
                        $query->orderBy("id", "desc");
                        $query->limit(1);
                    }))->where("id", $id)->orderBy("id", "desc")->first();

        //d($model,1);            
        if (isset($model->transaction)) {
            $type = $model->transaction->type;
            $excess_id = $model->transaction->excess_id;


            $package = Packages::where("id", $model->transaction->package_id)->first();
            $package = $this->packages->setPackage($package);

            $facilities = array();

            if (count($package["facilities"]) > 0) {

                $facilities = SubscriptionFacilities::
                        leftjoin('package_facilities', 'package_facilities.facility_id', '=', 'subscription_facilities.facility_id')
                        ->leftjoin('facilities', 'package_facilities.facility_id', '=', 'facilities.id')
                        ->where("subscription_facilities.transaction_id", $model->transaction->id)
                        ->where("facilities.status", 1)
                        ->groupBy("facilities.id")
                        ->get();
            }

            $excess = Excesses::find($excess_id);
            $prices = $package['prices'][$type][$excess_id];

            $data["prices"] = $prices;
            $data["facilities"] = $facilities;
            $data["package"] = $package;
            $data["type"] = $type;
            $data["model"] = $model;
            $data["excess_id"] = $excess_id;
            $data["excess"] = $excess;
        }

        return view('front/my_package', $data);
    }

    public function mypaymentmethod() {

        $id = auth("customers")->user()->id;
        $model = Transactions::where("customer_id", $id)->orderBy("id", "desc")->first();
        $user = Customers::find($id);
        $data["subscription"] = array();

        if (isset($model->id)) {
            $paymentMethods = array();
            if ($model->paymentMethod == "credit_card") {

                $customer = $user->asStripeCustomer();
                $paymentMethods = $user->defaultPaymentMethod();
            } else {

                $customer = GocardlessCustomers::where("customer_id", $id)->orderBy("id")->first();
                $subscription = GocardlessSubscriptions::where("gocardless_customer_id", $customer->id)->orderBy("id")->first();
                $data["subscription"] = $subscription;
            }

            $data["customer"] = $customer;
            $data["paymentMethod"] = $paymentMethods;
            $data["model"] = $model;
        }


        return view('front/my_payment_method', $data);
    }

    public function transactionPDF(PackagesRepository $packages, $number) {

        // return $this->getData($packages, $number)['prices'];
        $customer = auth("customers")->user();

        $this->packages = $packages;
        $model = Transactions::where("invoiceNumber", $number)
                ->where("customer_id", $customer->id)
                ->orderBy("id", "desc")
                ->first();

        $data = array();

        if (isset($model->id)) {

            $address = Addresses::where("customer_id", $customer->id)->first();

            $package = $this->packages->setPackage($model->package);

            $facilities = array();

            if (count($package["facilities"]) > 0) {

                $facilities = SubscriptionFacilities::
                        leftjoin('package_facilities', 'package_facilities.facility_id', '=', 'subscription_facilities.facility_id')
                        ->leftjoin('facilities', 'package_facilities.facility_id', '=', 'facilities.id')
                        ->where("subscription_facilities.transaction_id", $model->id)
                        ->where("facilities.status", 1)
                        ->groupBy("facilities.id")
                        ->select('subscription_facilities.title')
                        ->get();
            }

            $data["Title"] = $customer->title ?? '';
            $data["First_Name"] = $customer->firstName ?? '';
            $data["Last_Name"] = $customer->lastName ?? '';
            $data["Phone_Number"] = $customer->phone ?? '';
            $data["Email"] = $customer->email ?? '';

            $data['Address1'] = $address->address1 ?? '';
            $data['Address2'] = $address->address2;
            $data['City'] = $address->city ?? '';
            $data['Zip'] = $address->postcode ?? '';

            $data['Package_Name'] = ucfirst($package['title']) ?? '';

            $data['CURRENCY'] = Config("params.currency")['symbol'] ?? '';

            $data['Total_Price'] = numberformat($model->total) ?? '';

            $data['NET_Amount'] = numberformat($model->price) ?? '';

            $data['Plan'] = ucfirst($model->type) ?? '';

            $data["facilities"] = $facilities ?? [];
            
            
            $data['VAT_Amount'] = numberformat($model->total) - numberformat($model->price);

            $data['Invoice_Number'] = $model->invoiceNumber ?? '';

            $data['Created_Date_Time'] = date('d/m/Y', strtotime($model->startDate)) ?? '';

            $facilities = array_chunk($data['facilities']->toArray(), 3);

            $count = count($facilities);

            $pdf = PDF::loadView('front.pdf.invoice', ['data' => $data, 'facilities' => $facilities, 'count' => count($facilities)]);
            return $pdf->stream('invoice.pdf');
        }
    }

    public function mytransactions() {

        $id = auth("customers")->user()->id;
        $model = Transactions::where("customer_id", $id)->orderBy("id", "desc")->get();
        $data["model"] = $model;
        return view('front/my_transactions', $data);
    }

    public function transaction(PackagesRepository $packages, $number) {

        $data = $this->getData($packages, $number);
       
        

        return view('front/transaction', $data);
    }

    public function getData($packages, $number) {
        # code...
        $id = auth("customers")->user()->id;
        $customer = auth("customers")->user();

        //d($customer,1);
        $this->packages = $packages;
        $model = Transactions::where("invoiceNumber", $number)
                ->where("customer_id", $id)
                ->orderBy("id", "desc")
                ->first();

        $data = array();

        if (isset($model->id)) {

            $address = Addresses::where("customer_id", $id)->first();

            $type = $model->type;
            $excess_id = $model->excess_id;
            $package = $this->packages->setPackage($model->package);

            $facilities = array();

            if (count($package["facilities"]) > 0) {

                $facilities = SubscriptionFacilities::
                        leftjoin('package_facilities', 'package_facilities.facility_id', '=', 'subscription_facilities.facility_id')
                        ->leftjoin('facilities', 'package_facilities.facility_id', '=', 'facilities.id')
                        ->where("subscription_facilities.transaction_id", $model->id)
                        ->where("facilities.status", 1)
                        ->groupBy("facilities.id")
                        ->get();
            }

            $excess = Excesses::find($excess_id);

            $prices = $package['prices'][$type][$excess_id];

            $data["address"] = $address;
            $data["prices"] = $prices;
            $data["facilities"] = $facilities;
            $data["package"] = $package;
            $data["type"] = $type;
            $data["model"] = $model;
            $data["excess_id"] = $excess_id;
            $data["excess"] = $excess;
            $data["customer"] = $customer;
        }

        return $data;
    }

    public function updateContactOnHubspot($post) {

        $key = env('HUBSPOT_API_KEY');

        $arr = array(
            'properties' => array(
                array(
                    'property' => 'email',
                    'value' => $post['email']
                ),
                array(
                    'property' => 'firstname',
                    'value' => $post['firstname']
                ),
                array(
                    'property' => 'lastname',
                    'value' => $post['lastname']
                ),
                array(
                    'property' => 'phone',
                    'value' => $post['phone']
                ),
                array(
                    'property' => 'address',
                    'value' => $post['address1']
                )
            )
        );


        $res = $this->getVid($post['old_email']);

        if (array_key_exists('status', $res)) {
            if ($res['status'] == 'error') {
                return ['status' => false];
            }
        }

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($arr));

        curl_setopt($ch, CURLOPT_URL, 'https://api.hubapi.com/contacts/v1/contact/vid/' . $res['vid'] . '/profile?hapikey=' . $key);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        return json_decode($response, true);
    }

    public function getVid($email) {
        $key = env('HUBSPOT_API_KEY');

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://api.hubapi.com/contacts/v1/contact/email/' . $email . '/profile?hapikey=' . $key);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $res = curl_exec($ch);

        return json_decode($res, true);
    }

}
