<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Packages;
use App\Facilities;
use App\Excesses;
use Session;
use App\Repository\PackagesRepository;
use App\Transactions;
use App\Addresses;
use App\Customers;
use Carbon\Carbon;
use App\Settings;
use DB;
use App\PackageFacilities;
use App\SubscriptionFacilities;
use DateTime;
use Date;
use App\Helpers\PasswordEncryptHelper;
use App\Categories;
// use App\GocardlessSubscription;
use Illuminate\Support\Facades\Auth;
use App\EmailsResponders;
use App\Helpers\Functions;
use App\Helpers\EmailTemplates;
use PDF;
use Mail;
use Illuminate\Support\Str;

class ThankYouController extends Controller
{

    private $packages;
    protected $facilities;
    protected $key;
    protected $slug;

    public function __construct(PackagesRepository $packages)
    {
        $this->packages = $packages;
        $this->key = env('HUBSPOT_API_KEY');
    }

    public function index()
    {
        $data["headerClass"] = '';
        return view('front/thankyou', $data);
    }

    public function order_successful()
    {

        $id = Session::get('subscription_id');
        
        if (isset($id)) {

            $obj = Transactions::where('id', $id)->first();
            $data["headerClass"] = '';


            //$this->notify();
            return view('front/order_successful', $data, ['obj' => $obj]);
        } else {
            return redirect("/");
        }
    }

    public function notify()
    {


        $package_id = Session::get('package');
        $type = Session::get('type');
        $excess_id = Session::get('excess_id');
        $prices = Session::get('prices');
        $anchorDate2 = Session::get('hub_spot_date');
        $subscription_id = Session::get('subscription_id');
        $customer_id = auth('customers')->user()->id;
        $new = Session::get('new_user');
        $header = 200;
        $response = array();
        $response['errors'] = array();
        $response['error'] = false;

        if (isset(auth('customers')->user()->id) && isset($package_id) && isset($excess_id)) {

            $obj = Transactions::where('id', $subscription_id)->first();
            $paymentMethod = $obj->paymentMethod;
            $invoiceNumber = $obj->invoiceNumber;
            $created_at = date("Y-m-d H:i:s");
            $customerType = Session::get('customerType');
            $title = Session::get('title');
            $firstName = Session::get('first_name');
            $lastName = Session::get('last_name');
            $phone = Session::get('phone');
            $email = Session::get('email');
            $address = Session::get('address1');
            $address2 = Session::get('address2');
            $postcode = Session::get('postcode');
            $agreementDate = Session::get('date');
            $boilerAge = Session::get('boilerAge');
            $city = Session::get('city');

            $selectedFacilities = Session::get('facilities');

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

            $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", $subscription_id)
                ->where("facilities.status", 1)
                ->groupBy("facilities.id")
                ->select('subscription_facilities.title')
                ->get();
            //}
            //  d($facilities,1);




            $subscriptions = [
                "customer_id" => $customer_id,
                "subscription_id" => $subscription_id,
                "paymentMethod" => $paymentMethod,
                "boilerAge" => $boilerAge,
                "package_id" => $package_id,
                "type" => $type,
                "excess_id" => $excess_id,
                "price" => $prices["price"],
                "vat" => $prices["vat"],
                "total" => $prices["total_price"],
                "startDate" => $agreementDate,
                "invoiceNumber" => $invoiceNumber,
                "confirmed" => 1,
                "created_at" => date("Y-m-d H:i:s")
            ];

            $user = Customers::find($customer_id);
            $this->sendEmail($user, $invoiceNumber, $package, $subscriptions, $facilities);


            if ($new == "Yes") {
                $this->sendEmailPassword($email, $firstName, $agreementDate, $package["title"]);
                Session::put("new_user", "No");
                Session::forget("new_user");

                //die("here");
            }
            ///// for hub spot
            $post["salutation"] = $title;
            $post["firstname"] = $firstName;
            $post["lastname"] = $lastName;
            $post["phone"] = $phone;
            $post["age_of_boiler"] = $boilerAge;
            $post["email"] = $email;
            $post["address"] = $address;
            $post["zip"] = $postcode;
            $post["city"] = $city;
            $post["address_line_two"] = $address2;
            $post["state"] = $city;
            $post["package"] = $package["title"];
            $post["package_price"] = $prices["total_price"];
            $post["start_date"] = $anchorDate2;
            $post["frequency_of_collection"] = $type;


            Session::forget('excess_id');
            Session::forget('package');
            Session::forget('excess_id');
            Session::forget('prices');
            Session::forget('hub_spot_date');
            Session::save();
            $this->storeContact($post);
            $response['error'] = false;
        } else {
            $response['message'] = "already notify";
        }
        echo json_encode($response);
        die;
    }

