<?php

namespace App\Http\Controllers\Api\v1;

use Illuminate\Http\Request;
use App\SubscriptionPlans;
use App\ManagerPlan;
use App\Manager;
use App\User;
use App\EmailTemplate;
use App\Employee;
use App\UserCoupon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use App\EmailQueue;
use App\Organization;

/*
 * This controller allow strip to send their event notification occurs on dashboard about
 * payment , cancel payment or etcc..
 */

class StripeWebhookController extends Controller {

    public $endpoint_secret = '';

    public function __construct() {
        $this->stripeIntegration();
        if (STRIPE_TESTMODE == "on") {
            $this->endpoint_secret = ENDPOINT_SECRET_TEST;
        } else {
            $this->endpoint_secret = ENDPOINT_SECRET_LIVE;
        }
    }

    public function stripeIntegration() {
        $helperObj = new \App\CommonHelper();
        $stripePubKey = $helperObj->stripeConfiguration();
    }

    public function chargeEvent(Request $request) {
    	$payload = @file_get_contents('php://input');
        $event = null;
        $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
        try {
            
            $event = \Stripe\Event::constructFrom(
                            json_decode($payload, true), $sig_header, $this->endpoint_secret
            );
            $res = $this->eventSwitchThrough($event, $payload);
            //http_response_code(200);
            http_response_code($res);
        } catch (\UnexpectedValueException $e) {
            http_response_code(400);
            exit();
        } catch (\Stripe\Exception\SignatureVerificationException $e) {
            // Invalid signature
            http_response_code(400);
            exit();
        } catch (Exception $e) {
            http_response_code(400);
            exit();
        }
    }

    public function eventSwitchThrough($event, $payload) {
        $emailData = array();
        switch ($event->type) {
//            case 'customer.subscription.created':
//                $subscription = $event->data->object;
//                $emailData['mail_body'] = $subscription;
//                $emailData['mail_subject'] = $event->type;
//                //$this->sendMail($emailData);
//                $res = $this->subscriptionHandler($subscription,$payload);
//                $res = $this->insertWebhookResponse($payload);
//                break;
            case 'invoice.payment_succeeded':
                $subscription = $event->data->object;
                $emailData['mail_body'] = $subscription;
                $emailData['mail_subject'] = $event->type;  
                $res = $this->insertWebhookResponse($payload);
                $res = $this->subscriptionHandler($subscription,$payload);
                $this->sendMail($emailData);
                break;
            default:
                $emailData['mail_body'] = $payload;
                $emailData['mail_subject'] = 'defaultSwitch';
                //$this->sendMail($emailData);
                $res = 200;
                //  http_response_code(400);
                break;
        }
        return $res;
    }
    public function insertWebhookResponse($payload) {
        DB::table('webhook_log_response')->insert(
            ['response' => $payload]
        );
    }
    public function subscriptionHandler($subscription,$payload) {
        $subId = $subscription->subscription;
        $invoice_id = $subscription->id;
        $stripe_cust_id = $subscription->customer;
        $manager = Manager::where('stripe_cust_id', $stripe_cust_id)->first();
        //$plan_in_response = $subscription->plan;
        $plan_in_response = $subscription->lines->data[0]->plan;
        if (!isset($plan_in_response->id)) {
            return 200;
        }
        $plan = SubscriptionPlans::where('stripe_plan_id', $plan_in_response->id)->get()->first();
        $mangerPlandata = ManagerPlan::where(['subscription_id' => $subId,'invoice_id' => $invoice_id])->get()->first();
        if (empty($mangerPlandata) && !empty($plan)) {
            //update status to expired of old plan
            $this->changestatusToExpired($manager, $plan);
            $mangerPlan = new ManagerPlan();
            $mangerPlan->manager_id = $manager->user_id;
            $mangerPlan->plan_id = $plan->id;
            $mangerPlan->status = 'current';
            $mangerPlan->plan_price = $plan->price;
            $mangerPlan->final_price = $plan->price;
            $mangerPlan->stripe_webhook_response = $payload;
            $mangerPlan->subscription_id = $subId;
            $mangerPlan->invoice_id = $invoice_id;
            //$mangerPlan->subscription_id = $subId;
            $mangerPlan->created_at = date('Y-m-d', $subscription->created);
//            $mangerPlan->activated_at = date('Y-m-d', $subscription->current_period_start);
            $mangerPlan->activated_at = date('Y-m-d', $subscription->lines->data[0]->period->start);
//            $mangerPlan->expire_on = date('Y-m-d', $subscription->current_period_end);
            $mangerPlan->expire_on = date('Y-m-d', $subscription->lines->data[0]->period->end);
            $mangerPlan->updated_at = date('Y-m-d H:i:s');

            $user = User::find($manager->user_id);
            $user->plan = $plan->id;
            $user->save();
            $mangerPlan->save();

            $employees = Employee::all()->where('organization_id', $manager->organization_id);
            foreach ($employees as $emp) {
                $emp->plan_expired = $mangerPlan->expire_on ;
                $emp->save();
            }
            $body = EmailTemplate::where('slug', 'PLAN_INVOICE')->first();
            if (!empty($body)) {
                $this->notifyToManager($body, $user, $plan);
            }
            return 200;
        } else {
            return 200;
        }
    }

