<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
use DateTime;
use DateInterval;
use DatePeriod;
use Auth;
use App\User;
use App\ManagerPlan;

class RenewSycleUserPlans extends Command
{
    protected $signature = 'plan:renewForSycleUser';
    protected $description = 'Renew Sycle User Plan';

    //Path constants

    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle()
    {
        $aboutToExpireUsers = DB::select( "SELECT manager_plans.*, manager_plans.id As managerPrimaryId , manager_plans.expire_on As expiration, users.id, users.name FROM `users` 
                              LEFT JOIN manager_plans ON manager_plans.manager_id = users.id 
                              WHERE `is_auto_renew` = 1 
                              AND manager_plans.`status` = 'current' 
                              AND `subscription_id` IS NULL 
                              AND manager_plans.expire_on = CURDATE()" );
                              
        if(!empty($aboutToExpireUsers)) {
            foreach ($aboutToExpireUsers as $key => $value) {
                //Update records to next 1 Year
                $newExpiryDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($value->expiration)) . " + 1 year"));

                $this->insertRowManagerPlans($value, $newExpiryDate);
                $this->renewExistingPlan($value->managerPrimaryId);
                $this->updateEmployeeExpiration($value->id, $newExpiryDate);

                echo "\n Updated Plan for User.. " . $value->name . "  \n";
            }
        } else {
            echo "\n No plans are about to Expire....  \n";
        }
                               
        $this->updateCronLog();
    }

    public function insertRowManagerPlans($value, $newExpiryDate)
    { 
        $managerPlans = new ManagerPlan();
        $managerPlans->manager_id = $value->manager_id;
        $managerPlans->plan_id = $value->plan_id;
        $managerPlans->plan_price = $value->plan_price;
        $managerPlans->final_price = $value->final_price;
        $managerPlans->promo_discount = $value->promo_discount;
        $managerPlans->status = 'current';
        $managerPlans->no_of_used_users = $value->no_of_used_users;
        $managerPlans->coupon_id = $value->coupon_id;
        $managerPlans->subscription_id = $value->subscription_id;
        $managerPlans->invoice_id = $value->invoice_id;
        $managerPlans->stripe_webhook_response = $value->stripe_webhook_response;
        $managerPlans->activated_at = date('Y-m-d');
        $managerPlans->expire_on = $newExpiryDate;
        $managerPlans->created_at = date('Y-m-d');
        $managerPlans->save();
    }

    public function renewExistingPlan($id)
    {       
        DB::table('manager_plans')->where('id', $id)->update(['status' => 'renew']);
    }

    public function updateEmployeeExpiration($userId, $newExpiryDate)
    { 
        $helperobj = new \App\CommonHelper();
        $organization = $helperobj->getOrganizationIdByUserId($userId);
        if(!empty($organization)) {
            DB::table('employees')->where('organization_id', $organization->id)->update(['plan_expired' => $newExpiryDate]);
        }
    }

    public function updateCronLog()
    {
        $date = date('Y-m-d H:i:s');
        DB::table('cron_log')->where('name', $this->signature)->update(['cron_at' => $date]);
    }
}