    public function storeContact($post)
    {

        $arr = array(
            'properties' => array(
                array(
                    'property' => 'email',
                    'value' => $post['email']
                ),
                array(
                    'property' => 'salutation',
                    'value' => $post['salutation']
                ),
                array(
                    'property' => 'firstname',
                    'value' => $post['firstname']
                ),
                array(
                    'property' => 'lastname',
                    'value' => $post['lastname']
                ),
                array(
                    'property' => 'phone',
                    'value' => $post['phone']
                ),
                array(
                    'property' => 'address',
                    'value' => $post['address']
                ),
                array(
                    'property' => 'zip',
                    'value' => $post['zip']
                ),
                array(
                    'property' => 'city',
                    'value' => $post['city']
                ),
                array(
                    'property' => 'state',
                    'value' => $post['state']
                ),
                array(
                    'property' => 'address_line_two',
                    'value' => $post['address_line_two']
                ),
                array(
                    'property' => 'package',
                    'value' => $post['package']
                ),
                array(
                    'property' => 'package_price',
                    'value' => $post['package_price']
                ),
                array(
                    'property' => 'recurring_amount',
                    'value' => 0
                ),
                array(
                    'property' => 'boiler_service_complete',
                    'value' => false
                ),
                array(
                    'property' => 'age_of_boiler',
                    'value' => $post['age_of_boiler']
                ),
                array(
                    'property' => 'lifecyclestage',
                    'value' => 'customer'
                ),
                array(
                    'property' => 'frequency_of_collection',
                    'value' => $post['frequency_of_collection']
                ),
                array(
                    'property' => 'start_date',
                    'value' => $post['start_date']
                ),
            )
        );

        $contactResponse = $this->setCurlData('https://api.hubapi.com/contacts/v1/contact?hapikey=', $arr);

        if (!$contactResponse['status']) {

            return $contactResponse;
        }



        return ['status' => true];
    }

    public function setCurlData($url, $payload)
    {
        $ch = curl_init();

        $endpoint = $url . $this->key;
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        curl_close($ch);

        $result = json_decode($response, true);

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

        return ['status' => true];
    }

