<?php

namespace App\Http\Controllers;

use App\StripePacakge;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Packages;
use App\Excesses;
use App\Subscription;
use Session;
use Illuminate\Support\Facades\Auth;
use App\Repository\PackagesRepository;
use App\Transactions;

class ApplyNowController extends Controller
{

    private $packages;

    public function __construct(PackagesRepository $packages)
    {
        $this->packages = $packages;
    }

    public function save(Request $request)
    {
        $rules = ['package' => 'required', 'type' => 'required', 'excess_id' => 'required'];
        $message = [];
        $input = $request->all();

        $validator = Validator::make($input, $rules, $message);
        $header = 200;
        $response = array();
        $response['errors'] = array();
        $response['error'] = false;
        $response['url'] = "";
        
        if (!empty(auth('customers')->user())) {
            $stripe_plan = 'plan-' . $input['package'] . '-' . $input['type'] . '-' . $input['excess_id'];            
            $subscription_count = Transactions::where('customer_id', auth('customers')->user()->id)->where('package_id', $input['package'])->where('excess_id', $input['excess_id'])->where('type', $input['type'])->count();         
            if ($subscription_count > 0) {
                $response['errors']['message'] = 'Already have subscrition with this plan. You want to upgrade or downgrade choose other plan';
                $response['status'] = false;
                $response['error'] = true;
            } else {
                $model = Packages::where("id", $request->package)->first();
                $package = $this->packages->setPackage($model);
                $error = false;
                if ($package["customizable"] == 1 && $input["type"] == "yearly") {
                    $error = true;
                    if ($package["category_code"] == "home-care") {
                        $validator->errors()->add('error', 'Please note, the Your Flo package can only be purchased on a rolling monthly basis. Please select the per month option to proceed.');
                    } else {
                        $validator->errors()->add('error', 'Please note, the Landlord Your Flo package can only be purchased on a rolling monthly basis. Please click on the monthly button to proceed.');
                    }
                }

                $errors = $validator->errors();
                if ($validator->fails() || $error == true) {
                    $response['errors'] = $errors;
                    $response['error'] = true;
                    $header = 402;
                    //return redirect()->back()->withErrors($validator->errors())->withInput();
                } else {
                    $response = $this->validatePackages($request, $package, $model);
                    $response['message'] = 'You have subscription already want to upgrade or downgrade subscription package';
                }
                Session::put('message', $response['message']);
            }
        } else {
            $model = Packages::where("id", $request->package)->first();
            $package = $this->packages->setPackage($model);
            $error = false;
            if ($package["customizable"] == 1 && $input["type"] == "yearly") {
                $error = true;
                if ($package["category_code"] == "home-care") {
                    $validator->errors()->add('error', 'Please note, the Your Flo package can only be purchased on a rolling monthly basis. Please select the per month option to proceed.');
                } else {
                    $validator->errors()->add('error', 'Please note, the Landlord Your Flo package can only be purchased on a rolling monthly basis. Please click on the monthly button to proceed.');
                }
            }
            
            $errors = $validator->errors();
            if ($validator->fails() || $error == true) {
                $response['errors'] = $errors;
                $response['error'] = true;
                $header = 402;
                //return redirect()->back()->withErrors($validator->errors())->withInput();
            } else {
                $response = $this->validatePackages($request, $package, $model);
            }
        }
        return response()->json($response, $header);
    }

    public function validatePackages($request, $package, $model)
    {
        $facilities = $request->facilities;
        if ($package["customizable"] == 1) {
            foreach ($package["default_facilities"] as $default) {
                $facilities[] = $default->facility_id;
            }
            $title = env("CURRENCY_SYMBOL") . "0";
            $excess = Excesses::where("title", $title)->first();
            if (!empty($excess)) {
                Session::put('excess_id', $excess->id);
            } else {
                Session::put('excess_id', 1);
            }
        } else {
            Session::put('excess_id', $request->excess_id);
        }
        Session::put('package', $request->package);
        Session::put('type', $request->type);
        Session::put('facilities', $facilities);

        $response["status"] = true;
        $response["excess_id"] = Session::get('excess_id');
        $response["type"] = Session::get('type');
        $response["package"] = Session::get('package');
        $response["facilities"] = Session::get('facilities');
        $response['url'] = url("checkout");

        return $response;
    }
}