<?php

namespace App\Http\Controllers;

use App\Mail\MailCustomMessage;
use App\Mail\MailVerifyAccount;
use App\Models\UserHistory;
use App\Models\UserMessage;
use App\Repositories\UserRepository;
use App\User;
use Carbon;
use Illuminate\Support\Facades\Mail;


class CronController extends Controller
{


    protected $userRepo;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(UserRepository $userRepo)
    {
        $this->userRepo = $userRepo;

        // $this->middleware('auth');
    }

    public function index()
    {
        //$this->checkConfirmation();
        //TODO
        //SEPA Booking
        //Mail reminder
    }

    public function action($action = false, $key = false){

        if($key !== 'key'){
            abort(404);
        }
        if($action === 'check_payments_account'){
            $this->checkPaymentsAccounts();
        }
    }
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function checkConfirmation()
    {
        $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)->send(new MailVerifyAccount($user->confirmation_code, $user));
                $user->confirmation_code_to = $next;
                $user->confirmation_code_remider = 1;
                $user->save();
            }
        }
        return "TOSK";
    }

    public function checkPaymentsAccounts(){

        /*RULES
           reminders
                > 21 remind_first_days = 31 reminder_first
                > 21 remind_first_days + sepa = 32 reminder_first_sepa
                > 14 remind_sec_days = 33 reminder_sec
                > 2 remind_last_days = 34 reminder_last
                > 0 deaktiv = 35 reminder_deaktiv
                > 0 deaktiv + sepa = 36 reminder_deaktiv_sepa
                == 7 abo_booking_days + sepa + cron = 37 reminder_collect_sepa
        */
        //max Date for reminder
        $renewalDate = Carbon::now()->modify('+'.(config('main.remind_first_days')+1).' days');
        //dump($renewalDate);
        $users = User::where('payment_account', '!=', NULL)
                ->where('active', '=', 1)
                ->where('blocked', '!=', 1)
                ->where('payment_account', '<', $renewalDate)
                ->get();

       /* $user = User::find(2);
        $this->checkReminderPayments($user);
        dump($user->daysActiveAccount());
        dump($user->email." | ".$user->getPaymentAccountDateFormat());
        die();*/
        foreach ($users as $user){
            $this->checkReminderPayments($user);
            /*dump($user->daysActiveAccount());
            dump($user->email." | ".$user->getPaymentAccountDateFormat());
            dump('-------------------');*/
        }
        return "TOSK";
    }


    private function checkReminderPayments(User $user){

       /* $isSend = $this->checkIsReminderSend($user, 31);
        $isSend = $this->checkIsReminderSend($user, 32);
        $isSend = $this->checkIsReminderSend($user, 33);
        $isSend = $this->checkIsReminderSend($user, 34);
        $isSend = $this->checkIsReminderSend($user, 35);
        $isSend = $this->checkIsReminderSend($user, 36);
        return ;*/

        //35 reminder_deaktiv, 36 reminder_deaktiv_sepa
        if(!$user->isActiveAccount()){
            if($user->isAboOption()){
                $isSend = $this->checkIsReminderSend($user, 35);
                return $isSend;
            }
            $isSend = $this->checkIsReminderSend($user, 36);
            return $isSend;
        }

        //34 reminder_last
        if($user->daysActiveAccount() <= config('main.remind_last_days')){
            $isSend = $this->checkIsReminderSend($user, 34);
            return $isSend;
        }

        //33 reminder_sec
        if($user->daysActiveAccount() <= config('main.remind_sec_days')){
            if(!$user->isAboOption()){
                $isSend = $this->checkIsReminderSend($user, 33);
                return $isSend;
            }
        }

        //31 reminder_first, 32 reminder_first_sepa
        if($user->daysActiveAccount() > config('main.remind_sec_days')){
            if($user->isAboOption()){
                $isSend = $this->checkIsReminderSend($user, 32);
                return $isSend;
            }
            $isSend = $this->checkIsReminderSend($user, 31);
            return $isSend;
        }
    }


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

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

        if($isSend){
            return true;
        }
        $referenz = $this->sendReminderMail($user, $status);
        //is not sent create
        UserHistory::create(['user_id' => $user->id, 'action'=>'reminder_payments', 'referenz'=>$referenz, 'identifier'=>$user->payment_account, 'status'=>$status]);
        return false;

    }

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

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

        //dump($days);
        //dump($status);
        $pay_date = Carbon::parse($user->payment_account)->modify('- '.config('main.abo_booking_days').' days')->format('d.m.Y');
        $datetime = $user->getPaymentAccountDateFormat();
        $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.default_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;
    }

}