    public function sendEmail($customer, $invoiceNumber, $package, $subscriptions, $facilities)
    {




        $prices = Session::get('prices');
        $bothEmailsResponders = EmailsResponders::where('Title', 'User - Invoice')->orWhere('Title', 'Admin - Invoice')->get();

        $agreementDate = Session::get('date');

        $excess_id = Session::get('excess_id');
        $type = Session::get('type');

        $excess = Excesses::find($excess_id);
        $excessPrices = $package['prices'][$type][$excess_id];
        $facilities = array_chunk($facilities->toArray(), 3);
            
            $count = count($facilities);
        foreach ($bothEmailsResponders as $emailsResponders) {

            $data["body"] = $emailsResponders->Content;
            $data["title"] = $emailsResponders->Title;
            $data["subject"] = $emailsResponders->Subject;

            $replaces["Title"] = $customer->title;
            $replaces["First_Name"] = $customer->firstName;
            $replaces["Last_Name"] = $customer->lastName;
            $replaces["Phone_Number"] = $customer->phone;
            $replaces["Email"] = $customer->email;
            $replaces['Address1'] = $customer->address->address1 ?? '';
            $replaces['Address2'] = $customer->address->address2 ?? '';
            $replaces['City'] = $customer->address->city ?? '';
            $replaces['Zip'] = $customer->address->postcode ?? '';

            $replaces['Package_Name'] = ucfirst($package['title']) ?? '';
            $replaces["CURRENCY"] = env("CURRENCY_SYMBOL");

            $replaces['Total_Price'] = numberformat($prices["total_price"]);
            $replaces['NET_Amount'] = numberformat($prices["price"]);
            $replaces["Plan"] = rtrim($subscriptions["type"], "ly") ?? '';

            $replaces["VAT_Amount"] = numberformat($prices["vat_amount"]);
            $replaces["Invoice_Number"] = $invoiceNumber;
            $replaces["Created_Date_Time"] = date("d/m/y", strtotime($agreementDate));
            $replaces["Invoice_Service_Table"] = EmailTemplates::setPackageTemplate($facilities);
            $replaces["CALL_OUT_CHARGE"] = "Your call out charge is " . $excess->title . ".";
            $replaces["Website_Name"] = \URL::to('/');
            /*
            if ($package["customizable"] == false) {
            $replaces["CALL_OUT_CHARGE"] = "Your call out charge is " . $excess->title . ".";
            } else {
            $replaces["CALL_OUT_CHARGE"] = "";
            }
            */

            $template = Functions::replaces($data, $replaces);
            // $settings = sett
            
            $pdf = PDF::loadView('front.pdf.invoice', ['data' => $replaces, 'facilities' => $facilities, 'count' => $count]);
            //echo $pdf->output();
            //die;
            //d($pdf->output(),1);
            //file_put_contents("test1233.pdf", $pdf->output());
            $setting = Settings::where("category", "email")->where('title', 'Website Email Receivers')->first();
            
            try {
                if ($emailsResponders->Title == 'User - Invoice') {
                    
                    echo Mail::send('front.emails.template', ['content' => $template["body"]], function ($m) use ($customer, $template, $pdf) {
                        $m->from(env("MAIL_FROM_ADDRESS"), env("MAIL_FROM_NAME"));
                        //"aftabafzaal@live.com" $customer->email
                        $m->to($customer->email, $customer->first_name)->subject($template["subject"]);
                        $m->attachData($pdf->output(), 'invoice.pdf', ['mime' => 'application/pdf']);
                    });

                } elseif ($emailsResponders->Title == 'Admin - Invoice') {
                      
                    echo Mail::send('front.emails.template', ['content' => $template["body"]], function ($m) use ($customer, $template, $pdf, $setting) {
                        
                        $m->from(env("MAIL_FROM_ADDRESS"), env("MAIL_FROM_NAME"));
                        $m->to($setting->content, $customer->first_name)->subject($template["subject"]);
                        $m->attachData($pdf->output(), 'invoice.pdf', ['mime' => 'application/pdf']);
                    });

                } else {
                    echo "Email Responder Error";

                }
            } catch (\Throwable $th) {

                die($th);
                // throw $th;
            }

        }
    }

    public function sendEmailPassword($email, $first_name, $startDate, $package)
    {

        $emailsResponders = EmailsResponders::where('Title', 'User - Signup')->first();

        $data["body"] = $emailsResponders->Content;
        $data["title"] = $emailsResponders->Title;
        $data["subject"] = $emailsResponders->Subject;
        $replaces["Email"] = $email;
        $replaces["First_Name"] = $first_name;
        $replaces["Package_Name"] = $package;
        $replaces["Start_Date"] = date("d/m/Y", strtotime($startDate));
        $replaces["Website_Name"] = \URL::to('/');


        $template = Functions::replaces($data, $replaces);

        $subject = $template['subject'];

        try {

            Mail::send('front.emails.template', ['content' => $template["body"]], function ($m) use ($email, $first_name, $subject) {
                $m->from(env("MAIL_FROM_ADDRESS"), env("MAIL_FROM_NAME"));
                $m->to($email, $first_name)->subject($subject);
            });
        } catch (\Throwable $th) {
            die("Throwable 2");
            // throw $th;
        }
    }

}