    public function notifyToManager($body, $user, $plan) {
        $userName = $user->name;
        $userEmail = $user->email;
        $subcriptionPlanName = $plan->name;
        $subcriptionPlanPrice = $plan->price;
        $subcriptionPlanValidity = $plan->validity;

        $organization = Organization::where('user_id', $user->id)->first();
        if ($organization->organization_pic != "") {
            $helperobj = new \App\CommonHelper();
            $docUrl = $helperobj->publicPath();
            $image = $docUrl . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
            if (!file_exists($image)) {
                $image = ANGULARURL . 'assets/img/PU-logo.png';
            } else {
                $image = url() . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
            }
        } else {
            $image = ANGULARURL . 'assets/img/PU-logo.png';
        }

        $tmp1 = str_replace("##USER_NAME##", $userName, $body['description']);
        $tmp2 = str_replace("##PLAN_NAME##", $subcriptionPlanName, $tmp1);
        $tmp3 = str_replace("##PLAN_PRICE##", $subcriptionPlanPrice, $tmp2);
        $tmp4 = str_replace("##PLAN_VALIDITY##", $subcriptionPlanValidity, $tmp3);
        $tmp5 = str_replace("##LOGO##", $image, $tmp4);
        $tmp6 = str_replace("##YEAR##", date('Y'), $tmp5);
        $data['html'] = str_replace("##SUPPORT_LINK##", SUPPORT_LINK, $tmp6);

        $subject = $body['subject'];
        $subject = str_replace("##USER_NAME##", $organization->name, $body['subject']);

        $emailQueue = new EmailQueue();
        $emailQueue->type = TYPE_PLAN_INVOICE;
        $emailQueue->mail_subject = $subject;
        $emailQueue->mail_to = $userEmail;
        $emailQueue->mail_from = FROM_IN_MAIL;
        $emailQueue->mail_body = $data['html'];
        $emailQueue->is_send = 0;
        $date = new \DateTime();
        $ddf = $date->format('Y-m-d H:i:s');
        $emailQueue->created = $ddf;
        $emailQueue->save();
    }

    public function changestatusToExpired($manager, $plan) {
        $currentPlan = ManagerPlan::where('manager_id', $manager->user_id)
                        ->where('plan_id', $plan->id)
                        ->where('status', 'current')
                        ->orderBy('id', 'DESC')->first();

        if ($currentPlan && !empty($currentPlan)) {
            ManagerPlan::where('manager_id', $manager->user_id)
                    ->where('plan_id', $plan->id)
                    ->where('status', 'current')
                    ->update(array(
                        'status' => 'renew',
                        'updated_at' => date('Y-m-d H:i:s'))
            );
        }
    }

    public function sendMail($value) {
        $data['html'] = $value['mail_body'];
        $subject = $value['mail_subject'];
        $email = array('jatin.parmar@brainvire.com','rahul.trivedi@brainvire.com');
        Mail::send('emails.email', $data, function ($message) use ($subject, $email) {
            $message->from(FROM_IN_MAIL, APP_NAME_IN_MAIL);
            $message->to($email);
            $message->subject($subject);
        });
    }

}
