<?php
namespace App\Cron;

use App\User;
use App\Models\UserBusiness;
use App\Services\HTMLHelper;
use App\Models\UserCreditItem;
use App\Repositories\CreditRepository;
use App\Mail\MailCustomMessage;
use App\Mail\MailVerifyAccount;
use App\Models\UserHistory;
use App\Models\UserMessage;
use Carbon;
use Illuminate\Support\Facades\Mail;

class UserCheckPaymentsAccounts
{

    /*RULES
            reminders
                > 29 renewal_days > set next_m_level to m_level
                > 29 renewal_days $user->user_level->payment_year = 0 / false + 1 year

                > 21 remind_first_days = reminder_first //status 31
                > 14 remind_sec_days = reminder_sec //status 33
                > 2 remind_last_days =  reminder_last //status 34
                > 0 deaktiv = reminder_deaktiv  //status 35
    */

    public static function userReminderPayments(User $user, $dev){
        //35 reminder_deaktiv
        if(!$user->isActiveAccount()){ // payment_account gt now
            return self::checkIsReminderSend($user, 35, $dev);
        }
        //34 reminder_last
        if($user->daysActiveAccount() <= config('main.remind_last_days')){
            return self::checkIsReminderSend($user, 34, $dev);
        }
        //33 reminder_sec
        if($user->daysActiveAccount() <= config('main.remind_sec_days')){
            return self::checkIsReminderSend($user, 33, $dev);
        }
        //31 reminder_first
        if($user->daysActiveAccount() > config('main.remind_sec_days')){
            return self::checkIsReminderSend($user, 31, $dev);
        }
        return 0;
    }


    private static function checkIsReminderSend(User $user,  $status, $dev){

        $isSend = UserHistory::whereUserId($user->id)
                ->whereAction('reminder_payments')
                ->whereIdentifier($user->payment_account)
                ->whereStatus($status)
                ->get()->last();

        if($isSend){
            return 0;
        }
        if($dev){
            $referenz = 0;
        }else{
            $referenz = self::sendReminderMail($user, $status);
        }
        UserHistory::create(['user_id' => $user->id, 'action'=>'reminder_payments', 'referenz'=>$referenz, 'identifier'=>$user->payment_account, 'status'=>$status]);
        return $status;

    }

    private function sendReminderMail(User $user, $status){

        $days = $user->daysActiveAccount();
        if($days < 0){
            $days = $days*-1;
        }
        $datetime = $user->getPaymentAccountDateFormat();

        $pay_date = 0;
        $price = 0;
        /*$pay_date = Carbon::parse($user->payment_account)->modify('- '.config('main.abo_booking_days').' days')->format('d.m.Y');
        $price = "";
        if($user->payment_order_id && isset($user->payment_order_product->price)){
            $price = 'von '.$user->payment_order_product->getFormattedPrice().' EUR';
        }*/

        $message = __('reminder.copy_first_'.$status, ['days'=>$days, 'datetime'=>$datetime, 'price' =>$price, 'pay_date'=>$pay_date]);
        $message_last = __('reminder.copy_last_'.$status, ['days'=>$days, 'datetime'=>$datetime, 'price' =>$price, 'pay_date'=>$pay_date]);
        $button = __('reminder.button_'.$status);

        $message = preg_replace("/[\n\r]/","",$message);
        $message_last = preg_replace("/[\n\r]/","",$message_last);

        $data = [
            'subject' => __('reminder.subject')." | ID: ".$status,
            'message' => $message,
            'message_last' => $message_last,
            'url' => route('user_membership'),
            'button' => $button,
        ];
        //dump($data);
        $sender = User::find(1);
        $customer_mail = UserMessage::create([
            'user_id' =>  $user->id,
            'send_user_id' => $sender->id,
            'email' => $user->email,
            'subject' => $data['subject'],
            'message' => $data['message']." ".$data['message_last'],
        ]);
        try{
            if($status >= 34){
                //Mail::to($user->email)->bcc(config('app.info_mail'))->send(new MailCustomMessage($user, $data, $sender, false));
            }else{
                //Mail::to($user->email)->send(new MailCustomMessage($user, $data, $sender, false));
            }
        }
        catch(\Exception $e){
            \Log::channel('cron')->error('Mail Error: '.$e->getMessage());
            // Never reached
            $customer_mail->fail = true;
            $customer_mail->error = $e->getMessage();
            $customer_mail->save();
            return 0;
        }
        $customer_mail->send = true;
        $customer_mail->sent_at = now();
        $customer_mail->save();
        return 1;
    }

}


      /*public function checkConfirmation()
        {
                    User Register sind in der DB UserRegister, erst bei bestätigung wird es in die User DB übertragen

            $now = date('Y-m-d H:i:s');
            $next = date('Y-m-d H:i:s', strtotime('+3 week'));
    
            $users = User::where('confirmed', '=', 0)->where('confirmation_code_to', '<', $now)->get();
    
            foreach ($users as $user) {
    
                //delete user
                if ($user->confirmation_code_remider == 1) {
                    $this->userRepo->deleteUser($user);
    
                }
                //send new remider
                if ($user->confirmation_code_remider == 0) {
                    Mail::to($user->email)->bcc(config('app.info_mail'))->send(new MailVerifyAccount($user->confirmation_code, $user));
                    $user->confirmation_code_to = $next;
                    $user->confirmation_code_remider = 1;
                    $user->save();
                }
            }
            return "TOSK";
        }*/

